sqlite3.c 4.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.8.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. #ifndef SQLITE_API
  26. # define SQLITE_API
  27. #endif
  28. /************** Begin file sqlite3.h *****************************************/
  29. /*
  30. ** 2001 September 15
  31. **
  32. ** The author disclaims copyright to this source code. In place of
  33. ** a legal notice, here is a blessing:
  34. **
  35. ** May you do good and not evil.
  36. ** May you find forgiveness for yourself and forgive others.
  37. ** May you share freely, never taking more than you give.
  38. **
  39. *************************************************************************
  40. ** This header file defines the interface that the SQLite library
  41. ** presents to client programs. If a C-function, structure, datatype,
  42. ** or constant definition does not appear in this file, then it is
  43. ** not a published API of SQLite, is subject to change without
  44. ** notice, and should not be referenced by programs that use SQLite.
  45. **
  46. ** Some of the definitions that are in this file are marked as
  47. ** "experimental". Experimental interfaces are normally new
  48. ** features recently added to SQLite. We do not anticipate changes
  49. ** to experimental interfaces but reserve the right to make minor changes
  50. ** if experience from use "in the wild" suggest such changes are prudent.
  51. **
  52. ** The official C-language API documentation for SQLite is derived
  53. ** from comments in this file. This file is the authoritative source
  54. ** on how SQLite interfaces are suppose to operate.
  55. **
  56. ** The name of this file under configuration management is "sqlite.h.in".
  57. ** The makefile makes some minor changes to this file (such as inserting
  58. ** the version number) and changes its name to "sqlite3.h" as
  59. ** part of the build process.
  60. */
  61. #ifndef _SQLITE3_H_
  62. #define _SQLITE3_H_
  63. #include <stdarg.h> /* Needed for the definition of va_list */
  64. /*
  65. ** Make sure we can call this stuff from C++.
  66. */
  67. #if 0
  68. extern "C" {
  69. #endif
  70. /*
  71. ** Add the ability to override 'extern'
  72. */
  73. #ifndef SQLITE_EXTERN
  74. # define SQLITE_EXTERN extern
  75. #endif
  76. #ifndef SQLITE_API
  77. # define SQLITE_API
  78. #endif
  79. /*
  80. ** These no-op macros are used in front of interfaces to mark those
  81. ** interfaces as either deprecated or experimental. New applications
  82. ** should not use deprecated interfaces - they are support for backwards
  83. ** compatibility only. Application writers should be aware that
  84. ** experimental interfaces are subject to change in point releases.
  85. **
  86. ** These macros used to resolve to various kinds of compiler magic that
  87. ** would generate warning messages when they were used. But that
  88. ** compiler magic ended up generating such a flurry of bug reports
  89. ** that we have taken it all out and gone back to using simple
  90. ** noop macros.
  91. */
  92. #define SQLITE_DEPRECATED
  93. #define SQLITE_EXPERIMENTAL
  94. /*
  95. ** Ensure these symbols were not defined by some previous header file.
  96. */
  97. #ifdef SQLITE_VERSION
  98. # undef SQLITE_VERSION
  99. #endif
  100. #ifdef SQLITE_VERSION_NUMBER
  101. # undef SQLITE_VERSION_NUMBER
  102. #endif
  103. /*
  104. ** CAPI3REF: Compile-Time Library Version Numbers
  105. **
  106. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  107. ** evaluates to a string literal that is the SQLite version in the
  108. ** format "X.Y.Z" where X is the major version number (always 3 for
  109. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  110. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  111. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  112. ** numbers used in [SQLITE_VERSION].)^
  113. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  114. ** be larger than the release from which it is derived. Either Y will
  115. ** be held constant and Z will be incremented or else Y will be incremented
  116. ** and Z will be reset to zero.
  117. **
  118. ** Since version 3.6.18, SQLite source code has been stored in the
  119. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  120. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  121. ** a string which identifies a particular check-in of SQLite
  122. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  123. ** string contains the date and time of the check-in (UTC) and an SHA1
  124. ** hash of the entire source tree.
  125. **
  126. ** See also: [sqlite3_libversion()],
  127. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  128. ** [sqlite_version()] and [sqlite_source_id()].
  129. */
  130. #define SQLITE_VERSION "3.8.1"
  131. #define SQLITE_VERSION_NUMBER 3008001
  132. #define SQLITE_SOURCE_ID "2013-10-17 12:57:35 c78be6d786c19073b3a6730dfe3fb1be54f5657a"
  133. /*
  134. ** CAPI3REF: Run-Time Library Version Numbers
  135. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  136. **
  137. ** These interfaces provide the same information as the [SQLITE_VERSION],
  138. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  139. ** but are associated with the library instead of the header file. ^(Cautious
  140. ** programmers might include assert() statements in their application to
  141. ** verify that values returned by these interfaces match the macros in
  142. ** the header, and thus insure that the application is
  143. ** compiled with matching library and header files.
  144. **
  145. ** <blockquote><pre>
  146. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  147. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  148. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  149. ** </pre></blockquote>)^
  150. **
  151. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  152. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  153. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  154. ** function is provided for use in DLLs since DLL users usually do not have
  155. ** direct access to string constants within the DLL. ^The
  156. ** sqlite3_libversion_number() function returns an integer equal to
  157. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  158. ** a pointer to a string constant whose value is the same as the
  159. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  160. **
  161. ** See also: [sqlite_version()] and [sqlite_source_id()].
  162. */
  163. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  164. SQLITE_API const char *sqlite3_libversion(void);
  165. SQLITE_API const char *sqlite3_sourceid(void);
  166. SQLITE_API int sqlite3_libversion_number(void);
  167. /*
  168. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  169. **
  170. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  171. ** indicating whether the specified option was defined at
  172. ** compile time. ^The SQLITE_ prefix may be omitted from the
  173. ** option name passed to sqlite3_compileoption_used().
  174. **
  175. ** ^The sqlite3_compileoption_get() function allows iterating
  176. ** over the list of options that were defined at compile time by
  177. ** returning the N-th compile time option string. ^If N is out of range,
  178. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  179. ** prefix is omitted from any strings returned by
  180. ** sqlite3_compileoption_get().
  181. **
  182. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  183. ** and sqlite3_compileoption_get() may be omitted by specifying the
  184. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  185. **
  186. ** See also: SQL functions [sqlite_compileoption_used()] and
  187. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  188. */
  189. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  190. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  191. SQLITE_API const char *sqlite3_compileoption_get(int N);
  192. #endif
  193. /*
  194. ** CAPI3REF: Test To See If The Library Is Threadsafe
  195. **
  196. ** ^The sqlite3_threadsafe() function returns zero if and only if
  197. ** SQLite was compiled with mutexing code omitted due to the
  198. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  199. **
  200. ** SQLite can be compiled with or without mutexes. When
  201. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  202. ** are enabled and SQLite is threadsafe. When the
  203. ** [SQLITE_THREADSAFE] macro is 0,
  204. ** the mutexes are omitted. Without the mutexes, it is not safe
  205. ** to use SQLite concurrently from more than one thread.
  206. **
  207. ** Enabling mutexes incurs a measurable performance penalty.
  208. ** So if speed is of utmost importance, it makes sense to disable
  209. ** the mutexes. But for maximum safety, mutexes should be enabled.
  210. ** ^The default behavior is for mutexes to be enabled.
  211. **
  212. ** This interface can be used by an application to make sure that the
  213. ** version of SQLite that it is linking against was compiled with
  214. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  215. **
  216. ** This interface only reports on the compile-time mutex setting
  217. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  218. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  219. ** can be fully or partially disabled using a call to [sqlite3_config()]
  220. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  221. ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
  222. ** sqlite3_threadsafe() function shows only the compile-time setting of
  223. ** thread safety, not any run-time changes to that setting made by
  224. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  225. ** is unchanged by calls to sqlite3_config().)^
  226. **
  227. ** See the [threading mode] documentation for additional information.
  228. */
  229. SQLITE_API int sqlite3_threadsafe(void);
  230. /*
  231. ** CAPI3REF: Database Connection Handle
  232. ** KEYWORDS: {database connection} {database connections}
  233. **
  234. ** Each open SQLite database is represented by a pointer to an instance of
  235. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  236. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  237. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  238. ** and [sqlite3_close_v2()] are its destructors. There are many other
  239. ** interfaces (such as
  240. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  241. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  242. ** sqlite3 object.
  243. */
  244. typedef struct sqlite3 sqlite3;
  245. /*
  246. ** CAPI3REF: 64-Bit Integer Types
  247. ** KEYWORDS: sqlite_int64 sqlite_uint64
  248. **
  249. ** Because there is no cross-platform way to specify 64-bit integer types
  250. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  251. **
  252. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  253. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  254. ** compatibility only.
  255. **
  256. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  257. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  258. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  259. ** between 0 and +18446744073709551615 inclusive.
  260. */
  261. #ifdef SQLITE_INT64_TYPE
  262. typedef SQLITE_INT64_TYPE sqlite_int64;
  263. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  264. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  265. typedef __int64 sqlite_int64;
  266. typedef unsigned __int64 sqlite_uint64;
  267. #else
  268. typedef long long int sqlite_int64;
  269. typedef unsigned long long int sqlite_uint64;
  270. #endif
  271. typedef sqlite_int64 sqlite3_int64;
  272. typedef sqlite_uint64 sqlite3_uint64;
  273. /*
  274. ** If compiling for a processor that lacks floating point support,
  275. ** substitute integer for floating-point.
  276. */
  277. #ifdef SQLITE_OMIT_FLOATING_POINT
  278. # define double sqlite3_int64
  279. #endif
  280. /*
  281. ** CAPI3REF: Closing A Database Connection
  282. **
  283. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  284. ** for the [sqlite3] object.
  285. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
  286. ** the [sqlite3] object is successfully destroyed and all associated
  287. ** resources are deallocated.
  288. **
  289. ** ^If the database connection is associated with unfinalized prepared
  290. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  291. ** will leave the database connection open and return [SQLITE_BUSY].
  292. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  293. ** and unfinished sqlite3_backups, then the database connection becomes
  294. ** an unusable "zombie" which will automatically be deallocated when the
  295. ** last prepared statement is finalized or the last sqlite3_backup is
  296. ** finished. The sqlite3_close_v2() interface is intended for use with
  297. ** host languages that are garbage collected, and where the order in which
  298. ** destructors are called is arbitrary.
  299. **
  300. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  301. ** [sqlite3_blob_close | close] all [BLOB handles], and
  302. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  303. ** with the [sqlite3] object prior to attempting to close the object. ^If
  304. ** sqlite3_close_v2() is called on a [database connection] that still has
  305. ** outstanding [prepared statements], [BLOB handles], and/or
  306. ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
  307. ** of resources is deferred until all [prepared statements], [BLOB handles],
  308. ** and [sqlite3_backup] objects are also destroyed.
  309. **
  310. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  311. ** the transaction is automatically rolled back.
  312. **
  313. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  314. ** must be either a NULL
  315. ** pointer or an [sqlite3] object pointer obtained
  316. ** from [sqlite3_open()], [sqlite3_open16()], or
  317. ** [sqlite3_open_v2()], and not previously closed.
  318. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  319. ** argument is a harmless no-op.
  320. */
  321. SQLITE_API int sqlite3_close(sqlite3*);
  322. SQLITE_API int sqlite3_close_v2(sqlite3*);
  323. /*
  324. ** The type for a callback function.
  325. ** This is legacy and deprecated. It is included for historical
  326. ** compatibility and is not documented.
  327. */
  328. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  329. /*
  330. ** CAPI3REF: One-Step Query Execution Interface
  331. **
  332. ** The sqlite3_exec() interface is a convenience wrapper around
  333. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  334. ** that allows an application to run multiple statements of SQL
  335. ** without having to use a lot of C code.
  336. **
  337. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  338. ** semicolon-separate SQL statements passed into its 2nd argument,
  339. ** in the context of the [database connection] passed in as its 1st
  340. ** argument. ^If the callback function of the 3rd argument to
  341. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  342. ** coming out of the evaluated SQL statements. ^The 4th argument to
  343. ** sqlite3_exec() is relayed through to the 1st argument of each
  344. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  345. ** is NULL, then no callback is ever invoked and result rows are
  346. ** ignored.
  347. **
  348. ** ^If an error occurs while evaluating the SQL statements passed into
  349. ** sqlite3_exec(), then execution of the current statement stops and
  350. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  351. ** is not NULL then any error message is written into memory obtained
  352. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  353. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  354. ** on error message strings returned through the 5th parameter of
  355. ** of sqlite3_exec() after the error message string is no longer needed.
  356. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  357. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  358. ** NULL before returning.
  359. **
  360. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  361. ** routine returns SQLITE_ABORT without invoking the callback again and
  362. ** without running any subsequent SQL statements.
  363. **
  364. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  365. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  366. ** callback is an array of pointers to strings obtained as if from
  367. ** [sqlite3_column_text()], one for each column. ^If an element of a
  368. ** result row is NULL then the corresponding string pointer for the
  369. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  370. ** sqlite3_exec() callback is an array of pointers to strings where each
  371. ** entry represents the name of corresponding result column as obtained
  372. ** from [sqlite3_column_name()].
  373. **
  374. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  375. ** to an empty string, or a pointer that contains only whitespace and/or
  376. ** SQL comments, then no SQL statements are evaluated and the database
  377. ** is not changed.
  378. **
  379. ** Restrictions:
  380. **
  381. ** <ul>
  382. ** <li> The application must insure that the 1st parameter to sqlite3_exec()
  383. ** is a valid and open [database connection].
  384. ** <li> The application must not close [database connection] specified by
  385. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  386. ** <li> The application must not modify the SQL statement text passed into
  387. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  388. ** </ul>
  389. */
  390. SQLITE_API int sqlite3_exec(
  391. sqlite3*, /* An open database */
  392. const char *sql, /* SQL to be evaluated */
  393. int (*callback)(void*,int,char**,char**), /* Callback function */
  394. void *, /* 1st argument to callback */
  395. char **errmsg /* Error msg written here */
  396. );
  397. /*
  398. ** CAPI3REF: Result Codes
  399. ** KEYWORDS: SQLITE_OK {error code} {error codes}
  400. ** KEYWORDS: {result code} {result codes}
  401. **
  402. ** Many SQLite functions return an integer result code from the set shown
  403. ** here in order to indicate success or failure.
  404. **
  405. ** New error codes may be added in future versions of SQLite.
  406. **
  407. ** See also: [SQLITE_IOERR_READ | extended result codes],
  408. ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
  409. */
  410. #define SQLITE_OK 0 /* Successful result */
  411. /* beginning-of-error-codes */
  412. #define SQLITE_ERROR 1 /* SQL error or missing database */
  413. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  414. #define SQLITE_PERM 3 /* Access permission denied */
  415. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  416. #define SQLITE_BUSY 5 /* The database file is locked */
  417. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  418. #define SQLITE_NOMEM 7 /* A malloc() failed */
  419. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  420. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  421. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  422. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  423. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  424. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  425. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  426. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  427. #define SQLITE_EMPTY 16 /* Database is empty */
  428. #define SQLITE_SCHEMA 17 /* The database schema changed */
  429. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  430. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  431. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  432. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  433. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  434. #define SQLITE_AUTH 23 /* Authorization denied */
  435. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  436. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  437. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  438. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  439. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  440. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  441. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  442. /* end-of-error-codes */
  443. /*
  444. ** CAPI3REF: Extended Result Codes
  445. ** KEYWORDS: {extended error code} {extended error codes}
  446. ** KEYWORDS: {extended result code} {extended result codes}
  447. **
  448. ** In its default configuration, SQLite API routines return one of 26 integer
  449. ** [SQLITE_OK | result codes]. However, experience has shown that many of
  450. ** these result codes are too coarse-grained. They do not provide as
  451. ** much information about problems as programmers might like. In an effort to
  452. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  453. ** support for additional result codes that provide more detailed information
  454. ** about errors. The extended result codes are enabled or disabled
  455. ** on a per database connection basis using the
  456. ** [sqlite3_extended_result_codes()] API.
  457. **
  458. ** Some of the available extended result codes are listed here.
  459. ** One may expect the number of extended result codes will be expand
  460. ** over time. Software that uses extended result codes should expect
  461. ** to see new result codes in future releases of SQLite.
  462. **
  463. ** The SQLITE_OK result code will never be extended. It will always
  464. ** be exactly zero.
  465. */
  466. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  467. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  468. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  469. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  470. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  471. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  472. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  473. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  474. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  475. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  476. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  477. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  478. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  479. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  480. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  481. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  482. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  483. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  484. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  485. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  486. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  487. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  488. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  489. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  490. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  491. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  492. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  493. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  494. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  495. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  496. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  497. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  498. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  499. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  500. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  501. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  502. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  503. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  504. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  505. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  506. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  507. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  508. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  509. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  510. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  511. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  512. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  513. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  514. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  515. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  516. /*
  517. ** CAPI3REF: Flags For File Open Operations
  518. **
  519. ** These bit values are intended for use in the
  520. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  521. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  522. */
  523. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  524. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  525. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  526. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  527. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  528. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  529. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  530. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  531. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  532. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  533. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  534. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  535. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  536. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  537. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  538. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  539. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  540. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  541. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  542. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  543. /* Reserved: 0x00F00000 */
  544. /*
  545. ** CAPI3REF: Device Characteristics
  546. **
  547. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  548. ** object returns an integer which is a vector of these
  549. ** bit values expressing I/O characteristics of the mass storage
  550. ** device that holds the file that the [sqlite3_io_methods]
  551. ** refers to.
  552. **
  553. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  554. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  555. ** mean that writes of blocks that are nnn bytes in size and
  556. ** are aligned to an address which is an integer multiple of
  557. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  558. ** that when data is appended to a file, the data is appended
  559. ** first then the size of the file is extended, never the other
  560. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  561. ** information is written to disk in the same order as calls
  562. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  563. ** after reboot following a crash or power loss, the only bytes in a
  564. ** file that were written at the application level might have changed
  565. ** and that adjacent bytes, even bytes within the same sector are
  566. ** guaranteed to be unchanged.
  567. */
  568. #define SQLITE_IOCAP_ATOMIC 0x00000001
  569. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  570. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  571. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  572. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  573. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  574. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  575. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  576. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  577. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  578. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  579. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  580. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  581. /*
  582. ** CAPI3REF: File Locking Levels
  583. **
  584. ** SQLite uses one of these integer values as the second
  585. ** argument to calls it makes to the xLock() and xUnlock() methods
  586. ** of an [sqlite3_io_methods] object.
  587. */
  588. #define SQLITE_LOCK_NONE 0
  589. #define SQLITE_LOCK_SHARED 1
  590. #define SQLITE_LOCK_RESERVED 2
  591. #define SQLITE_LOCK_PENDING 3
  592. #define SQLITE_LOCK_EXCLUSIVE 4
  593. /*
  594. ** CAPI3REF: Synchronization Type Flags
  595. **
  596. ** When SQLite invokes the xSync() method of an
  597. ** [sqlite3_io_methods] object it uses a combination of
  598. ** these integer values as the second argument.
  599. **
  600. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  601. ** sync operation only needs to flush data to mass storage. Inode
  602. ** information need not be flushed. If the lower four bits of the flag
  603. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  604. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  605. ** to use Mac OS X style fullsync instead of fsync().
  606. **
  607. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  608. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  609. ** settings. The [synchronous pragma] determines when calls to the
  610. ** xSync VFS method occur and applies uniformly across all platforms.
  611. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  612. ** energetic or rigorous or forceful the sync operations are and
  613. ** only make a difference on Mac OSX for the default SQLite code.
  614. ** (Third-party VFS implementations might also make the distinction
  615. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  616. ** operating systems natively supported by SQLite, only Mac OSX
  617. ** cares about the difference.)
  618. */
  619. #define SQLITE_SYNC_NORMAL 0x00002
  620. #define SQLITE_SYNC_FULL 0x00003
  621. #define SQLITE_SYNC_DATAONLY 0x00010
  622. /*
  623. ** CAPI3REF: OS Interface Open File Handle
  624. **
  625. ** An [sqlite3_file] object represents an open file in the
  626. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  627. ** implementations will
  628. ** want to subclass this object by appending additional fields
  629. ** for their own use. The pMethods entry is a pointer to an
  630. ** [sqlite3_io_methods] object that defines methods for performing
  631. ** I/O operations on the open file.
  632. */
  633. typedef struct sqlite3_file sqlite3_file;
  634. struct sqlite3_file {
  635. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  636. };
  637. /*
  638. ** CAPI3REF: OS Interface File Virtual Methods Object
  639. **
  640. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  641. ** [sqlite3_file] object (or, more commonly, a subclass of the
  642. ** [sqlite3_file] object) with a pointer to an instance of this object.
  643. ** This object defines the methods used to perform various operations
  644. ** against the open file represented by the [sqlite3_file] object.
  645. **
  646. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  647. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  648. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  649. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  650. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  651. ** to NULL.
  652. **
  653. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  654. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  655. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  656. ** flag may be ORed in to indicate that only the data of the file
  657. ** and not its inode needs to be synced.
  658. **
  659. ** The integer values to xLock() and xUnlock() are one of
  660. ** <ul>
  661. ** <li> [SQLITE_LOCK_NONE],
  662. ** <li> [SQLITE_LOCK_SHARED],
  663. ** <li> [SQLITE_LOCK_RESERVED],
  664. ** <li> [SQLITE_LOCK_PENDING], or
  665. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  666. ** </ul>
  667. ** xLock() increases the lock. xUnlock() decreases the lock.
  668. ** The xCheckReservedLock() method checks whether any database connection,
  669. ** either in this process or in some other process, is holding a RESERVED,
  670. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  671. ** if such a lock exists and false otherwise.
  672. **
  673. ** The xFileControl() method is a generic interface that allows custom
  674. ** VFS implementations to directly control an open file using the
  675. ** [sqlite3_file_control()] interface. The second "op" argument is an
  676. ** integer opcode. The third argument is a generic pointer intended to
  677. ** point to a structure that may contain arguments or space in which to
  678. ** write return values. Potential uses for xFileControl() might be
  679. ** functions to enable blocking locks with timeouts, to change the
  680. ** locking strategy (for example to use dot-file locks), to inquire
  681. ** about the status of a lock, or to break stale locks. The SQLite
  682. ** core reserves all opcodes less than 100 for its own use.
  683. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
  684. ** Applications that define a custom xFileControl method should use opcodes
  685. ** greater than 100 to avoid conflicts. VFS implementations should
  686. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  687. ** recognize.
  688. **
  689. ** The xSectorSize() method returns the sector size of the
  690. ** device that underlies the file. The sector size is the
  691. ** minimum write that can be performed without disturbing
  692. ** other bytes in the file. The xDeviceCharacteristics()
  693. ** method returns a bit vector describing behaviors of the
  694. ** underlying device:
  695. **
  696. ** <ul>
  697. ** <li> [SQLITE_IOCAP_ATOMIC]
  698. ** <li> [SQLITE_IOCAP_ATOMIC512]
  699. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  700. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  701. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  702. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  703. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  704. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  705. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  706. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  707. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  708. ** </ul>
  709. **
  710. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  711. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  712. ** mean that writes of blocks that are nnn bytes in size and
  713. ** are aligned to an address which is an integer multiple of
  714. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  715. ** that when data is appended to a file, the data is appended
  716. ** first then the size of the file is extended, never the other
  717. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  718. ** information is written to disk in the same order as calls
  719. ** to xWrite().
  720. **
  721. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  722. ** in the unread portions of the buffer with zeros. A VFS that
  723. ** fails to zero-fill short reads might seem to work. However,
  724. ** failure to zero-fill short reads will eventually lead to
  725. ** database corruption.
  726. */
  727. typedef struct sqlite3_io_methods sqlite3_io_methods;
  728. struct sqlite3_io_methods {
  729. int iVersion;
  730. int (*xClose)(sqlite3_file*);
  731. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  732. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  733. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  734. int (*xSync)(sqlite3_file*, int flags);
  735. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  736. int (*xLock)(sqlite3_file*, int);
  737. int (*xUnlock)(sqlite3_file*, int);
  738. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  739. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  740. int (*xSectorSize)(sqlite3_file*);
  741. int (*xDeviceCharacteristics)(sqlite3_file*);
  742. /* Methods above are valid for version 1 */
  743. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  744. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  745. void (*xShmBarrier)(sqlite3_file*);
  746. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  747. /* Methods above are valid for version 2 */
  748. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  749. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  750. /* Methods above are valid for version 3 */
  751. /* Additional methods may be added in future releases */
  752. };
  753. /*
  754. ** CAPI3REF: Standard File Control Opcodes
  755. **
  756. ** These integer constants are opcodes for the xFileControl method
  757. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  758. ** interface.
  759. **
  760. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  761. ** opcode causes the xFileControl method to write the current state of
  762. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  763. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  764. ** into an integer that the pArg argument points to. This capability
  765. ** is used during testing and only needs to be supported when SQLITE_TEST
  766. ** is defined.
  767. ** <ul>
  768. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  769. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  770. ** layer a hint of how large the database file will grow to be during the
  771. ** current transaction. This hint is not guaranteed to be accurate but it
  772. ** is often close. The underlying VFS might choose to preallocate database
  773. ** file space based on this hint in order to help writes to the database
  774. ** file run faster.
  775. **
  776. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  777. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  778. ** extends and truncates the database file in chunks of a size specified
  779. ** by the user. The fourth argument to [sqlite3_file_control()] should
  780. ** point to an integer (type int) containing the new chunk-size to use
  781. ** for the nominated database. Allocating database file space in large
  782. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  783. ** improve performance on some systems.
  784. **
  785. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  786. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  787. ** to the [sqlite3_file] object associated with a particular database
  788. ** connection. See the [sqlite3_file_control()] documentation for
  789. ** additional information.
  790. **
  791. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  792. ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
  793. ** SQLite and sent to all VFSes in place of a call to the xSync method
  794. ** when the database connection has [PRAGMA synchronous] set to OFF.)^
  795. ** Some specialized VFSes need this signal in order to operate correctly
  796. ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
  797. ** VFSes do not need this signal and should silently ignore this opcode.
  798. ** Applications should not call [sqlite3_file_control()] with this
  799. ** opcode as doing so may disrupt the operation of the specialized VFSes
  800. ** that do require it.
  801. **
  802. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  803. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  804. ** retry counts and intervals for certain disk I/O operations for the
  805. ** windows [VFS] in order to provide robustness in the presence of
  806. ** anti-virus programs. By default, the windows VFS will retry file read,
  807. ** file write, and file delete operations up to 10 times, with a delay
  808. ** of 25 milliseconds before the first retry and with the delay increasing
  809. ** by an additional 25 milliseconds with each subsequent retry. This
  810. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  811. ** to be adjusted. The values are changed for all database connections
  812. ** within the same process. The argument is a pointer to an array of two
  813. ** integers where the first integer i the new retry count and the second
  814. ** integer is the delay. If either integer is negative, then the setting
  815. ** is not changed but instead the prior value of that setting is written
  816. ** into the array entry, allowing the current retry settings to be
  817. ** interrogated. The zDbName parameter is ignored.
  818. **
  819. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  820. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  821. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  822. ** write ahead log and shared memory files used for transaction control
  823. ** are automatically deleted when the latest connection to the database
  824. ** closes. Setting persistent WAL mode causes those files to persist after
  825. ** close. Persisting the files is useful when other processes that do not
  826. ** have write permission on the directory containing the database file want
  827. ** to read the database file, as the WAL and shared memory files must exist
  828. ** in order for the database to be readable. The fourth parameter to
  829. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  830. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  831. ** WAL mode. If the integer is -1, then it is overwritten with the current
  832. ** WAL persistence setting.
  833. **
  834. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  835. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  836. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  837. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  838. ** xDeviceCharacteristics methods. The fourth parameter to
  839. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  840. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  841. ** mode. If the integer is -1, then it is overwritten with the current
  842. ** zero-damage mode setting.
  843. **
  844. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  845. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  846. ** a write transaction to indicate that, unless it is rolled back for some
  847. ** reason, the entire database file will be overwritten by the current
  848. ** transaction. This is used by VACUUM operations.
  849. **
  850. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  851. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  852. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  853. ** final bottom-level VFS are written into memory obtained from
  854. ** [sqlite3_malloc()] and the result is stored in the char* variable
  855. ** that the fourth parameter of [sqlite3_file_control()] points to.
  856. ** The caller is responsible for freeing the memory when done. As with
  857. ** all file-control actions, there is no guarantee that this will actually
  858. ** do anything. Callers should initialize the char* variable to a NULL
  859. ** pointer in case this file-control is not implemented. This file-control
  860. ** is intended for diagnostic use only.
  861. **
  862. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  863. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  864. ** file control is sent to the open [sqlite3_file] object corresponding
  865. ** to the database file to which the pragma statement refers. ^The argument
  866. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  867. ** pointers to strings (char**) in which the second element of the array
  868. ** is the name of the pragma and the third element is the argument to the
  869. ** pragma or NULL if the pragma has no argument. ^The handler for an
  870. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  871. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  872. ** or the equivalent and that string will become the result of the pragma or
  873. ** the error message if the pragma fails. ^If the
  874. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  875. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  876. ** file control returns [SQLITE_OK], then the parser assumes that the
  877. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  878. ** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  879. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  880. ** that the VFS encountered an error while handling the [PRAGMA] and the
  881. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  882. ** file control occurs at the beginning of pragma statement analysis and so
  883. ** it is able to override built-in [PRAGMA] statements.
  884. **
  885. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  886. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  887. ** file-control may be invoked by SQLite on the database file handle
  888. ** shortly after it is opened in order to provide a custom VFS with access
  889. ** to the connections busy-handler callback. The argument is of type (void **)
  890. ** - an array of two (void *) values. The first (void *) actually points
  891. ** to a function of type (int (*)(void *)). In order to invoke the connections
  892. ** busy-handler, this function should be invoked with the second (void *) in
  893. ** the array as the only argument. If it returns non-zero, then the operation
  894. ** should be retried. If it returns zero, the custom VFS should abandon the
  895. ** current operation.
  896. **
  897. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  898. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  899. ** to have SQLite generate a
  900. ** temporary filename using the same algorithm that is followed to generate
  901. ** temporary filenames for TEMP tables and other internal uses. The
  902. ** argument should be a char** which will be filled with the filename
  903. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  904. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  905. **
  906. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  907. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  908. ** maximum number of bytes that will be used for memory-mapped I/O.
  909. ** The argument is a pointer to a value of type sqlite3_int64 that
  910. ** is an advisory maximum number of bytes in the file to memory map. The
  911. ** pointer is overwritten with the old value. The limit is not changed if
  912. ** the value originally pointed to is negative, and so the current limit
  913. ** can be queried by passing in a pointer to a negative number. This
  914. ** file-control is used internally to implement [PRAGMA mmap_size].
  915. **
  916. ** </ul>
  917. */
  918. #define SQLITE_FCNTL_LOCKSTATE 1
  919. #define SQLITE_GET_LOCKPROXYFILE 2
  920. #define SQLITE_SET_LOCKPROXYFILE 3
  921. #define SQLITE_LAST_ERRNO 4
  922. #define SQLITE_FCNTL_SIZE_HINT 5
  923. #define SQLITE_FCNTL_CHUNK_SIZE 6
  924. #define SQLITE_FCNTL_FILE_POINTER 7
  925. #define SQLITE_FCNTL_SYNC_OMITTED 8
  926. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  927. #define SQLITE_FCNTL_PERSIST_WAL 10
  928. #define SQLITE_FCNTL_OVERWRITE 11
  929. #define SQLITE_FCNTL_VFSNAME 12
  930. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  931. #define SQLITE_FCNTL_PRAGMA 14
  932. #define SQLITE_FCNTL_BUSYHANDLER 15
  933. #define SQLITE_FCNTL_TEMPFILENAME 16
  934. #define SQLITE_FCNTL_MMAP_SIZE 18
  935. /*
  936. ** CAPI3REF: Mutex Handle
  937. **
  938. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  939. ** abstract type for a mutex object. The SQLite core never looks
  940. ** at the internal representation of an [sqlite3_mutex]. It only
  941. ** deals with pointers to the [sqlite3_mutex] object.
  942. **
  943. ** Mutexes are created using [sqlite3_mutex_alloc()].
  944. */
  945. typedef struct sqlite3_mutex sqlite3_mutex;
  946. /*
  947. ** CAPI3REF: OS Interface Object
  948. **
  949. ** An instance of the sqlite3_vfs object defines the interface between
  950. ** the SQLite core and the underlying operating system. The "vfs"
  951. ** in the name of the object stands for "virtual file system". See
  952. ** the [VFS | VFS documentation] for further information.
  953. **
  954. ** The value of the iVersion field is initially 1 but may be larger in
  955. ** future versions of SQLite. Additional fields may be appended to this
  956. ** object when the iVersion value is increased. Note that the structure
  957. ** of the sqlite3_vfs object changes in the transaction between
  958. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  959. ** modified.
  960. **
  961. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  962. ** structure used by this VFS. mxPathname is the maximum length of
  963. ** a pathname in this VFS.
  964. **
  965. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  966. ** the pNext pointer. The [sqlite3_vfs_register()]
  967. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  968. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  969. ** searches the list. Neither the application code nor the VFS
  970. ** implementation should use the pNext pointer.
  971. **
  972. ** The pNext field is the only field in the sqlite3_vfs
  973. ** structure that SQLite will ever modify. SQLite will only access
  974. ** or modify this field while holding a particular static mutex.
  975. ** The application should never modify anything within the sqlite3_vfs
  976. ** object once the object has been registered.
  977. **
  978. ** The zName field holds the name of the VFS module. The name must
  979. ** be unique across all VFS modules.
  980. **
  981. ** [[sqlite3_vfs.xOpen]]
  982. ** ^SQLite guarantees that the zFilename parameter to xOpen
  983. ** is either a NULL pointer or string obtained
  984. ** from xFullPathname() with an optional suffix added.
  985. ** ^If a suffix is added to the zFilename parameter, it will
  986. ** consist of a single "-" character followed by no more than
  987. ** 11 alphanumeric and/or "-" characters.
  988. ** ^SQLite further guarantees that
  989. ** the string will be valid and unchanged until xClose() is
  990. ** called. Because of the previous sentence,
  991. ** the [sqlite3_file] can safely store a pointer to the
  992. ** filename if it needs to remember the filename for some reason.
  993. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  994. ** must invent its own temporary name for the file. ^Whenever the
  995. ** xFilename parameter is NULL it will also be the case that the
  996. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  997. **
  998. ** The flags argument to xOpen() includes all bits set in
  999. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1000. ** or [sqlite3_open16()] is used, then flags includes at least
  1001. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1002. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1003. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1004. **
  1005. ** ^(SQLite will also add one of the following flags to the xOpen()
  1006. ** call, depending on the object being opened:
  1007. **
  1008. ** <ul>
  1009. ** <li> [SQLITE_OPEN_MAIN_DB]
  1010. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1011. ** <li> [SQLITE_OPEN_TEMP_DB]
  1012. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1013. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1014. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1015. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1016. ** <li> [SQLITE_OPEN_WAL]
  1017. ** </ul>)^
  1018. **
  1019. ** The file I/O implementation can use the object type flags to
  1020. ** change the way it deals with files. For example, an application
  1021. ** that does not care about crash recovery or rollback might make
  1022. ** the open of a journal file a no-op. Writes to this journal would
  1023. ** also be no-ops, and any attempt to read the journal would return
  1024. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1025. ** file will be doing page-aligned sector reads and writes in a random
  1026. ** order and set up its I/O subsystem accordingly.
  1027. **
  1028. ** SQLite might also add one of the following flags to the xOpen method:
  1029. **
  1030. ** <ul>
  1031. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1032. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1033. ** </ul>
  1034. **
  1035. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1036. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1037. ** will be set for TEMP databases and their journals, transient
  1038. ** databases, and subjournals.
  1039. **
  1040. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1041. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1042. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1043. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1044. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1045. ** be created, and that it is an error if it already exists.
  1046. ** It is <i>not</i> used to indicate the file should be opened
  1047. ** for exclusive access.
  1048. **
  1049. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1050. ** to hold the [sqlite3_file] structure passed as the third
  1051. ** argument to xOpen. The xOpen method does not have to
  1052. ** allocate the structure; it should just fill it in. Note that
  1053. ** the xOpen method must set the sqlite3_file.pMethods to either
  1054. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1055. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1056. ** element will be valid after xOpen returns regardless of the success
  1057. ** or failure of the xOpen call.
  1058. **
  1059. ** [[sqlite3_vfs.xAccess]]
  1060. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1061. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1062. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1063. ** to test whether a file is at least readable. The file can be a
  1064. ** directory.
  1065. **
  1066. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1067. ** output buffer xFullPathname. The exact size of the output buffer
  1068. ** is also passed as a parameter to both methods. If the output buffer
  1069. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1070. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1071. ** to prevent this by setting mxPathname to a sufficiently large value.
  1072. **
  1073. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1074. ** interfaces are not strictly a part of the filesystem, but they are
  1075. ** included in the VFS structure for completeness.
  1076. ** The xRandomness() function attempts to return nBytes bytes
  1077. ** of good-quality randomness into zOut. The return value is
  1078. ** the actual number of bytes of randomness obtained.
  1079. ** The xSleep() method causes the calling thread to sleep for at
  1080. ** least the number of microseconds given. ^The xCurrentTime()
  1081. ** method returns a Julian Day Number for the current date and time as
  1082. ** a floating point value.
  1083. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1084. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1085. ** a 24-hour day).
  1086. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1087. ** date and time if that method is available (if iVersion is 2 or
  1088. ** greater and the function pointer is not NULL) and will fall back
  1089. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1090. **
  1091. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1092. ** are not used by the SQLite core. These optional interfaces are provided
  1093. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1094. ** system calls with functions under its control, a test program can
  1095. ** simulate faults and error conditions that would otherwise be difficult
  1096. ** or impossible to induce. The set of system calls that can be overridden
  1097. ** varies from one VFS to another, and from one version of the same VFS to the
  1098. ** next. Applications that use these interfaces must be prepared for any
  1099. ** or all of these interfaces to be NULL or for their behavior to change
  1100. ** from one release to the next. Applications must not attempt to access
  1101. ** any of these methods if the iVersion of the VFS is less than 3.
  1102. */
  1103. typedef struct sqlite3_vfs sqlite3_vfs;
  1104. typedef void (*sqlite3_syscall_ptr)(void);
  1105. struct sqlite3_vfs {
  1106. int iVersion; /* Structure version number (currently 3) */
  1107. int szOsFile; /* Size of subclassed sqlite3_file */
  1108. int mxPathname; /* Maximum file pathname length */
  1109. sqlite3_vfs *pNext; /* Next registered VFS */
  1110. const char *zName; /* Name of this virtual file system */
  1111. void *pAppData; /* Pointer to application-specific data */
  1112. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1113. int flags, int *pOutFlags);
  1114. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1115. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1116. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1117. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1118. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1119. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1120. void (*xDlClose)(sqlite3_vfs*, void*);
  1121. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1122. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1123. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1124. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1125. /*
  1126. ** The methods above are in version 1 of the sqlite_vfs object
  1127. ** definition. Those that follow are added in version 2 or later
  1128. */
  1129. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1130. /*
  1131. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1132. ** Those below are for version 3 and greater.
  1133. */
  1134. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1135. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1136. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1137. /*
  1138. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1139. ** New fields may be appended in figure versions. The iVersion
  1140. ** value will increment whenever this happens.
  1141. */
  1142. };
  1143. /*
  1144. ** CAPI3REF: Flags for the xAccess VFS method
  1145. **
  1146. ** These integer constants can be used as the third parameter to
  1147. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1148. ** what kind of permissions the xAccess method is looking for.
  1149. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1150. ** simply checks whether the file exists.
  1151. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1152. ** checks whether the named directory is both readable and writable
  1153. ** (in other words, if files can be added, removed, and renamed within
  1154. ** the directory).
  1155. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1156. ** [temp_store_directory pragma], though this could change in a future
  1157. ** release of SQLite.
  1158. ** With SQLITE_ACCESS_READ, the xAccess method
  1159. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1160. ** currently unused, though it might be used in a future release of
  1161. ** SQLite.
  1162. */
  1163. #define SQLITE_ACCESS_EXISTS 0
  1164. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1165. #define SQLITE_ACCESS_READ 2 /* Unused */
  1166. /*
  1167. ** CAPI3REF: Flags for the xShmLock VFS method
  1168. **
  1169. ** These integer constants define the various locking operations
  1170. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1171. ** following are the only legal combinations of flags to the
  1172. ** xShmLock method:
  1173. **
  1174. ** <ul>
  1175. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1176. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1177. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1178. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1179. ** </ul>
  1180. **
  1181. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1182. ** was given no the corresponding lock.
  1183. **
  1184. ** The xShmLock method can transition between unlocked and SHARED or
  1185. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1186. ** and EXCLUSIVE.
  1187. */
  1188. #define SQLITE_SHM_UNLOCK 1
  1189. #define SQLITE_SHM_LOCK 2
  1190. #define SQLITE_SHM_SHARED 4
  1191. #define SQLITE_SHM_EXCLUSIVE 8
  1192. /*
  1193. ** CAPI3REF: Maximum xShmLock index
  1194. **
  1195. ** The xShmLock method on [sqlite3_io_methods] may use values
  1196. ** between 0 and this upper bound as its "offset" argument.
  1197. ** The SQLite core will never attempt to acquire or release a
  1198. ** lock outside of this range
  1199. */
  1200. #define SQLITE_SHM_NLOCK 8
  1201. /*
  1202. ** CAPI3REF: Initialize The SQLite Library
  1203. **
  1204. ** ^The sqlite3_initialize() routine initializes the
  1205. ** SQLite library. ^The sqlite3_shutdown() routine
  1206. ** deallocates any resources that were allocated by sqlite3_initialize().
  1207. ** These routines are designed to aid in process initialization and
  1208. ** shutdown on embedded systems. Workstation applications using
  1209. ** SQLite normally do not need to invoke either of these routines.
  1210. **
  1211. ** A call to sqlite3_initialize() is an "effective" call if it is
  1212. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1213. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1214. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1215. ** of sqlite3_initialize() does any initialization. All other calls
  1216. ** are harmless no-ops.)^
  1217. **
  1218. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1219. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1220. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1221. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1222. **
  1223. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1224. ** is not. The sqlite3_shutdown() interface must only be called from a
  1225. ** single thread. All open [database connections] must be closed and all
  1226. ** other SQLite resources must be deallocated prior to invoking
  1227. ** sqlite3_shutdown().
  1228. **
  1229. ** Among other things, ^sqlite3_initialize() will invoke
  1230. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1231. ** will invoke sqlite3_os_end().
  1232. **
  1233. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1234. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1235. ** the library (perhaps it is unable to allocate a needed resource such
  1236. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1237. **
  1238. ** ^The sqlite3_initialize() routine is called internally by many other
  1239. ** SQLite interfaces so that an application usually does not need to
  1240. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1241. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1242. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1243. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1244. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1245. ** are omitted and the application must call sqlite3_initialize() directly
  1246. ** prior to using any other SQLite interface. For maximum portability,
  1247. ** it is recommended that applications always invoke sqlite3_initialize()
  1248. ** directly prior to using any other SQLite interface. Future releases
  1249. ** of SQLite may require this. In other words, the behavior exhibited
  1250. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1251. ** default behavior in some future release of SQLite.
  1252. **
  1253. ** The sqlite3_os_init() routine does operating-system specific
  1254. ** initialization of the SQLite library. The sqlite3_os_end()
  1255. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1256. ** performed by these routines include allocation or deallocation
  1257. ** of static resources, initialization of global variables,
  1258. ** setting up a default [sqlite3_vfs] module, or setting up
  1259. ** a default configuration using [sqlite3_config()].
  1260. **
  1261. ** The application should never invoke either sqlite3_os_init()
  1262. ** or sqlite3_os_end() directly. The application should only invoke
  1263. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1264. ** interface is called automatically by sqlite3_initialize() and
  1265. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1266. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1267. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1268. ** When [custom builds | built for other platforms]
  1269. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1270. ** option) the application must supply a suitable implementation for
  1271. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1272. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1273. ** must return [SQLITE_OK] on success and some other [error code] upon
  1274. ** failure.
  1275. */
  1276. SQLITE_API int sqlite3_initialize(void);
  1277. SQLITE_API int sqlite3_shutdown(void);
  1278. SQLITE_API int sqlite3_os_init(void);
  1279. SQLITE_API int sqlite3_os_end(void);
  1280. /*
  1281. ** CAPI3REF: Configuring The SQLite Library
  1282. **
  1283. ** The sqlite3_config() interface is used to make global configuration
  1284. ** changes to SQLite in order to tune SQLite to the specific needs of
  1285. ** the application. The default configuration is recommended for most
  1286. ** applications and so this routine is usually not necessary. It is
  1287. ** provided to support rare applications with unusual needs.
  1288. **
  1289. ** The sqlite3_config() interface is not threadsafe. The application
  1290. ** must insure that no other SQLite interfaces are invoked by other
  1291. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1292. ** may only be invoked prior to library initialization using
  1293. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1294. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1295. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1296. ** Note, however, that ^sqlite3_config() can be called as part of the
  1297. ** implementation of an application-defined [sqlite3_os_init()].
  1298. **
  1299. ** The first argument to sqlite3_config() is an integer
  1300. ** [configuration option] that determines
  1301. ** what property of SQLite is to be configured. Subsequent arguments
  1302. ** vary depending on the [configuration option]
  1303. ** in the first argument.
  1304. **
  1305. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1306. ** ^If the option is unknown or SQLite is unable to set the option
  1307. ** then this routine returns a non-zero [error code].
  1308. */
  1309. SQLITE_API int sqlite3_config(int, ...);
  1310. /*
  1311. ** CAPI3REF: Configure database connections
  1312. **
  1313. ** The sqlite3_db_config() interface is used to make configuration
  1314. ** changes to a [database connection]. The interface is similar to
  1315. ** [sqlite3_config()] except that the changes apply to a single
  1316. ** [database connection] (specified in the first argument).
  1317. **
  1318. ** The second argument to sqlite3_db_config(D,V,...) is the
  1319. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1320. ** that indicates what aspect of the [database connection] is being configured.
  1321. ** Subsequent arguments vary depending on the configuration verb.
  1322. **
  1323. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1324. ** the call is considered successful.
  1325. */
  1326. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1327. /*
  1328. ** CAPI3REF: Memory Allocation Routines
  1329. **
  1330. ** An instance of this object defines the interface between SQLite
  1331. ** and low-level memory allocation routines.
  1332. **
  1333. ** This object is used in only one place in the SQLite interface.
  1334. ** A pointer to an instance of this object is the argument to
  1335. ** [sqlite3_config()] when the configuration option is
  1336. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1337. ** By creating an instance of this object
  1338. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1339. ** during configuration, an application can specify an alternative
  1340. ** memory allocation subsystem for SQLite to use for all of its
  1341. ** dynamic memory needs.
  1342. **
  1343. ** Note that SQLite comes with several [built-in memory allocators]
  1344. ** that are perfectly adequate for the overwhelming majority of applications
  1345. ** and that this object is only useful to a tiny minority of applications
  1346. ** with specialized memory allocation requirements. This object is
  1347. ** also used during testing of SQLite in order to specify an alternative
  1348. ** memory allocator that simulates memory out-of-memory conditions in
  1349. ** order to verify that SQLite recovers gracefully from such
  1350. ** conditions.
  1351. **
  1352. ** The xMalloc, xRealloc, and xFree methods must work like the
  1353. ** malloc(), realloc() and free() functions from the standard C library.
  1354. ** ^SQLite guarantees that the second argument to
  1355. ** xRealloc is always a value returned by a prior call to xRoundup.
  1356. **
  1357. ** xSize should return the allocated size of a memory allocation
  1358. ** previously obtained from xMalloc or xRealloc. The allocated size
  1359. ** is always at least as big as the requested size but may be larger.
  1360. **
  1361. ** The xRoundup method returns what would be the allocated size of
  1362. ** a memory allocation given a particular requested size. Most memory
  1363. ** allocators round up memory allocations at least to the next multiple
  1364. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1365. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1366. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1367. ** that causes the corresponding memory allocation to fail.
  1368. **
  1369. ** The xInit method initializes the memory allocator. (For example,
  1370. ** it might allocate any require mutexes or initialize internal data
  1371. ** structures. The xShutdown method is invoked (indirectly) by
  1372. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1373. ** by xInit. The pAppData pointer is used as the only parameter to
  1374. ** xInit and xShutdown.
  1375. **
  1376. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1377. ** the xInit method, so the xInit method need not be threadsafe. The
  1378. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1379. ** not need to be threadsafe either. For all other methods, SQLite
  1380. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1381. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1382. ** it is by default) and so the methods are automatically serialized.
  1383. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1384. ** methods must be threadsafe or else make their own arrangements for
  1385. ** serialization.
  1386. **
  1387. ** SQLite will never invoke xInit() more than once without an intervening
  1388. ** call to xShutdown().
  1389. */
  1390. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1391. struct sqlite3_mem_methods {
  1392. void *(*xMalloc)(int); /* Memory allocation function */
  1393. void (*xFree)(void*); /* Free a prior allocation */
  1394. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1395. int (*xSize)(void*); /* Return the size of an allocation */
  1396. int (*xRoundup)(int); /* Round up request size to allocation size */
  1397. int (*xInit)(void*); /* Initialize the memory allocator */
  1398. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1399. void *pAppData; /* Argument to xInit() and xShutdown() */
  1400. };
  1401. /*
  1402. ** CAPI3REF: Configuration Options
  1403. ** KEYWORDS: {configuration option}
  1404. **
  1405. ** These constants are the available integer configuration options that
  1406. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1407. **
  1408. ** New configuration options may be added in future releases of SQLite.
  1409. ** Existing configuration options might be discontinued. Applications
  1410. ** should check the return code from [sqlite3_config()] to make sure that
  1411. ** the call worked. The [sqlite3_config()] interface will return a
  1412. ** non-zero [error code] if a discontinued or unsupported configuration option
  1413. ** is invoked.
  1414. **
  1415. ** <dl>
  1416. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1417. ** <dd>There are no arguments to this option. ^This option sets the
  1418. ** [threading mode] to Single-thread. In other words, it disables
  1419. ** all mutexing and puts SQLite into a mode where it can only be used
  1420. ** by a single thread. ^If SQLite is compiled with
  1421. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1422. ** it is not possible to change the [threading mode] from its default
  1423. ** value of Single-thread and so [sqlite3_config()] will return
  1424. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1425. ** configuration option.</dd>
  1426. **
  1427. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1428. ** <dd>There are no arguments to this option. ^This option sets the
  1429. ** [threading mode] to Multi-thread. In other words, it disables
  1430. ** mutexing on [database connection] and [prepared statement] objects.
  1431. ** The application is responsible for serializing access to
  1432. ** [database connections] and [prepared statements]. But other mutexes
  1433. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1434. ** environment as long as no two threads attempt to use the same
  1435. ** [database connection] at the same time. ^If SQLite is compiled with
  1436. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1437. ** it is not possible to set the Multi-thread [threading mode] and
  1438. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1439. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1440. **
  1441. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1442. ** <dd>There are no arguments to this option. ^This option sets the
  1443. ** [threading mode] to Serialized. In other words, this option enables
  1444. ** all mutexes including the recursive
  1445. ** mutexes on [database connection] and [prepared statement] objects.
  1446. ** In this mode (which is the default when SQLite is compiled with
  1447. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1448. ** to [database connections] and [prepared statements] so that the
  1449. ** application is free to use the same [database connection] or the
  1450. ** same [prepared statement] in different threads at the same time.
  1451. ** ^If SQLite is compiled with
  1452. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1453. ** it is not possible to set the Serialized [threading mode] and
  1454. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1455. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1456. **
  1457. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1458. ** <dd> ^(This option takes a single argument which is a pointer to an
  1459. ** instance of the [sqlite3_mem_methods] structure. The argument specifies
  1460. ** alternative low-level memory allocation routines to be used in place of
  1461. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1462. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1463. ** before the [sqlite3_config()] call returns.</dd>
  1464. **
  1465. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1466. ** <dd> ^(This option takes a single argument which is a pointer to an
  1467. ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
  1468. ** structure is filled with the currently defined memory allocation routines.)^
  1469. ** This option can be used to overload the default memory allocation
  1470. ** routines with a wrapper that simulations memory allocation failure or
  1471. ** tracks memory usage, for example. </dd>
  1472. **
  1473. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1474. ** <dd> ^This option takes single argument of type int, interpreted as a
  1475. ** boolean, which enables or disables the collection of memory allocation
  1476. ** statistics. ^(When memory allocation statistics are disabled, the
  1477. ** following SQLite interfaces become non-operational:
  1478. ** <ul>
  1479. ** <li> [sqlite3_memory_used()]
  1480. ** <li> [sqlite3_memory_highwater()]
  1481. ** <li> [sqlite3_soft_heap_limit64()]
  1482. ** <li> [sqlite3_status()]
  1483. ** </ul>)^
  1484. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1485. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1486. ** allocation statistics are disabled by default.
  1487. ** </dd>
  1488. **
  1489. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1490. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1491. ** scratch memory. There are three arguments: A pointer an 8-byte
  1492. ** aligned memory buffer from which the scratch allocations will be
  1493. ** drawn, the size of each scratch allocation (sz),
  1494. ** and the maximum number of scratch allocations (N). The sz
  1495. ** argument must be a multiple of 16.
  1496. ** The first argument must be a pointer to an 8-byte aligned buffer
  1497. ** of at least sz*N bytes of memory.
  1498. ** ^SQLite will use no more than two scratch buffers per thread. So
  1499. ** N should be set to twice the expected maximum number of threads.
  1500. ** ^SQLite will never require a scratch buffer that is more than 6
  1501. ** times the database page size. ^If SQLite needs needs additional
  1502. ** scratch memory beyond what is provided by this configuration option, then
  1503. ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1504. **
  1505. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1506. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1507. ** the database page cache with the default page cache implementation.
  1508. ** This configuration should not be used if an application-define page
  1509. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  1510. ** There are three arguments to this option: A pointer to 8-byte aligned
  1511. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1512. ** The sz argument should be the size of the largest database page
  1513. ** (a power of two between 512 and 32768) plus a little extra for each
  1514. ** page header. ^The page header size is 20 to 40 bytes depending on
  1515. ** the host architecture. ^It is harmless, apart from the wasted memory,
  1516. ** to make sz a little too large. The first
  1517. ** argument should point to an allocation of at least sz*N bytes of memory.
  1518. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1519. ** memory needs for the first N pages that it adds to cache. ^If additional
  1520. ** page cache memory is needed beyond what is provided by this option, then
  1521. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1522. ** The pointer in the first argument must
  1523. ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  1524. ** will be undefined.</dd>
  1525. **
  1526. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1527. ** <dd> ^This option specifies a static memory buffer that SQLite will use
  1528. ** for all of its dynamic memory allocation needs beyond those provided
  1529. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1530. ** There are three arguments: An 8-byte aligned pointer to the memory,
  1531. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1532. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1533. ** to using its default memory allocator (the system malloc() implementation),
  1534. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1535. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1536. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1537. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1538. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1539. ** boundary or subsequent behavior of SQLite will be undefined.
  1540. ** The minimum allocation size is capped at 2**12. Reasonable values
  1541. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1542. **
  1543. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1544. ** <dd> ^(This option takes a single argument which is a pointer to an
  1545. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  1546. ** alternative low-level mutex routines to be used in place
  1547. ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
  1548. ** content of the [sqlite3_mutex_methods] structure before the call to
  1549. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1550. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1551. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1552. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1553. ** return [SQLITE_ERROR].</dd>
  1554. **
  1555. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1556. ** <dd> ^(This option takes a single argument which is a pointer to an
  1557. ** instance of the [sqlite3_mutex_methods] structure. The
  1558. ** [sqlite3_mutex_methods]
  1559. ** structure is filled with the currently defined mutex routines.)^
  1560. ** This option can be used to overload the default mutex allocation
  1561. ** routines with a wrapper used to track mutex usage for performance
  1562. ** profiling or testing, for example. ^If SQLite is compiled with
  1563. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1564. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1565. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1566. ** return [SQLITE_ERROR].</dd>
  1567. **
  1568. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1569. ** <dd> ^(This option takes two arguments that determine the default
  1570. ** memory allocation for the lookaside memory allocator on each
  1571. ** [database connection]. The first argument is the
  1572. ** size of each lookaside buffer slot and the second is the number of
  1573. ** slots allocated to each database connection.)^ ^(This option sets the
  1574. ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1575. ** verb to [sqlite3_db_config()] can be used to change the lookaside
  1576. ** configuration on individual connections.)^ </dd>
  1577. **
  1578. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1579. ** <dd> ^(This option takes a single argument which is a pointer to
  1580. ** an [sqlite3_pcache_methods2] object. This object specifies the interface
  1581. ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
  1582. ** object and uses it for page cache memory allocations.</dd>
  1583. **
  1584. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1585. ** <dd> ^(This option takes a single argument which is a pointer to an
  1586. ** [sqlite3_pcache_methods2] object. SQLite copies of the current
  1587. ** page cache implementation into that object.)^ </dd>
  1588. **
  1589. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1590. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1591. ** global [error log].
  1592. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1593. ** function with a call signature of void(*)(void*,int,const char*),
  1594. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1595. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1596. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1597. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1598. ** passed through as the first parameter to the application-defined logger
  1599. ** function whenever that function is invoked. ^The second parameter to
  1600. ** the logger function is a copy of the first parameter to the corresponding
  1601. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1602. ** [extended result code]. ^The third parameter passed to the logger is
  1603. ** log message after formatting via [sqlite3_snprintf()].
  1604. ** The SQLite logging interface is not reentrant; the logger function
  1605. ** supplied by the application must not invoke any SQLite interface.
  1606. ** In a multi-threaded application, the application-defined logger
  1607. ** function must be threadsafe. </dd>
  1608. **
  1609. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1610. ** <dd>^(This option takes a single argument of type int. If non-zero, then
  1611. ** URI handling is globally enabled. If the parameter is zero, then URI handling
  1612. ** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
  1613. ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  1614. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1615. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1616. ** connection is opened. ^If it is globally disabled, filenames are
  1617. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1618. ** database connection is opened. ^(By default, URI handling is globally
  1619. ** disabled. The default value may be changed by compiling with the
  1620. ** [SQLITE_USE_URI] symbol defined.)^
  1621. **
  1622. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1623. ** <dd>^This option takes a single integer argument which is interpreted as
  1624. ** a boolean in order to enable or disable the use of covering indices for
  1625. ** full table scans in the query optimizer. ^The default setting is determined
  1626. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1627. ** if that compile-time option is omitted.
  1628. ** The ability to disable the use of covering indices for full table scans
  1629. ** is because some incorrectly coded legacy applications might malfunction
  1630. ** when the optimization is enabled. Providing the ability to
  1631. ** disable the optimization allows the older, buggy application code to work
  1632. ** without change even with newer versions of SQLite.
  1633. **
  1634. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1635. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1636. ** <dd> These options are obsolete and should not be used by new code.
  1637. ** They are retained for backwards compatibility but are now no-ops.
  1638. ** </dd>
  1639. **
  1640. ** [[SQLITE_CONFIG_SQLLOG]]
  1641. ** <dt>SQLITE_CONFIG_SQLLOG
  1642. ** <dd>This option is only available if sqlite is compiled with the
  1643. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1644. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1645. ** The second should be of type (void*). The callback is invoked by the library
  1646. ** in three separate circumstances, identified by the value passed as the
  1647. ** fourth parameter. If the fourth parameter is 0, then the database connection
  1648. ** passed as the second argument has just been opened. The third argument
  1649. ** points to a buffer containing the name of the main database file. If the
  1650. ** fourth parameter is 1, then the SQL statement that the third parameter
  1651. ** points to has just been executed. Or, if the fourth parameter is 2, then
  1652. ** the connection being passed as the second parameter is being closed. The
  1653. ** third parameter is passed NULL In this case. An example of using this
  1654. ** configuration option can be seen in the "test_sqllog.c" source file in
  1655. ** the canonical SQLite source tree.</dd>
  1656. **
  1657. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1658. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1659. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1660. ** that are the default mmap size limit (the default setting for
  1661. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1662. ** ^The default setting can be overridden by each database connection using
  1663. ** either the [PRAGMA mmap_size] command, or by using the
  1664. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  1665. ** cannot be changed at run-time. Nor may the maximum allowed mmap size
  1666. ** exceed the compile-time maximum mmap size set by the
  1667. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1668. ** ^If either argument to this option is negative, then that argument is
  1669. ** changed to its compile-time default.
  1670. ** </dl>
  1671. */
  1672. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1673. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1674. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1675. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1676. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1677. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1678. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1679. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1680. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1681. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1682. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1683. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1684. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1685. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  1686. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  1687. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  1688. #define SQLITE_CONFIG_URI 17 /* int */
  1689. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  1690. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  1691. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  1692. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  1693. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  1694. /*
  1695. ** CAPI3REF: Database Connection Configuration Options
  1696. **
  1697. ** These constants are the available integer configuration options that
  1698. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1699. **
  1700. ** New configuration options may be added in future releases of SQLite.
  1701. ** Existing configuration options might be discontinued. Applications
  1702. ** should check the return code from [sqlite3_db_config()] to make sure that
  1703. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  1704. ** non-zero [error code] if a discontinued or unsupported configuration option
  1705. ** is invoked.
  1706. **
  1707. ** <dl>
  1708. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  1709. ** <dd> ^This option takes three additional arguments that determine the
  1710. ** [lookaside memory allocator] configuration for the [database connection].
  1711. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  1712. ** pointer to a memory buffer to use for lookaside memory.
  1713. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  1714. ** may be NULL in which case SQLite will allocate the
  1715. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  1716. ** size of each lookaside buffer slot. ^The third argument is the number of
  1717. ** slots. The size of the buffer in the first argument must be greater than
  1718. ** or equal to the product of the second and third arguments. The buffer
  1719. ** must be aligned to an 8-byte boundary. ^If the second argument to
  1720. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  1721. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  1722. ** configuration for a database connection can only be changed when that
  1723. ** connection is not currently using lookaside memory, or in other words
  1724. ** when the "current value" returned by
  1725. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  1726. ** Any attempt to change the lookaside memory configuration when lookaside
  1727. ** memory is in use leaves the configuration unchanged and returns
  1728. ** [SQLITE_BUSY].)^</dd>
  1729. **
  1730. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  1731. ** <dd> ^This option is used to enable or disable the enforcement of
  1732. ** [foreign key constraints]. There should be two additional arguments.
  1733. ** The first argument is an integer which is 0 to disable FK enforcement,
  1734. ** positive to enable FK enforcement or negative to leave FK enforcement
  1735. ** unchanged. The second parameter is a pointer to an integer into which
  1736. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  1737. ** following this call. The second parameter may be a NULL pointer, in
  1738. ** which case the FK enforcement setting is not reported back. </dd>
  1739. **
  1740. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  1741. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  1742. ** There should be two additional arguments.
  1743. ** The first argument is an integer which is 0 to disable triggers,
  1744. ** positive to enable triggers or negative to leave the setting unchanged.
  1745. ** The second parameter is a pointer to an integer into which
  1746. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  1747. ** following this call. The second parameter may be a NULL pointer, in
  1748. ** which case the trigger setting is not reported back. </dd>
  1749. **
  1750. ** </dl>
  1751. */
  1752. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  1753. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  1754. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  1755. /*
  1756. ** CAPI3REF: Enable Or Disable Extended Result Codes
  1757. **
  1758. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  1759. ** [extended result codes] feature of SQLite. ^The extended result
  1760. ** codes are disabled by default for historical compatibility.
  1761. */
  1762. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  1763. /*
  1764. ** CAPI3REF: Last Insert Rowid
  1765. **
  1766. ** ^Each entry in an SQLite table has a unique 64-bit signed
  1767. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  1768. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  1769. ** names are not also used by explicitly declared columns. ^If
  1770. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  1771. ** is another alias for the rowid.
  1772. **
  1773. ** ^This routine returns the [rowid] of the most recent
  1774. ** successful [INSERT] into the database from the [database connection]
  1775. ** in the first argument. ^As of SQLite version 3.7.7, this routines
  1776. ** records the last insert rowid of both ordinary tables and [virtual tables].
  1777. ** ^If no successful [INSERT]s
  1778. ** have ever occurred on that database connection, zero is returned.
  1779. **
  1780. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  1781. ** method, then this routine will return the [rowid] of the inserted
  1782. ** row as long as the trigger or virtual table method is running.
  1783. ** But once the trigger or virtual table method ends, the value returned
  1784. ** by this routine reverts to what it was before the trigger or virtual
  1785. ** table method began.)^
  1786. **
  1787. ** ^An [INSERT] that fails due to a constraint violation is not a
  1788. ** successful [INSERT] and does not change the value returned by this
  1789. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  1790. ** and INSERT OR ABORT make no changes to the return value of this
  1791. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  1792. ** encounters a constraint violation, it does not fail. The
  1793. ** INSERT continues to completion after deleting rows that caused
  1794. ** the constraint problem so INSERT OR REPLACE will always change
  1795. ** the return value of this interface.)^
  1796. **
  1797. ** ^For the purposes of this routine, an [INSERT] is considered to
  1798. ** be successful even if it is subsequently rolled back.
  1799. **
  1800. ** This function is accessible to SQL statements via the
  1801. ** [last_insert_rowid() SQL function].
  1802. **
  1803. ** If a separate thread performs a new [INSERT] on the same
  1804. ** database connection while the [sqlite3_last_insert_rowid()]
  1805. ** function is running and thus changes the last insert [rowid],
  1806. ** then the value returned by [sqlite3_last_insert_rowid()] is
  1807. ** unpredictable and might not equal either the old or the new
  1808. ** last insert [rowid].
  1809. */
  1810. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  1811. /*
  1812. ** CAPI3REF: Count The Number Of Rows Modified
  1813. **
  1814. ** ^This function returns the number of database rows that were changed
  1815. ** or inserted or deleted by the most recently completed SQL statement
  1816. ** on the [database connection] specified by the first parameter.
  1817. ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  1818. ** or [DELETE] statement are counted. Auxiliary changes caused by
  1819. ** triggers or [foreign key actions] are not counted.)^ Use the
  1820. ** [sqlite3_total_changes()] function to find the total number of changes
  1821. ** including changes caused by triggers and foreign key actions.
  1822. **
  1823. ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  1824. ** are not counted. Only real table changes are counted.
  1825. **
  1826. ** ^(A "row change" is a change to a single row of a single table
  1827. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  1828. ** are changed as side effects of [REPLACE] constraint resolution,
  1829. ** rollback, ABORT processing, [DROP TABLE], or by any other
  1830. ** mechanisms do not count as direct row changes.)^
  1831. **
  1832. ** A "trigger context" is a scope of execution that begins and
  1833. ** ends with the script of a [CREATE TRIGGER | trigger].
  1834. ** Most SQL statements are
  1835. ** evaluated outside of any trigger. This is the "top level"
  1836. ** trigger context. If a trigger fires from the top level, a
  1837. ** new trigger context is entered for the duration of that one
  1838. ** trigger. Subtriggers create subcontexts for their duration.
  1839. **
  1840. ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  1841. ** not create a new trigger context.
  1842. **
  1843. ** ^This function returns the number of direct row changes in the
  1844. ** most recent INSERT, UPDATE, or DELETE statement within the same
  1845. ** trigger context.
  1846. **
  1847. ** ^Thus, when called from the top level, this function returns the
  1848. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  1849. ** that also occurred at the top level. ^(Within the body of a trigger,
  1850. ** the sqlite3_changes() interface can be called to find the number of
  1851. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  1852. ** statement within the body of the same trigger.
  1853. ** However, the number returned does not include changes
  1854. ** caused by subtriggers since those have their own context.)^
  1855. **
  1856. ** See also the [sqlite3_total_changes()] interface, the
  1857. ** [count_changes pragma], and the [changes() SQL function].
  1858. **
  1859. ** If a separate thread makes changes on the same database connection
  1860. ** while [sqlite3_changes()] is running then the value returned
  1861. ** is unpredictable and not meaningful.
  1862. */
  1863. SQLITE_API int sqlite3_changes(sqlite3*);
  1864. /*
  1865. ** CAPI3REF: Total Number Of Rows Modified
  1866. **
  1867. ** ^This function returns the number of row changes caused by [INSERT],
  1868. ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  1869. ** ^(The count returned by sqlite3_total_changes() includes all changes
  1870. ** from all [CREATE TRIGGER | trigger] contexts and changes made by
  1871. ** [foreign key actions]. However,
  1872. ** the count does not include changes used to implement [REPLACE] constraints,
  1873. ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
  1874. ** count does not include rows of views that fire an [INSTEAD OF trigger],
  1875. ** though if the INSTEAD OF trigger makes changes of its own, those changes
  1876. ** are counted.)^
  1877. ** ^The sqlite3_total_changes() function counts the changes as soon as
  1878. ** the statement that makes them is completed (when the statement handle
  1879. ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  1880. **
  1881. ** See also the [sqlite3_changes()] interface, the
  1882. ** [count_changes pragma], and the [total_changes() SQL function].
  1883. **
  1884. ** If a separate thread makes changes on the same database connection
  1885. ** while [sqlite3_total_changes()] is running then the value
  1886. ** returned is unpredictable and not meaningful.
  1887. */
  1888. SQLITE_API int sqlite3_total_changes(sqlite3*);
  1889. /*
  1890. ** CAPI3REF: Interrupt A Long-Running Query
  1891. **
  1892. ** ^This function causes any pending database operation to abort and
  1893. ** return at its earliest opportunity. This routine is typically
  1894. ** called in response to a user action such as pressing "Cancel"
  1895. ** or Ctrl-C where the user wants a long query operation to halt
  1896. ** immediately.
  1897. **
  1898. ** ^It is safe to call this routine from a thread different from the
  1899. ** thread that is currently running the database operation. But it
  1900. ** is not safe to call this routine with a [database connection] that
  1901. ** is closed or might close before sqlite3_interrupt() returns.
  1902. **
  1903. ** ^If an SQL operation is very nearly finished at the time when
  1904. ** sqlite3_interrupt() is called, then it might not have an opportunity
  1905. ** to be interrupted and might continue to completion.
  1906. **
  1907. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  1908. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  1909. ** that is inside an explicit transaction, then the entire transaction
  1910. ** will be rolled back automatically.
  1911. **
  1912. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  1913. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  1914. ** that are started after the sqlite3_interrupt() call and before the
  1915. ** running statements reaches zero are interrupted as if they had been
  1916. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  1917. ** that are started after the running statement count reaches zero are
  1918. ** not effected by the sqlite3_interrupt().
  1919. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  1920. ** SQL statements is a no-op and has no effect on SQL statements
  1921. ** that are started after the sqlite3_interrupt() call returns.
  1922. **
  1923. ** If the database connection closes while [sqlite3_interrupt()]
  1924. ** is running then bad things will likely happen.
  1925. */
  1926. SQLITE_API void sqlite3_interrupt(sqlite3*);
  1927. /*
  1928. ** CAPI3REF: Determine If An SQL Statement Is Complete
  1929. **
  1930. ** These routines are useful during command-line input to determine if the
  1931. ** currently entered text seems to form a complete SQL statement or
  1932. ** if additional input is needed before sending the text into
  1933. ** SQLite for parsing. ^These routines return 1 if the input string
  1934. ** appears to be a complete SQL statement. ^A statement is judged to be
  1935. ** complete if it ends with a semicolon token and is not a prefix of a
  1936. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  1937. ** string literals or quoted identifier names or comments are not
  1938. ** independent tokens (they are part of the token in which they are
  1939. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  1940. ** and comments that follow the final semicolon are ignored.
  1941. **
  1942. ** ^These routines return 0 if the statement is incomplete. ^If a
  1943. ** memory allocation fails, then SQLITE_NOMEM is returned.
  1944. **
  1945. ** ^These routines do not parse the SQL statements thus
  1946. ** will not detect syntactically incorrect SQL.
  1947. **
  1948. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  1949. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  1950. ** automatically by sqlite3_complete16(). If that initialization fails,
  1951. ** then the return value from sqlite3_complete16() will be non-zero
  1952. ** regardless of whether or not the input SQL is complete.)^
  1953. **
  1954. ** The input to [sqlite3_complete()] must be a zero-terminated
  1955. ** UTF-8 string.
  1956. **
  1957. ** The input to [sqlite3_complete16()] must be a zero-terminated
  1958. ** UTF-16 string in native byte order.
  1959. */
  1960. SQLITE_API int sqlite3_complete(const char *sql);
  1961. SQLITE_API int sqlite3_complete16(const void *sql);
  1962. /*
  1963. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  1964. **
  1965. ** ^This routine sets a callback function that might be invoked whenever
  1966. ** an attempt is made to open a database table that another thread
  1967. ** or process has locked.
  1968. **
  1969. ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  1970. ** is returned immediately upon encountering the lock. ^If the busy callback
  1971. ** is not NULL, then the callback might be invoked with two arguments.
  1972. **
  1973. ** ^The first argument to the busy handler is a copy of the void* pointer which
  1974. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  1975. ** the busy handler callback is the number of times that the busy handler has
  1976. ** been invoked for this locking event. ^If the
  1977. ** busy callback returns 0, then no additional attempts are made to
  1978. ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  1979. ** ^If the callback returns non-zero, then another attempt
  1980. ** is made to open the database for reading and the cycle repeats.
  1981. **
  1982. ** The presence of a busy handler does not guarantee that it will be invoked
  1983. ** when there is lock contention. ^If SQLite determines that invoking the busy
  1984. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  1985. ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  1986. ** Consider a scenario where one process is holding a read lock that
  1987. ** it is trying to promote to a reserved lock and
  1988. ** a second process is holding a reserved lock that it is trying
  1989. ** to promote to an exclusive lock. The first process cannot proceed
  1990. ** because it is blocked by the second and the second process cannot
  1991. ** proceed because it is blocked by the first. If both processes
  1992. ** invoke the busy handlers, neither will make any progress. Therefore,
  1993. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  1994. ** will induce the first process to release its read lock and allow
  1995. ** the second process to proceed.
  1996. **
  1997. ** ^The default busy callback is NULL.
  1998. **
  1999. ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  2000. ** when SQLite is in the middle of a large transaction where all the
  2001. ** changes will not fit into the in-memory cache. SQLite will
  2002. ** already hold a RESERVED lock on the database file, but it needs
  2003. ** to promote this lock to EXCLUSIVE so that it can spill cache
  2004. ** pages into the database file without harm to concurrent
  2005. ** readers. ^If it is unable to promote the lock, then the in-memory
  2006. ** cache will be left in an inconsistent state and so the error
  2007. ** code is promoted from the relatively benign [SQLITE_BUSY] to
  2008. ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
  2009. ** forces an automatic rollback of the changes. See the
  2010. ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  2011. ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  2012. ** this is important.
  2013. **
  2014. ** ^(There can only be a single busy handler defined for each
  2015. ** [database connection]. Setting a new busy handler clears any
  2016. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2017. ** will also set or clear the busy handler.
  2018. **
  2019. ** The busy callback should not take any actions which modify the
  2020. ** database connection that invoked the busy handler. Any such actions
  2021. ** result in undefined behavior.
  2022. **
  2023. ** A busy handler must not close the database connection
  2024. ** or [prepared statement] that invoked the busy handler.
  2025. */
  2026. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2027. /*
  2028. ** CAPI3REF: Set A Busy Timeout
  2029. **
  2030. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2031. ** for a specified amount of time when a table is locked. ^The handler
  2032. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2033. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2034. ** the handler returns 0 which causes [sqlite3_step()] to return
  2035. ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  2036. **
  2037. ** ^Calling this routine with an argument less than or equal to zero
  2038. ** turns off all busy handlers.
  2039. **
  2040. ** ^(There can only be a single busy handler for a particular
  2041. ** [database connection] any any given moment. If another busy handler
  2042. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2043. ** this routine, that other busy handler is cleared.)^
  2044. */
  2045. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2046. /*
  2047. ** CAPI3REF: Convenience Routines For Running Queries
  2048. **
  2049. ** This is a legacy interface that is preserved for backwards compatibility.
  2050. ** Use of this interface is not recommended.
  2051. **
  2052. ** Definition: A <b>result table</b> is memory data structure created by the
  2053. ** [sqlite3_get_table()] interface. A result table records the
  2054. ** complete query results from one or more queries.
  2055. **
  2056. ** The table conceptually has a number of rows and columns. But
  2057. ** these numbers are not part of the result table itself. These
  2058. ** numbers are obtained separately. Let N be the number of rows
  2059. ** and M be the number of columns.
  2060. **
  2061. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2062. ** There are (N+1)*M elements in the array. The first M pointers point
  2063. ** to zero-terminated strings that contain the names of the columns.
  2064. ** The remaining entries all point to query results. NULL values result
  2065. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2066. ** string representation as returned by [sqlite3_column_text()].
  2067. **
  2068. ** A result table might consist of one or more memory allocations.
  2069. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2070. ** A result table should be deallocated using [sqlite3_free_table()].
  2071. **
  2072. ** ^(As an example of the result table format, suppose a query result
  2073. ** is as follows:
  2074. **
  2075. ** <blockquote><pre>
  2076. ** Name | Age
  2077. ** -----------------------
  2078. ** Alice | 43
  2079. ** Bob | 28
  2080. ** Cindy | 21
  2081. ** </pre></blockquote>
  2082. **
  2083. ** There are two column (M==2) and three rows (N==3). Thus the
  2084. ** result table has 8 entries. Suppose the result table is stored
  2085. ** in an array names azResult. Then azResult holds this content:
  2086. **
  2087. ** <blockquote><pre>
  2088. ** azResult&#91;0] = "Name";
  2089. ** azResult&#91;1] = "Age";
  2090. ** azResult&#91;2] = "Alice";
  2091. ** azResult&#91;3] = "43";
  2092. ** azResult&#91;4] = "Bob";
  2093. ** azResult&#91;5] = "28";
  2094. ** azResult&#91;6] = "Cindy";
  2095. ** azResult&#91;7] = "21";
  2096. ** </pre></blockquote>)^
  2097. **
  2098. ** ^The sqlite3_get_table() function evaluates one or more
  2099. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2100. ** string of its 2nd parameter and returns a result table to the
  2101. ** pointer given in its 3rd parameter.
  2102. **
  2103. ** After the application has finished with the result from sqlite3_get_table(),
  2104. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2105. ** release the memory that was malloced. Because of the way the
  2106. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2107. ** function must not try to call [sqlite3_free()] directly. Only
  2108. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2109. **
  2110. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2111. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2112. ** to any internal data structures of SQLite. It uses only the public
  2113. ** interface defined here. As a consequence, errors that occur in the
  2114. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2115. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2116. ** [sqlite3_errmsg()].
  2117. */
  2118. SQLITE_API int sqlite3_get_table(
  2119. sqlite3 *db, /* An open database */
  2120. const char *zSql, /* SQL to be evaluated */
  2121. char ***pazResult, /* Results of the query */
  2122. int *pnRow, /* Number of result rows written here */
  2123. int *pnColumn, /* Number of result columns written here */
  2124. char **pzErrmsg /* Error msg written here */
  2125. );
  2126. SQLITE_API void sqlite3_free_table(char **result);
  2127. /*
  2128. ** CAPI3REF: Formatted String Printing Functions
  2129. **
  2130. ** These routines are work-alikes of the "printf()" family of functions
  2131. ** from the standard C library.
  2132. **
  2133. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2134. ** results into memory obtained from [sqlite3_malloc()].
  2135. ** The strings returned by these two routines should be
  2136. ** released by [sqlite3_free()]. ^Both routines return a
  2137. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2138. ** memory to hold the resulting string.
  2139. **
  2140. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2141. ** the standard C library. The result is written into the
  2142. ** buffer supplied as the second parameter whose size is given by
  2143. ** the first parameter. Note that the order of the
  2144. ** first two parameters is reversed from snprintf().)^ This is an
  2145. ** historical accident that cannot be fixed without breaking
  2146. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2147. ** returns a pointer to its buffer instead of the number of
  2148. ** characters actually written into the buffer.)^ We admit that
  2149. ** the number of characters written would be a more useful return
  2150. ** value but we cannot change the implementation of sqlite3_snprintf()
  2151. ** now without breaking compatibility.
  2152. **
  2153. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2154. ** guarantees that the buffer is always zero-terminated. ^The first
  2155. ** parameter "n" is the total size of the buffer, including space for
  2156. ** the zero terminator. So the longest string that can be completely
  2157. ** written will be n-1 characters.
  2158. **
  2159. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2160. **
  2161. ** These routines all implement some additional formatting
  2162. ** options that are useful for constructing SQL statements.
  2163. ** All of the usual printf() formatting options apply. In addition, there
  2164. ** is are "%q", "%Q", and "%z" options.
  2165. **
  2166. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2167. ** string from the argument list. But %q also doubles every '\'' character.
  2168. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2169. ** character it escapes that character and allows it to be inserted into
  2170. ** the string.
  2171. **
  2172. ** For example, assume the string variable zText contains text as follows:
  2173. **
  2174. ** <blockquote><pre>
  2175. ** char *zText = "It's a happy day!";
  2176. ** </pre></blockquote>
  2177. **
  2178. ** One can use this text in an SQL statement as follows:
  2179. **
  2180. ** <blockquote><pre>
  2181. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2182. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2183. ** sqlite3_free(zSQL);
  2184. ** </pre></blockquote>
  2185. **
  2186. ** Because the %q format string is used, the '\'' character in zText
  2187. ** is escaped and the SQL generated is as follows:
  2188. **
  2189. ** <blockquote><pre>
  2190. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2191. ** </pre></blockquote>
  2192. **
  2193. ** This is correct. Had we used %s instead of %q, the generated SQL
  2194. ** would have looked like this:
  2195. **
  2196. ** <blockquote><pre>
  2197. ** INSERT INTO table1 VALUES('It's a happy day!');
  2198. ** </pre></blockquote>
  2199. **
  2200. ** This second example is an SQL syntax error. As a general rule you should
  2201. ** always use %q instead of %s when inserting text into a string literal.
  2202. **
  2203. ** ^(The %Q option works like %q except it also adds single quotes around
  2204. ** the outside of the total string. Additionally, if the parameter in the
  2205. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2206. ** single quotes).)^ So, for example, one could say:
  2207. **
  2208. ** <blockquote><pre>
  2209. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2210. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2211. ** sqlite3_free(zSQL);
  2212. ** </pre></blockquote>
  2213. **
  2214. ** The code above will render a correct SQL statement in the zSQL
  2215. ** variable even if the zText variable is a NULL pointer.
  2216. **
  2217. ** ^(The "%z" formatting option works like "%s" but with the
  2218. ** addition that after the string has been read and copied into
  2219. ** the result, [sqlite3_free()] is called on the input string.)^
  2220. */
  2221. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2222. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2223. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2224. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2225. /*
  2226. ** CAPI3REF: Memory Allocation Subsystem
  2227. **
  2228. ** The SQLite core uses these three routines for all of its own
  2229. ** internal memory allocation needs. "Core" in the previous sentence
  2230. ** does not include operating-system specific VFS implementation. The
  2231. ** Windows VFS uses native malloc() and free() for some operations.
  2232. **
  2233. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2234. ** of memory at least N bytes in length, where N is the parameter.
  2235. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2236. ** memory, it returns a NULL pointer. ^If the parameter N to
  2237. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2238. ** a NULL pointer.
  2239. **
  2240. ** ^Calling sqlite3_free() with a pointer previously returned
  2241. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2242. ** that it might be reused. ^The sqlite3_free() routine is
  2243. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2244. ** to sqlite3_free() is harmless. After being freed, memory
  2245. ** should neither be read nor written. Even reading previously freed
  2246. ** memory might result in a segmentation fault or other severe error.
  2247. ** Memory corruption, a segmentation fault, or other severe error
  2248. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2249. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2250. **
  2251. ** ^(The sqlite3_realloc() interface attempts to resize a
  2252. ** prior memory allocation to be at least N bytes, where N is the
  2253. ** second parameter. The memory allocation to be resized is the first
  2254. ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
  2255. ** is a NULL pointer then its behavior is identical to calling
  2256. ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  2257. ** ^If the second parameter to sqlite3_realloc() is zero or
  2258. ** negative then the behavior is exactly the same as calling
  2259. ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  2260. ** ^sqlite3_realloc() returns a pointer to a memory allocation
  2261. ** of at least N bytes in size or NULL if sufficient memory is unavailable.
  2262. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2263. ** of the prior allocation are copied into the beginning of buffer returned
  2264. ** by sqlite3_realloc() and the prior allocation is freed.
  2265. ** ^If sqlite3_realloc() returns NULL, then the prior allocation
  2266. ** is not freed.
  2267. **
  2268. ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
  2269. ** is always aligned to at least an 8 byte boundary, or to a
  2270. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2271. ** option is used.
  2272. **
  2273. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2274. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2275. ** implementation of these routines to be omitted. That capability
  2276. ** is no longer provided. Only built-in memory allocators can be used.
  2277. **
  2278. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2279. ** the system malloc() and free() directly when converting
  2280. ** filenames between the UTF-8 encoding used by SQLite
  2281. ** and whatever filename encoding is used by the particular Windows
  2282. ** installation. Memory allocation errors were detected, but
  2283. ** they were reported back as [SQLITE_CANTOPEN] or
  2284. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2285. **
  2286. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2287. ** must be either NULL or else pointers obtained from a prior
  2288. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2289. ** not yet been released.
  2290. **
  2291. ** The application must not read or write any part of
  2292. ** a block of memory after it has been released using
  2293. ** [sqlite3_free()] or [sqlite3_realloc()].
  2294. */
  2295. SQLITE_API void *sqlite3_malloc(int);
  2296. SQLITE_API void *sqlite3_realloc(void*, int);
  2297. SQLITE_API void sqlite3_free(void*);
  2298. /*
  2299. ** CAPI3REF: Memory Allocator Statistics
  2300. **
  2301. ** SQLite provides these two interfaces for reporting on the status
  2302. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2303. ** routines, which form the built-in memory allocation subsystem.
  2304. **
  2305. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2306. ** of memory currently outstanding (malloced but not freed).
  2307. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2308. ** value of [sqlite3_memory_used()] since the high-water mark
  2309. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2310. ** [sqlite3_memory_highwater()] include any overhead
  2311. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2312. ** but not overhead added by the any underlying system library
  2313. ** routines that [sqlite3_malloc()] may call.
  2314. **
  2315. ** ^The memory high-water mark is reset to the current value of
  2316. ** [sqlite3_memory_used()] if and only if the parameter to
  2317. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2318. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2319. ** prior to the reset.
  2320. */
  2321. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2322. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2323. /*
  2324. ** CAPI3REF: Pseudo-Random Number Generator
  2325. **
  2326. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2327. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2328. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2329. ** the build-in random() and randomblob() SQL functions. This interface allows
  2330. ** applications to access the same PRNG for other purposes.
  2331. **
  2332. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2333. **
  2334. ** ^The first time this routine is invoked (either internally or by
  2335. ** the application) the PRNG is seeded using randomness obtained
  2336. ** from the xRandomness method of the default [sqlite3_vfs] object.
  2337. ** ^On all subsequent invocations, the pseudo-randomness is generated
  2338. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2339. ** method.
  2340. */
  2341. SQLITE_API void sqlite3_randomness(int N, void *P);
  2342. /*
  2343. ** CAPI3REF: Compile-Time Authorization Callbacks
  2344. **
  2345. ** ^This routine registers an authorizer callback with a particular
  2346. ** [database connection], supplied in the first argument.
  2347. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2348. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2349. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2350. ** points during the compilation process, as logic is being created
  2351. ** to perform various actions, the authorizer callback is invoked to
  2352. ** see if those actions are allowed. ^The authorizer callback should
  2353. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2354. ** specific action but allow the SQL statement to continue to be
  2355. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2356. ** rejected with an error. ^If the authorizer callback returns
  2357. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2358. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2359. ** the authorizer will fail with an error message.
  2360. **
  2361. ** When the callback returns [SQLITE_OK], that means the operation
  2362. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2363. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2364. ** authorizer will fail with an error message explaining that
  2365. ** access is denied.
  2366. **
  2367. ** ^The first parameter to the authorizer callback is a copy of the third
  2368. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2369. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2370. ** the particular action to be authorized. ^The third through sixth parameters
  2371. ** to the callback are zero-terminated strings that contain additional
  2372. ** details about the action to be authorized.
  2373. **
  2374. ** ^If the action code is [SQLITE_READ]
  2375. ** and the callback returns [SQLITE_IGNORE] then the
  2376. ** [prepared statement] statement is constructed to substitute
  2377. ** a NULL value in place of the table column that would have
  2378. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2379. ** return can be used to deny an untrusted user access to individual
  2380. ** columns of a table.
  2381. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2382. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2383. ** [truncate optimization] is disabled and all rows are deleted individually.
  2384. **
  2385. ** An authorizer is used when [sqlite3_prepare | preparing]
  2386. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2387. ** do not try to access data they are not allowed to see, or that they do not
  2388. ** try to execute malicious statements that damage the database. For
  2389. ** example, an application may allow a user to enter arbitrary
  2390. ** SQL queries for evaluation by a database. But the application does
  2391. ** not want the user to be able to make arbitrary changes to the
  2392. ** database. An authorizer could then be put in place while the
  2393. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2394. ** disallows everything except [SELECT] statements.
  2395. **
  2396. ** Applications that need to process SQL from untrusted sources
  2397. ** might also consider lowering resource limits using [sqlite3_limit()]
  2398. ** and limiting database size using the [max_page_count] [PRAGMA]
  2399. ** in addition to using an authorizer.
  2400. **
  2401. ** ^(Only a single authorizer can be in place on a database connection
  2402. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2403. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2404. ** The authorizer is disabled by default.
  2405. **
  2406. ** The authorizer callback must not do anything that will modify
  2407. ** the database connection that invoked the authorizer callback.
  2408. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2409. ** database connections for the meaning of "modify" in this paragraph.
  2410. **
  2411. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2412. ** statement might be re-prepared during [sqlite3_step()] due to a
  2413. ** schema change. Hence, the application should ensure that the
  2414. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2415. **
  2416. ** ^Note that the authorizer callback is invoked only during
  2417. ** [sqlite3_prepare()] or its variants. Authorization is not
  2418. ** performed during statement evaluation in [sqlite3_step()], unless
  2419. ** as stated in the previous paragraph, sqlite3_step() invokes
  2420. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2421. */
  2422. SQLITE_API int sqlite3_set_authorizer(
  2423. sqlite3*,
  2424. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2425. void *pUserData
  2426. );
  2427. /*
  2428. ** CAPI3REF: Authorizer Return Codes
  2429. **
  2430. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2431. ** return either [SQLITE_OK] or one of these two constants in order
  2432. ** to signal SQLite whether or not the action is permitted. See the
  2433. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2434. ** information.
  2435. **
  2436. ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
  2437. ** from the [sqlite3_vtab_on_conflict()] interface.
  2438. */
  2439. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2440. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2441. /*
  2442. ** CAPI3REF: Authorizer Action Codes
  2443. **
  2444. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2445. ** that is invoked to authorize certain SQL statement actions. The
  2446. ** second parameter to the callback is an integer code that specifies
  2447. ** what action is being authorized. These are the integer action codes that
  2448. ** the authorizer callback may be passed.
  2449. **
  2450. ** These action code values signify what kind of operation is to be
  2451. ** authorized. The 3rd and 4th parameters to the authorization
  2452. ** callback function will be parameters or NULL depending on which of these
  2453. ** codes is used as the second parameter. ^(The 5th parameter to the
  2454. ** authorizer callback is the name of the database ("main", "temp",
  2455. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2456. ** is the name of the inner-most trigger or view that is responsible for
  2457. ** the access attempt or NULL if this access attempt is directly from
  2458. ** top-level SQL code.
  2459. */
  2460. /******************************************* 3rd ************ 4th ***********/
  2461. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2462. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2463. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2464. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2465. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2466. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2467. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2468. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2469. #define SQLITE_DELETE 9 /* Table Name NULL */
  2470. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2471. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2472. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2473. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2474. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2475. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2476. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2477. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2478. #define SQLITE_INSERT 18 /* Table Name NULL */
  2479. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2480. #define SQLITE_READ 20 /* Table Name Column Name */
  2481. #define SQLITE_SELECT 21 /* NULL NULL */
  2482. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2483. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2484. #define SQLITE_ATTACH 24 /* Filename NULL */
  2485. #define SQLITE_DETACH 25 /* Database Name NULL */
  2486. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2487. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2488. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2489. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2490. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2491. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2492. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2493. #define SQLITE_COPY 0 /* No longer used */
  2494. /*
  2495. ** CAPI3REF: Tracing And Profiling Functions
  2496. **
  2497. ** These routines register callback functions that can be used for
  2498. ** tracing and profiling the execution of SQL statements.
  2499. **
  2500. ** ^The callback function registered by sqlite3_trace() is invoked at
  2501. ** various times when an SQL statement is being run by [sqlite3_step()].
  2502. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2503. ** SQL statement text as the statement first begins executing.
  2504. ** ^(Additional sqlite3_trace() callbacks might occur
  2505. ** as each triggered subprogram is entered. The callbacks for triggers
  2506. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2507. **
  2508. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  2509. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  2510. **
  2511. ** ^The callback function registered by sqlite3_profile() is invoked
  2512. ** as each SQL statement finishes. ^The profile callback contains
  2513. ** the original statement text and an estimate of wall-clock time
  2514. ** of how long that statement took to run. ^The profile callback
  2515. ** time is in units of nanoseconds, however the current implementation
  2516. ** is only capable of millisecond resolution so the six least significant
  2517. ** digits in the time are meaningless. Future versions of SQLite
  2518. ** might provide greater resolution on the profiler callback. The
  2519. ** sqlite3_profile() function is considered experimental and is
  2520. ** subject to change in future versions of SQLite.
  2521. */
  2522. SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2523. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  2524. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2525. /*
  2526. ** CAPI3REF: Query Progress Callbacks
  2527. **
  2528. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2529. ** function X to be invoked periodically during long running calls to
  2530. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2531. ** database connection D. An example use for this
  2532. ** interface is to keep a GUI updated during a large query.
  2533. **
  2534. ** ^The parameter P is passed through as the only parameter to the
  2535. ** callback function X. ^The parameter N is the approximate number of
  2536. ** [virtual machine instructions] that are evaluated between successive
  2537. ** invocations of the callback X. ^If N is less than one then the progress
  2538. ** handler is disabled.
  2539. **
  2540. ** ^Only a single progress handler may be defined at one time per
  2541. ** [database connection]; setting a new progress handler cancels the
  2542. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2543. ** ^The progress handler is also disabled by setting N to a value less
  2544. ** than 1.
  2545. **
  2546. ** ^If the progress callback returns non-zero, the operation is
  2547. ** interrupted. This feature can be used to implement a
  2548. ** "Cancel" button on a GUI progress dialog box.
  2549. **
  2550. ** The progress handler callback must not do anything that will modify
  2551. ** the database connection that invoked the progress handler.
  2552. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2553. ** database connections for the meaning of "modify" in this paragraph.
  2554. **
  2555. */
  2556. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2557. /*
  2558. ** CAPI3REF: Opening A New Database Connection
  2559. **
  2560. ** ^These routines open an SQLite database file as specified by the
  2561. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2562. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2563. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2564. ** returned in *ppDb, even if an error occurs. The only exception is that
  2565. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2566. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2567. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2568. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2569. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2570. ** an English language description of the error following a failure of any
  2571. ** of the sqlite3_open() routines.
  2572. **
  2573. ** ^The default encoding for the database will be UTF-8 if
  2574. ** sqlite3_open() or sqlite3_open_v2() is called and
  2575. ** UTF-16 in the native byte order if sqlite3_open16() is used.
  2576. **
  2577. ** Whether or not an error occurs when it is opened, resources
  2578. ** associated with the [database connection] handle should be released by
  2579. ** passing it to [sqlite3_close()] when it is no longer required.
  2580. **
  2581. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2582. ** except that it accepts two additional parameters for additional control
  2583. ** over the new database connection. ^(The flags parameter to
  2584. ** sqlite3_open_v2() can take one of
  2585. ** the following three values, optionally combined with the
  2586. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2587. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2588. **
  2589. ** <dl>
  2590. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2591. ** <dd>The database is opened in read-only mode. If the database does not
  2592. ** already exist, an error is returned.</dd>)^
  2593. **
  2594. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2595. ** <dd>The database is opened for reading and writing if possible, or reading
  2596. ** only if the file is write protected by the operating system. In either
  2597. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2598. **
  2599. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2600. ** <dd>The database is opened for reading and writing, and is created if
  2601. ** it does not already exist. This is the behavior that is always used for
  2602. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2603. ** </dl>
  2604. **
  2605. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2606. ** combinations shown above optionally combined with other
  2607. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  2608. ** then the behavior is undefined.
  2609. **
  2610. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2611. ** opens in the multi-thread [threading mode] as long as the single-thread
  2612. ** mode has not been set at compile-time or start-time. ^If the
  2613. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2614. ** in the serialized [threading mode] unless single-thread was
  2615. ** previously selected at compile-time or start-time.
  2616. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2617. ** eligible to use [shared cache mode], regardless of whether or not shared
  2618. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2619. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2620. ** participate in [shared cache mode] even if it is enabled.
  2621. **
  2622. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2623. ** [sqlite3_vfs] object that defines the operating system interface that
  2624. ** the new database connection should use. ^If the fourth parameter is
  2625. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2626. **
  2627. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2628. ** is created for the connection. ^This in-memory database will vanish when
  2629. ** the database connection is closed. Future versions of SQLite might
  2630. ** make use of additional special filenames that begin with the ":" character.
  2631. ** It is recommended that when a database filename actually does begin with
  2632. ** a ":" character you should prefix the filename with a pathname such as
  2633. ** "./" to avoid ambiguity.
  2634. **
  2635. ** ^If the filename is an empty string, then a private, temporary
  2636. ** on-disk database will be created. ^This private database will be
  2637. ** automatically deleted as soon as the database connection is closed.
  2638. **
  2639. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  2640. **
  2641. ** ^If [URI filename] interpretation is enabled, and the filename argument
  2642. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  2643. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  2644. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  2645. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  2646. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  2647. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  2648. ** by default, but future releases of SQLite might enable URI filename
  2649. ** interpretation by default. See "[URI filenames]" for additional
  2650. ** information.
  2651. **
  2652. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  2653. ** authority, then it must be either an empty string or the string
  2654. ** "localhost". ^If the authority is not an empty string or "localhost", an
  2655. ** error is returned to the caller. ^The fragment component of a URI, if
  2656. ** present, is ignored.
  2657. **
  2658. ** ^SQLite uses the path component of the URI as the name of the disk file
  2659. ** which contains the database. ^If the path begins with a '/' character,
  2660. ** then it is interpreted as an absolute path. ^If the path does not begin
  2661. ** with a '/' (meaning that the authority section is omitted from the URI)
  2662. ** then the path is interpreted as a relative path.
  2663. ** ^On windows, the first component of an absolute path
  2664. ** is a drive specification (e.g. "C:").
  2665. **
  2666. ** [[core URI query parameters]]
  2667. ** The query component of a URI may contain parameters that are interpreted
  2668. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  2669. ** SQLite interprets the following three query parameters:
  2670. **
  2671. ** <ul>
  2672. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  2673. ** a VFS object that provides the operating system interface that should
  2674. ** be used to access the database file on disk. ^If this option is set to
  2675. ** an empty string the default VFS object is used. ^Specifying an unknown
  2676. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  2677. ** present, then the VFS specified by the option takes precedence over
  2678. ** the value passed as the fourth parameter to sqlite3_open_v2().
  2679. **
  2680. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  2681. ** "rwc", or "memory". Attempting to set it to any other value is
  2682. ** an error)^.
  2683. ** ^If "ro" is specified, then the database is opened for read-only
  2684. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  2685. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  2686. ** "rw", then the database is opened for read-write (but not create)
  2687. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  2688. ** been set. ^Value "rwc" is equivalent to setting both
  2689. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  2690. ** set to "memory" then a pure [in-memory database] that never reads
  2691. ** or writes from disk is used. ^It is an error to specify a value for
  2692. ** the mode parameter that is less restrictive than that specified by
  2693. ** the flags passed in the third parameter to sqlite3_open_v2().
  2694. **
  2695. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  2696. ** "private". ^Setting it to "shared" is equivalent to setting the
  2697. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  2698. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  2699. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  2700. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  2701. ** a URI filename, its value overrides any behavior requested by setting
  2702. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  2703. ** </ul>
  2704. **
  2705. ** ^Specifying an unknown parameter in the query component of a URI is not an
  2706. ** error. Future versions of SQLite might understand additional query
  2707. ** parameters. See "[query parameters with special meaning to SQLite]" for
  2708. ** additional information.
  2709. **
  2710. ** [[URI filename examples]] <h3>URI filename examples</h3>
  2711. **
  2712. ** <table border="1" align=center cellpadding=5>
  2713. ** <tr><th> URI filenames <th> Results
  2714. ** <tr><td> file:data.db <td>
  2715. ** Open the file "data.db" in the current directory.
  2716. ** <tr><td> file:/home/fred/data.db<br>
  2717. ** file:///home/fred/data.db <br>
  2718. ** file://localhost/home/fred/data.db <br> <td>
  2719. ** Open the database file "/home/fred/data.db".
  2720. ** <tr><td> file://darkstar/home/fred/data.db <td>
  2721. ** An error. "darkstar" is not a recognized authority.
  2722. ** <tr><td style="white-space:nowrap">
  2723. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  2724. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  2725. ** C:. Note that the %20 escaping in this example is not strictly
  2726. ** necessary - space characters can be used literally
  2727. ** in URI filenames.
  2728. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  2729. ** Open file "data.db" in the current directory for read-only access.
  2730. ** Regardless of whether or not shared-cache mode is enabled by
  2731. ** default, use a private cache.
  2732. ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
  2733. ** Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
  2734. ** <tr><td> file:data.db?mode=readonly <td>
  2735. ** An error. "readonly" is not a valid option for the "mode" parameter.
  2736. ** </table>
  2737. **
  2738. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  2739. ** query components of a URI. A hexadecimal escape sequence consists of a
  2740. ** percent sign - "%" - followed by exactly two hexadecimal digits
  2741. ** specifying an octet value. ^Before the path or query components of a
  2742. ** URI filename are interpreted, they are encoded using UTF-8 and all
  2743. ** hexadecimal escape sequences replaced by a single byte containing the
  2744. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  2745. ** the results are undefined.
  2746. **
  2747. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  2748. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  2749. ** codepage is currently defined. Filenames containing international
  2750. ** characters must be converted to UTF-8 prior to passing them into
  2751. ** sqlite3_open() or sqlite3_open_v2().
  2752. **
  2753. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  2754. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  2755. ** features that require the use of temporary files may fail.
  2756. **
  2757. ** See also: [sqlite3_temp_directory]
  2758. */
  2759. SQLITE_API int sqlite3_open(
  2760. const char *filename, /* Database filename (UTF-8) */
  2761. sqlite3 **ppDb /* OUT: SQLite db handle */
  2762. );
  2763. SQLITE_API int sqlite3_open16(
  2764. const void *filename, /* Database filename (UTF-16) */
  2765. sqlite3 **ppDb /* OUT: SQLite db handle */
  2766. );
  2767. SQLITE_API int sqlite3_open_v2(
  2768. const char *filename, /* Database filename (UTF-8) */
  2769. sqlite3 **ppDb, /* OUT: SQLite db handle */
  2770. int flags, /* Flags */
  2771. const char *zVfs /* Name of VFS module to use */
  2772. );
  2773. /*
  2774. ** CAPI3REF: Obtain Values For URI Parameters
  2775. **
  2776. ** These are utility routines, useful to VFS implementations, that check
  2777. ** to see if a database file was a URI that contained a specific query
  2778. ** parameter, and if so obtains the value of that query parameter.
  2779. **
  2780. ** If F is the database filename pointer passed into the xOpen() method of
  2781. ** a VFS implementation when the flags parameter to xOpen() has one or
  2782. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  2783. ** P is the name of the query parameter, then
  2784. ** sqlite3_uri_parameter(F,P) returns the value of the P
  2785. ** parameter if it exists or a NULL pointer if P does not appear as a
  2786. ** query parameter on F. If P is a query parameter of F
  2787. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  2788. ** a pointer to an empty string.
  2789. **
  2790. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  2791. ** parameter and returns true (1) or false (0) according to the value
  2792. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  2793. ** value of query parameter P is one of "yes", "true", or "on" in any
  2794. ** case or if the value begins with a non-zero number. The
  2795. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  2796. ** query parameter P is one of "no", "false", or "off" in any case or
  2797. ** if the value begins with a numeric zero. If P is not a query
  2798. ** parameter on F or if the value of P is does not match any of the
  2799. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  2800. **
  2801. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  2802. ** 64-bit signed integer and returns that integer, or D if P does not
  2803. ** exist. If the value of P is something other than an integer, then
  2804. ** zero is returned.
  2805. **
  2806. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  2807. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  2808. ** is not a database file pathname pointer that SQLite passed into the xOpen
  2809. ** VFS method, then the behavior of this routine is undefined and probably
  2810. ** undesirable.
  2811. */
  2812. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  2813. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  2814. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  2815. /*
  2816. ** CAPI3REF: Error Codes And Messages
  2817. **
  2818. ** ^The sqlite3_errcode() interface returns the numeric [result code] or
  2819. ** [extended result code] for the most recent failed sqlite3_* API call
  2820. ** associated with a [database connection]. If a prior API call failed
  2821. ** but the most recent API call succeeded, the return value from
  2822. ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
  2823. ** interface is the same except that it always returns the
  2824. ** [extended result code] even when extended result codes are
  2825. ** disabled.
  2826. **
  2827. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  2828. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  2829. ** ^(Memory to hold the error message string is managed internally.
  2830. ** The application does not need to worry about freeing the result.
  2831. ** However, the error string might be overwritten or deallocated by
  2832. ** subsequent calls to other SQLite interface functions.)^
  2833. **
  2834. ** ^The sqlite3_errstr() interface returns the English-language text
  2835. ** that describes the [result code], as UTF-8.
  2836. ** ^(Memory to hold the error message string is managed internally
  2837. ** and must not be freed by the application)^.
  2838. **
  2839. ** When the serialized [threading mode] is in use, it might be the
  2840. ** case that a second error occurs on a separate thread in between
  2841. ** the time of the first error and the call to these interfaces.
  2842. ** When that happens, the second error will be reported since these
  2843. ** interfaces always report the most recent result. To avoid
  2844. ** this, each thread can obtain exclusive use of the [database connection] D
  2845. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  2846. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  2847. ** all calls to the interfaces listed here are completed.
  2848. **
  2849. ** If an interface fails with SQLITE_MISUSE, that means the interface
  2850. ** was invoked incorrectly by the application. In that case, the
  2851. ** error code and message may or may not be set.
  2852. */
  2853. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  2854. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  2855. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  2856. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  2857. SQLITE_API const char *sqlite3_errstr(int);
  2858. /*
  2859. ** CAPI3REF: SQL Statement Object
  2860. ** KEYWORDS: {prepared statement} {prepared statements}
  2861. **
  2862. ** An instance of this object represents a single SQL statement.
  2863. ** This object is variously known as a "prepared statement" or a
  2864. ** "compiled SQL statement" or simply as a "statement".
  2865. **
  2866. ** The life of a statement object goes something like this:
  2867. **
  2868. ** <ol>
  2869. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  2870. ** function.
  2871. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  2872. ** interfaces.
  2873. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  2874. ** <li> Reset the statement using [sqlite3_reset()] then go back
  2875. ** to step 2. Do this zero or more times.
  2876. ** <li> Destroy the object using [sqlite3_finalize()].
  2877. ** </ol>
  2878. **
  2879. ** Refer to documentation on individual methods above for additional
  2880. ** information.
  2881. */
  2882. typedef struct sqlite3_stmt sqlite3_stmt;
  2883. /*
  2884. ** CAPI3REF: Run-time Limits
  2885. **
  2886. ** ^(This interface allows the size of various constructs to be limited
  2887. ** on a connection by connection basis. The first parameter is the
  2888. ** [database connection] whose limit is to be set or queried. The
  2889. ** second parameter is one of the [limit categories] that define a
  2890. ** class of constructs to be size limited. The third parameter is the
  2891. ** new limit for that construct.)^
  2892. **
  2893. ** ^If the new limit is a negative number, the limit is unchanged.
  2894. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  2895. ** [limits | hard upper bound]
  2896. ** set at compile-time by a C preprocessor macro called
  2897. ** [limits | SQLITE_MAX_<i>NAME</i>].
  2898. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  2899. ** ^Attempts to increase a limit above its hard upper bound are
  2900. ** silently truncated to the hard upper bound.
  2901. **
  2902. ** ^Regardless of whether or not the limit was changed, the
  2903. ** [sqlite3_limit()] interface returns the prior value of the limit.
  2904. ** ^Hence, to find the current value of a limit without changing it,
  2905. ** simply invoke this interface with the third parameter set to -1.
  2906. **
  2907. ** Run-time limits are intended for use in applications that manage
  2908. ** both their own internal database and also databases that are controlled
  2909. ** by untrusted external sources. An example application might be a
  2910. ** web browser that has its own databases for storing history and
  2911. ** separate databases controlled by JavaScript applications downloaded
  2912. ** off the Internet. The internal databases can be given the
  2913. ** large, default limits. Databases managed by external sources can
  2914. ** be given much smaller limits designed to prevent a denial of service
  2915. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  2916. ** interface to further control untrusted SQL. The size of the database
  2917. ** created by an untrusted script can be contained using the
  2918. ** [max_page_count] [PRAGMA].
  2919. **
  2920. ** New run-time limit categories may be added in future releases.
  2921. */
  2922. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  2923. /*
  2924. ** CAPI3REF: Run-Time Limit Categories
  2925. ** KEYWORDS: {limit category} {*limit categories}
  2926. **
  2927. ** These constants define various performance limits
  2928. ** that can be lowered at run-time using [sqlite3_limit()].
  2929. ** The synopsis of the meanings of the various limits is shown below.
  2930. ** Additional information is available at [limits | Limits in SQLite].
  2931. **
  2932. ** <dl>
  2933. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  2934. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  2935. **
  2936. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  2937. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  2938. **
  2939. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  2940. ** <dd>The maximum number of columns in a table definition or in the
  2941. ** result set of a [SELECT] or the maximum number of columns in an index
  2942. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  2943. **
  2944. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  2945. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  2946. **
  2947. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  2948. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  2949. **
  2950. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  2951. ** <dd>The maximum number of instructions in a virtual machine program
  2952. ** used to implement an SQL statement. This limit is not currently
  2953. ** enforced, though that might be added in some future release of
  2954. ** SQLite.</dd>)^
  2955. **
  2956. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  2957. ** <dd>The maximum number of arguments on a function.</dd>)^
  2958. **
  2959. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  2960. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  2961. **
  2962. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  2963. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  2964. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  2965. ** [GLOB] operators.</dd>)^
  2966. **
  2967. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  2968. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  2969. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  2970. **
  2971. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  2972. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  2973. ** </dl>
  2974. */
  2975. #define SQLITE_LIMIT_LENGTH 0
  2976. #define SQLITE_LIMIT_SQL_LENGTH 1
  2977. #define SQLITE_LIMIT_COLUMN 2
  2978. #define SQLITE_LIMIT_EXPR_DEPTH 3
  2979. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  2980. #define SQLITE_LIMIT_VDBE_OP 5
  2981. #define SQLITE_LIMIT_FUNCTION_ARG 6
  2982. #define SQLITE_LIMIT_ATTACHED 7
  2983. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  2984. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  2985. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  2986. /*
  2987. ** CAPI3REF: Compiling An SQL Statement
  2988. ** KEYWORDS: {SQL statement compiler}
  2989. **
  2990. ** To execute an SQL query, it must first be compiled into a byte-code
  2991. ** program using one of these routines.
  2992. **
  2993. ** The first argument, "db", is a [database connection] obtained from a
  2994. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  2995. ** [sqlite3_open16()]. The database connection must not have been closed.
  2996. **
  2997. ** The second argument, "zSql", is the statement to be compiled, encoded
  2998. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  2999. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3000. ** use UTF-16.
  3001. **
  3002. ** ^If the nByte argument is less than zero, then zSql is read up to the
  3003. ** first zero terminator. ^If nByte is non-negative, then it is the maximum
  3004. ** number of bytes read from zSql. ^When nByte is non-negative, the
  3005. ** zSql string ends at either the first '\000' or '\u0000' character or
  3006. ** the nByte-th byte, whichever comes first. If the caller knows
  3007. ** that the supplied string is nul-terminated, then there is a small
  3008. ** performance advantage to be gained by passing an nByte parameter that
  3009. ** is equal to the number of bytes in the input string <i>including</i>
  3010. ** the nul-terminator bytes as this saves SQLite from having to
  3011. ** make a copy of the input string.
  3012. **
  3013. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3014. ** past the end of the first SQL statement in zSql. These routines only
  3015. ** compile the first statement in zSql, so *pzTail is left pointing to
  3016. ** what remains uncompiled.
  3017. **
  3018. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3019. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3020. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3021. ** string or a comment) then *ppStmt is set to NULL.
  3022. ** The calling procedure is responsible for deleting the compiled
  3023. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3024. ** ppStmt may not be NULL.
  3025. **
  3026. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3027. ** otherwise an [error code] is returned.
  3028. **
  3029. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3030. ** recommended for all new programs. The two older interfaces are retained
  3031. ** for backwards compatibility, but their use is discouraged.
  3032. ** ^In the "v2" interfaces, the prepared statement
  3033. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3034. ** original SQL text. This causes the [sqlite3_step()] interface to
  3035. ** behave differently in three ways:
  3036. **
  3037. ** <ol>
  3038. ** <li>
  3039. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3040. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3041. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3042. ** retries will occur before sqlite3_step() gives up and returns an error.
  3043. ** </li>
  3044. **
  3045. ** <li>
  3046. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3047. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3048. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3049. ** and the application would have to make a second call to [sqlite3_reset()]
  3050. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3051. ** interfaces, the underlying reason for the error is returned immediately.
  3052. ** </li>
  3053. **
  3054. ** <li>
  3055. ** ^If the specific value bound to [parameter | host parameter] in the
  3056. ** WHERE clause might influence the choice of query plan for a statement,
  3057. ** then the statement will be automatically recompiled, as if there had been
  3058. ** a schema change, on the first [sqlite3_step()] call following any change
  3059. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3060. ** ^The specific value of WHERE-clause [parameter] might influence the
  3061. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3062. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3063. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3064. ** the
  3065. ** </li>
  3066. ** </ol>
  3067. */
  3068. SQLITE_API int sqlite3_prepare(
  3069. sqlite3 *db, /* Database handle */
  3070. const char *zSql, /* SQL statement, UTF-8 encoded */
  3071. int nByte, /* Maximum length of zSql in bytes. */
  3072. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3073. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3074. );
  3075. SQLITE_API int sqlite3_prepare_v2(
  3076. sqlite3 *db, /* Database handle */
  3077. const char *zSql, /* SQL statement, UTF-8 encoded */
  3078. int nByte, /* Maximum length of zSql in bytes. */
  3079. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3080. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3081. );
  3082. SQLITE_API int sqlite3_prepare16(
  3083. sqlite3 *db, /* Database handle */
  3084. const void *zSql, /* SQL statement, UTF-16 encoded */
  3085. int nByte, /* Maximum length of zSql in bytes. */
  3086. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3087. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3088. );
  3089. SQLITE_API int sqlite3_prepare16_v2(
  3090. sqlite3 *db, /* Database handle */
  3091. const void *zSql, /* SQL statement, UTF-16 encoded */
  3092. int nByte, /* Maximum length of zSql in bytes. */
  3093. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3094. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3095. );
  3096. /*
  3097. ** CAPI3REF: Retrieving Statement SQL
  3098. **
  3099. ** ^This interface can be used to retrieve a saved copy of the original
  3100. ** SQL text used to create a [prepared statement] if that statement was
  3101. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3102. */
  3103. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3104. /*
  3105. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3106. **
  3107. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3108. ** and only if the [prepared statement] X makes no direct changes to
  3109. ** the content of the database file.
  3110. **
  3111. ** Note that [application-defined SQL functions] or
  3112. ** [virtual tables] might change the database indirectly as a side effect.
  3113. ** ^(For example, if an application defines a function "eval()" that
  3114. ** calls [sqlite3_exec()], then the following SQL statement would
  3115. ** change the database file through side-effects:
  3116. **
  3117. ** <blockquote><pre>
  3118. ** SELECT eval('DELETE FROM t1') FROM t2;
  3119. ** </pre></blockquote>
  3120. **
  3121. ** But because the [SELECT] statement does not change the database file
  3122. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3123. **
  3124. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3125. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3126. ** since the statements themselves do not actually modify the database but
  3127. ** rather they control the timing of when other statements modify the
  3128. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3129. ** sqlite3_stmt_readonly() to return true since, while those statements
  3130. ** change the configuration of a database connection, they do not make
  3131. ** changes to the content of the database files on disk.
  3132. */
  3133. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3134. /*
  3135. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3136. **
  3137. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3138. ** [prepared statement] S has been stepped at least once using
  3139. ** [sqlite3_step(S)] but has not run to completion and/or has not
  3140. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3141. ** interface returns false if S is a NULL pointer. If S is not a
  3142. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3143. ** object, then the behavior is undefined and probably undesirable.
  3144. **
  3145. ** This interface can be used in combination [sqlite3_next_stmt()]
  3146. ** to locate all prepared statements associated with a database
  3147. ** connection that are in need of being reset. This can be used,
  3148. ** for example, in diagnostic routines to search for prepared
  3149. ** statements that are holding a transaction open.
  3150. */
  3151. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  3152. /*
  3153. ** CAPI3REF: Dynamically Typed Value Object
  3154. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3155. **
  3156. ** SQLite uses the sqlite3_value object to represent all values
  3157. ** that can be stored in a database table. SQLite uses dynamic typing
  3158. ** for the values it stores. ^Values stored in sqlite3_value objects
  3159. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3160. **
  3161. ** An sqlite3_value object may be either "protected" or "unprotected".
  3162. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3163. ** will accept either a protected or an unprotected sqlite3_value.
  3164. ** Every interface that accepts sqlite3_value arguments specifies
  3165. ** whether or not it requires a protected sqlite3_value.
  3166. **
  3167. ** The terms "protected" and "unprotected" refer to whether or not
  3168. ** a mutex is held. An internal mutex is held for a protected
  3169. ** sqlite3_value object but no mutex is held for an unprotected
  3170. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3171. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3172. ** or if SQLite is run in one of reduced mutex modes
  3173. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3174. ** then there is no distinction between protected and unprotected
  3175. ** sqlite3_value objects and they can be used interchangeably. However,
  3176. ** for maximum code portability it is recommended that applications
  3177. ** still make the distinction between protected and unprotected
  3178. ** sqlite3_value objects even when not strictly required.
  3179. **
  3180. ** ^The sqlite3_value objects that are passed as parameters into the
  3181. ** implementation of [application-defined SQL functions] are protected.
  3182. ** ^The sqlite3_value object returned by
  3183. ** [sqlite3_column_value()] is unprotected.
  3184. ** Unprotected sqlite3_value objects may only be used with
  3185. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3186. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3187. ** interfaces require protected sqlite3_value objects.
  3188. */
  3189. typedef struct Mem sqlite3_value;
  3190. /*
  3191. ** CAPI3REF: SQL Function Context Object
  3192. **
  3193. ** The context in which an SQL function executes is stored in an
  3194. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3195. ** is always first parameter to [application-defined SQL functions].
  3196. ** The application-defined SQL function implementation will pass this
  3197. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3198. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3199. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3200. ** and/or [sqlite3_set_auxdata()].
  3201. */
  3202. typedef struct sqlite3_context sqlite3_context;
  3203. /*
  3204. ** CAPI3REF: Binding Values To Prepared Statements
  3205. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3206. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3207. **
  3208. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3209. ** literals may be replaced by a [parameter] that matches one of following
  3210. ** templates:
  3211. **
  3212. ** <ul>
  3213. ** <li> ?
  3214. ** <li> ?NNN
  3215. ** <li> :VVV
  3216. ** <li> @VVV
  3217. ** <li> $VVV
  3218. ** </ul>
  3219. **
  3220. ** In the templates above, NNN represents an integer literal,
  3221. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3222. ** parameters (also called "host parameter names" or "SQL parameters")
  3223. ** can be set using the sqlite3_bind_*() routines defined here.
  3224. **
  3225. ** ^The first argument to the sqlite3_bind_*() routines is always
  3226. ** a pointer to the [sqlite3_stmt] object returned from
  3227. ** [sqlite3_prepare_v2()] or its variants.
  3228. **
  3229. ** ^The second argument is the index of the SQL parameter to be set.
  3230. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3231. ** SQL parameter is used more than once, second and subsequent
  3232. ** occurrences have the same index as the first occurrence.
  3233. ** ^The index for named parameters can be looked up using the
  3234. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3235. ** for "?NNN" parameters is the value of NNN.
  3236. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3237. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3238. **
  3239. ** ^The third argument is the value to bind to the parameter.
  3240. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3241. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3242. ** is ignored and the end result is the same as sqlite3_bind_null().
  3243. **
  3244. ** ^(In those routines that have a fourth argument, its value is the
  3245. ** number of bytes in the parameter. To be clear: the value is the
  3246. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3247. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3248. ** is negative, then the length of the string is
  3249. ** the number of bytes up to the first zero terminator.
  3250. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3251. ** the behavior is undefined.
  3252. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3253. ** or sqlite3_bind_text16() then that parameter must be the byte offset
  3254. ** where the NUL terminator would occur assuming the string were NUL
  3255. ** terminated. If any NUL characters occur at byte offsets less than
  3256. ** the value of the fourth parameter then the resulting string value will
  3257. ** contain embedded NULs. The result of expressions involving strings
  3258. ** with embedded NULs is undefined.
  3259. **
  3260. ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  3261. ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  3262. ** string after SQLite has finished with it. ^The destructor is called
  3263. ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
  3264. ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
  3265. ** ^If the fifth argument is
  3266. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3267. ** information is in static, unmanaged space and does not need to be freed.
  3268. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3269. ** SQLite makes its own private copy of the data immediately, before
  3270. ** the sqlite3_bind_*() routine returns.
  3271. **
  3272. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3273. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3274. ** (just an integer to hold its size) while it is being processed.
  3275. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3276. ** content is later written using
  3277. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3278. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3279. **
  3280. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3281. ** for the [prepared statement] or with a prepared statement for which
  3282. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3283. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3284. ** routine is passed a [prepared statement] that has been finalized, the
  3285. ** result is undefined and probably harmful.
  3286. **
  3287. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3288. ** ^Unbound parameters are interpreted as NULL.
  3289. **
  3290. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3291. ** [error code] if anything goes wrong.
  3292. ** ^[SQLITE_RANGE] is returned if the parameter
  3293. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3294. **
  3295. ** See also: [sqlite3_bind_parameter_count()],
  3296. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3297. */
  3298. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3299. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  3300. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  3301. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3302. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  3303. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  3304. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3305. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3306. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3307. /*
  3308. ** CAPI3REF: Number Of SQL Parameters
  3309. **
  3310. ** ^This routine can be used to find the number of [SQL parameters]
  3311. ** in a [prepared statement]. SQL parameters are tokens of the
  3312. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3313. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3314. ** to the parameters at a later time.
  3315. **
  3316. ** ^(This routine actually returns the index of the largest (rightmost)
  3317. ** parameter. For all forms except ?NNN, this will correspond to the
  3318. ** number of unique parameters. If parameters of the ?NNN form are used,
  3319. ** there may be gaps in the list.)^
  3320. **
  3321. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3322. ** [sqlite3_bind_parameter_name()], and
  3323. ** [sqlite3_bind_parameter_index()].
  3324. */
  3325. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  3326. /*
  3327. ** CAPI3REF: Name Of A Host Parameter
  3328. **
  3329. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3330. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3331. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3332. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3333. ** respectively.
  3334. ** In other words, the initial ":" or "$" or "@" or "?"
  3335. ** is included as part of the name.)^
  3336. ** ^Parameters of the form "?" without a following integer have no name
  3337. ** and are referred to as "nameless" or "anonymous parameters".
  3338. **
  3339. ** ^The first host parameter has an index of 1, not 0.
  3340. **
  3341. ** ^If the value N is out of range or if the N-th parameter is
  3342. ** nameless, then NULL is returned. ^The returned string is
  3343. ** always in UTF-8 encoding even if the named parameter was
  3344. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3345. ** [sqlite3_prepare16_v2()].
  3346. **
  3347. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3348. ** [sqlite3_bind_parameter_count()], and
  3349. ** [sqlite3_bind_parameter_index()].
  3350. */
  3351. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3352. /*
  3353. ** CAPI3REF: Index Of A Parameter With A Given Name
  3354. **
  3355. ** ^Return the index of an SQL parameter given its name. ^The
  3356. ** index value returned is suitable for use as the second
  3357. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3358. ** is returned if no matching parameter is found. ^The parameter
  3359. ** name must be given in UTF-8 even if the original statement
  3360. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3361. **
  3362. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3363. ** [sqlite3_bind_parameter_count()], and
  3364. ** [sqlite3_bind_parameter_index()].
  3365. */
  3366. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3367. /*
  3368. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3369. **
  3370. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3371. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3372. ** ^Use this routine to reset all host parameters to NULL.
  3373. */
  3374. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  3375. /*
  3376. ** CAPI3REF: Number Of Columns In A Result Set
  3377. **
  3378. ** ^Return the number of columns in the result set returned by the
  3379. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3380. ** statement that does not return data (for example an [UPDATE]).
  3381. **
  3382. ** See also: [sqlite3_data_count()]
  3383. */
  3384. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  3385. /*
  3386. ** CAPI3REF: Column Names In A Result Set
  3387. **
  3388. ** ^These routines return the name assigned to a particular column
  3389. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3390. ** interface returns a pointer to a zero-terminated UTF-8 string
  3391. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3392. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3393. ** that implements the [SELECT] statement. ^The second parameter is the
  3394. ** column number. ^The leftmost column is number 0.
  3395. **
  3396. ** ^The returned string pointer is valid until either the [prepared statement]
  3397. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3398. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3399. ** or until the next call to
  3400. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3401. **
  3402. ** ^If sqlite3_malloc() fails during the processing of either routine
  3403. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3404. ** NULL pointer is returned.
  3405. **
  3406. ** ^The name of a result column is the value of the "AS" clause for
  3407. ** that column, if there is an AS clause. If there is no AS clause
  3408. ** then the name of the column is unspecified and may change from
  3409. ** one release of SQLite to the next.
  3410. */
  3411. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3412. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3413. /*
  3414. ** CAPI3REF: Source Of Data In A Query Result
  3415. **
  3416. ** ^These routines provide a means to determine the database, table, and
  3417. ** table column that is the origin of a particular result column in
  3418. ** [SELECT] statement.
  3419. ** ^The name of the database or table or column can be returned as
  3420. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3421. ** the database name, the _table_ routines return the table name, and
  3422. ** the origin_ routines return the column name.
  3423. ** ^The returned string is valid until the [prepared statement] is destroyed
  3424. ** using [sqlite3_finalize()] or until the statement is automatically
  3425. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3426. ** or until the same information is requested
  3427. ** again in a different encoding.
  3428. **
  3429. ** ^The names returned are the original un-aliased names of the
  3430. ** database, table, and column.
  3431. **
  3432. ** ^The first argument to these interfaces is a [prepared statement].
  3433. ** ^These functions return information about the Nth result column returned by
  3434. ** the statement, where N is the second function argument.
  3435. ** ^The left-most column is column 0 for these routines.
  3436. **
  3437. ** ^If the Nth column returned by the statement is an expression or
  3438. ** subquery and is not a column value, then all of these functions return
  3439. ** NULL. ^These routine might also return NULL if a memory allocation error
  3440. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3441. ** or column that query result column was extracted from.
  3442. **
  3443. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3444. ** UTF-16 encoded strings and the other functions return UTF-8.
  3445. **
  3446. ** ^These APIs are only available if the library was compiled with the
  3447. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3448. **
  3449. ** If two or more threads call one or more of these routines against the same
  3450. ** prepared statement and column at the same time then the results are
  3451. ** undefined.
  3452. **
  3453. ** If two or more threads call one or more
  3454. ** [sqlite3_column_database_name | column metadata interfaces]
  3455. ** for the same [prepared statement] and result column
  3456. ** at the same time then the results are undefined.
  3457. */
  3458. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3459. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3460. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3461. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3462. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3463. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3464. /*
  3465. ** CAPI3REF: Declared Datatype Of A Query Result
  3466. **
  3467. ** ^(The first parameter is a [prepared statement].
  3468. ** If this statement is a [SELECT] statement and the Nth column of the
  3469. ** returned result set of that [SELECT] is a table column (not an
  3470. ** expression or subquery) then the declared type of the table
  3471. ** column is returned.)^ ^If the Nth column of the result set is an
  3472. ** expression or subquery, then a NULL pointer is returned.
  3473. ** ^The returned string is always UTF-8 encoded.
  3474. **
  3475. ** ^(For example, given the database schema:
  3476. **
  3477. ** CREATE TABLE t1(c1 VARIANT);
  3478. **
  3479. ** and the following statement to be compiled:
  3480. **
  3481. ** SELECT c1 + 1, c1 FROM t1;
  3482. **
  3483. ** this routine would return the string "VARIANT" for the second result
  3484. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3485. **
  3486. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3487. ** is declared to contain a particular type does not mean that the
  3488. ** data stored in that column is of the declared type. SQLite is
  3489. ** strongly typed, but the typing is dynamic not static. ^Type
  3490. ** is associated with individual values, not with the containers
  3491. ** used to hold those values.
  3492. */
  3493. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3494. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3495. /*
  3496. ** CAPI3REF: Evaluate An SQL Statement
  3497. **
  3498. ** After a [prepared statement] has been prepared using either
  3499. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3500. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3501. ** must be called one or more times to evaluate the statement.
  3502. **
  3503. ** The details of the behavior of the sqlite3_step() interface depend
  3504. ** on whether the statement was prepared using the newer "v2" interface
  3505. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3506. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3507. ** new "v2" interface is recommended for new applications but the legacy
  3508. ** interface will continue to be supported.
  3509. **
  3510. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3511. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3512. ** ^With the "v2" interface, any of the other [result codes] or
  3513. ** [extended result codes] might be returned as well.
  3514. **
  3515. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3516. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3517. ** or occurs outside of an explicit transaction, then you can retry the
  3518. ** statement. If the statement is not a [COMMIT] and occurs within an
  3519. ** explicit transaction then you should rollback the transaction before
  3520. ** continuing.
  3521. **
  3522. ** ^[SQLITE_DONE] means that the statement has finished executing
  3523. ** successfully. sqlite3_step() should not be called again on this virtual
  3524. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3525. ** machine back to its initial state.
  3526. **
  3527. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3528. ** is returned each time a new row of data is ready for processing by the
  3529. ** caller. The values may be accessed using the [column access functions].
  3530. ** sqlite3_step() is called again to retrieve the next row of data.
  3531. **
  3532. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3533. ** violation) has occurred. sqlite3_step() should not be called again on
  3534. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3535. ** ^With the legacy interface, a more specific error code (for example,
  3536. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3537. ** can be obtained by calling [sqlite3_reset()] on the
  3538. ** [prepared statement]. ^In the "v2" interface,
  3539. ** the more specific error code is returned directly by sqlite3_step().
  3540. **
  3541. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3542. ** Perhaps it was called on a [prepared statement] that has
  3543. ** already been [sqlite3_finalize | finalized] or on one that had
  3544. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3545. ** be the case that the same database connection is being used by two or
  3546. ** more threads at the same moment in time.
  3547. **
  3548. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3549. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3550. ** other than [SQLITE_ROW] before any subsequent invocation of
  3551. ** sqlite3_step(). Failure to reset the prepared statement using
  3552. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3553. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3554. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3555. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3556. ** break because any application that ever receives an SQLITE_MISUSE error
  3557. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3558. ** can be used to restore the legacy behavior.
  3559. **
  3560. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3561. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3562. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3563. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3564. ** specific [error codes] that better describes the error.
  3565. ** We admit that this is a goofy design. The problem has been fixed
  3566. ** with the "v2" interface. If you prepare all of your SQL statements
  3567. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3568. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3569. ** then the more specific [error codes] are returned directly
  3570. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3571. */
  3572. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  3573. /*
  3574. ** CAPI3REF: Number of columns in a result set
  3575. **
  3576. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  3577. ** current row of the result set of [prepared statement] P.
  3578. ** ^If prepared statement P does not have results ready to return
  3579. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  3580. ** interfaces) then sqlite3_data_count(P) returns 0.
  3581. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  3582. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  3583. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  3584. ** will return non-zero if previous call to [sqlite3_step](P) returned
  3585. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  3586. ** where it always returns zero since each step of that multi-step
  3587. ** pragma returns 0 columns of data.
  3588. **
  3589. ** See also: [sqlite3_column_count()]
  3590. */
  3591. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  3592. /*
  3593. ** CAPI3REF: Fundamental Datatypes
  3594. ** KEYWORDS: SQLITE_TEXT
  3595. **
  3596. ** ^(Every value in SQLite has one of five fundamental datatypes:
  3597. **
  3598. ** <ul>
  3599. ** <li> 64-bit signed integer
  3600. ** <li> 64-bit IEEE floating point number
  3601. ** <li> string
  3602. ** <li> BLOB
  3603. ** <li> NULL
  3604. ** </ul>)^
  3605. **
  3606. ** These constants are codes for each of those types.
  3607. **
  3608. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  3609. ** for a completely different meaning. Software that links against both
  3610. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  3611. ** SQLITE_TEXT.
  3612. */
  3613. #define SQLITE_INTEGER 1
  3614. #define SQLITE_FLOAT 2
  3615. #define SQLITE_BLOB 4
  3616. #define SQLITE_NULL 5
  3617. #ifdef SQLITE_TEXT
  3618. # undef SQLITE_TEXT
  3619. #else
  3620. # define SQLITE_TEXT 3
  3621. #endif
  3622. #define SQLITE3_TEXT 3
  3623. /*
  3624. ** CAPI3REF: Result Values From A Query
  3625. ** KEYWORDS: {column access functions}
  3626. **
  3627. ** These routines form the "result set" interface.
  3628. **
  3629. ** ^These routines return information about a single column of the current
  3630. ** result row of a query. ^In every case the first argument is a pointer
  3631. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  3632. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  3633. ** and the second argument is the index of the column for which information
  3634. ** should be returned. ^The leftmost column of the result set has the index 0.
  3635. ** ^The number of columns in the result can be determined using
  3636. ** [sqlite3_column_count()].
  3637. **
  3638. ** If the SQL statement does not currently point to a valid row, or if the
  3639. ** column index is out of range, the result is undefined.
  3640. ** These routines may only be called when the most recent call to
  3641. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  3642. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  3643. ** If any of these routines are called after [sqlite3_reset()] or
  3644. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  3645. ** something other than [SQLITE_ROW], the results are undefined.
  3646. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  3647. ** are called from a different thread while any of these routines
  3648. ** are pending, then the results are undefined.
  3649. **
  3650. ** ^The sqlite3_column_type() routine returns the
  3651. ** [SQLITE_INTEGER | datatype code] for the initial data type
  3652. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  3653. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  3654. ** returned by sqlite3_column_type() is only meaningful if no type
  3655. ** conversions have occurred as described below. After a type conversion,
  3656. ** the value returned by sqlite3_column_type() is undefined. Future
  3657. ** versions of SQLite may change the behavior of sqlite3_column_type()
  3658. ** following a type conversion.
  3659. **
  3660. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  3661. ** routine returns the number of bytes in that BLOB or string.
  3662. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  3663. ** the string to UTF-8 and then returns the number of bytes.
  3664. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  3665. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  3666. ** the number of bytes in that string.
  3667. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  3668. **
  3669. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  3670. ** routine returns the number of bytes in that BLOB or string.
  3671. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  3672. ** the string to UTF-16 and then returns the number of bytes.
  3673. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  3674. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  3675. ** the number of bytes in that string.
  3676. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  3677. **
  3678. ** ^The values returned by [sqlite3_column_bytes()] and
  3679. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  3680. ** of the string. ^For clarity: the values returned by
  3681. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  3682. ** bytes in the string, not the number of characters.
  3683. **
  3684. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  3685. ** even empty strings, are always zero-terminated. ^The return
  3686. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  3687. **
  3688. ** ^The object returned by [sqlite3_column_value()] is an
  3689. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  3690. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  3691. ** If the [unprotected sqlite3_value] object returned by
  3692. ** [sqlite3_column_value()] is used in any other way, including calls
  3693. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  3694. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  3695. **
  3696. ** These routines attempt to convert the value where appropriate. ^For
  3697. ** example, if the internal representation is FLOAT and a text result
  3698. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  3699. ** conversion automatically. ^(The following table details the conversions
  3700. ** that are applied:
  3701. **
  3702. ** <blockquote>
  3703. ** <table border="1">
  3704. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  3705. **
  3706. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  3707. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  3708. ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
  3709. ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
  3710. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  3711. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  3712. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  3713. ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
  3714. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  3715. ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
  3716. ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
  3717. ** <tr><td> TEXT <td> FLOAT <td> Use atof()
  3718. ** <tr><td> TEXT <td> BLOB <td> No change
  3719. ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
  3720. ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
  3721. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  3722. ** </table>
  3723. ** </blockquote>)^
  3724. **
  3725. ** The table above makes reference to standard C library functions atoi()
  3726. ** and atof(). SQLite does not really use these functions. It has its
  3727. ** own equivalent internal routines. The atoi() and atof() names are
  3728. ** used in the table for brevity and because they are familiar to most
  3729. ** C programmers.
  3730. **
  3731. ** Note that when type conversions occur, pointers returned by prior
  3732. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  3733. ** sqlite3_column_text16() may be invalidated.
  3734. ** Type conversions and pointer invalidations might occur
  3735. ** in the following cases:
  3736. **
  3737. ** <ul>
  3738. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  3739. ** sqlite3_column_text16() is called. A zero-terminator might
  3740. ** need to be added to the string.</li>
  3741. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  3742. ** sqlite3_column_text16() is called. The content must be converted
  3743. ** to UTF-16.</li>
  3744. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  3745. ** sqlite3_column_text() is called. The content must be converted
  3746. ** to UTF-8.</li>
  3747. ** </ul>
  3748. **
  3749. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  3750. ** not invalidate a prior pointer, though of course the content of the buffer
  3751. ** that the prior pointer references will have been modified. Other kinds
  3752. ** of conversion are done in place when it is possible, but sometimes they
  3753. ** are not possible and in those cases prior pointers are invalidated.
  3754. **
  3755. ** The safest and easiest to remember policy is to invoke these routines
  3756. ** in one of the following ways:
  3757. **
  3758. ** <ul>
  3759. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  3760. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  3761. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  3762. ** </ul>
  3763. **
  3764. ** In other words, you should call sqlite3_column_text(),
  3765. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  3766. ** into the desired format, then invoke sqlite3_column_bytes() or
  3767. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  3768. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  3769. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  3770. ** with calls to sqlite3_column_bytes().
  3771. **
  3772. ** ^The pointers returned are valid until a type conversion occurs as
  3773. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  3774. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  3775. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  3776. ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  3777. ** [sqlite3_free()].
  3778. **
  3779. ** ^(If a memory allocation error occurs during the evaluation of any
  3780. ** of these routines, a default value is returned. The default value
  3781. ** is either the integer 0, the floating point number 0.0, or a NULL
  3782. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  3783. ** [SQLITE_NOMEM].)^
  3784. */
  3785. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  3786. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  3787. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  3788. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  3789. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  3790. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  3791. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  3792. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  3793. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  3794. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  3795. /*
  3796. ** CAPI3REF: Destroy A Prepared Statement Object
  3797. **
  3798. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  3799. ** ^If the most recent evaluation of the statement encountered no errors
  3800. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  3801. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  3802. ** sqlite3_finalize(S) returns the appropriate [error code] or
  3803. ** [extended error code].
  3804. **
  3805. ** ^The sqlite3_finalize(S) routine can be called at any point during
  3806. ** the life cycle of [prepared statement] S:
  3807. ** before statement S is ever evaluated, after
  3808. ** one or more calls to [sqlite3_reset()], or after any call
  3809. ** to [sqlite3_step()] regardless of whether or not the statement has
  3810. ** completed execution.
  3811. **
  3812. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  3813. **
  3814. ** The application must finalize every [prepared statement] in order to avoid
  3815. ** resource leaks. It is a grievous error for the application to try to use
  3816. ** a prepared statement after it has been finalized. Any use of a prepared
  3817. ** statement after it has been finalized can result in undefined and
  3818. ** undesirable behavior such as segfaults and heap corruption.
  3819. */
  3820. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  3821. /*
  3822. ** CAPI3REF: Reset A Prepared Statement Object
  3823. **
  3824. ** The sqlite3_reset() function is called to reset a [prepared statement]
  3825. ** object back to its initial state, ready to be re-executed.
  3826. ** ^Any SQL statement variables that had values bound to them using
  3827. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  3828. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  3829. **
  3830. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  3831. ** back to the beginning of its program.
  3832. **
  3833. ** ^If the most recent call to [sqlite3_step(S)] for the
  3834. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  3835. ** or if [sqlite3_step(S)] has never before been called on S,
  3836. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  3837. **
  3838. ** ^If the most recent call to [sqlite3_step(S)] for the
  3839. ** [prepared statement] S indicated an error, then
  3840. ** [sqlite3_reset(S)] returns an appropriate [error code].
  3841. **
  3842. ** ^The [sqlite3_reset(S)] interface does not change the values
  3843. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  3844. */
  3845. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  3846. /*
  3847. ** CAPI3REF: Create Or Redefine SQL Functions
  3848. ** KEYWORDS: {function creation routines}
  3849. ** KEYWORDS: {application-defined SQL function}
  3850. ** KEYWORDS: {application-defined SQL functions}
  3851. **
  3852. ** ^These functions (collectively known as "function creation routines")
  3853. ** are used to add SQL functions or aggregates or to redefine the behavior
  3854. ** of existing SQL functions or aggregates. The only differences between
  3855. ** these routines are the text encoding expected for
  3856. ** the second parameter (the name of the function being created)
  3857. ** and the presence or absence of a destructor callback for
  3858. ** the application data pointer.
  3859. **
  3860. ** ^The first parameter is the [database connection] to which the SQL
  3861. ** function is to be added. ^If an application uses more than one database
  3862. ** connection then application-defined SQL functions must be added
  3863. ** to each database connection separately.
  3864. **
  3865. ** ^The second parameter is the name of the SQL function to be created or
  3866. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  3867. ** representation, exclusive of the zero-terminator. ^Note that the name
  3868. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  3869. ** ^Any attempt to create a function with a longer name
  3870. ** will result in [SQLITE_MISUSE] being returned.
  3871. **
  3872. ** ^The third parameter (nArg)
  3873. ** is the number of arguments that the SQL function or
  3874. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  3875. ** aggregate may take any number of arguments between 0 and the limit
  3876. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  3877. ** parameter is less than -1 or greater than 127 then the behavior is
  3878. ** undefined.
  3879. **
  3880. ** ^The fourth parameter, eTextRep, specifies what
  3881. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  3882. ** its parameters. Every SQL function implementation must be able to work
  3883. ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
  3884. ** more efficient with one encoding than another. ^An application may
  3885. ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
  3886. ** times with the same function but with different values of eTextRep.
  3887. ** ^When multiple implementations of the same function are available, SQLite
  3888. ** will pick the one that involves the least amount of data conversion.
  3889. ** If there is only a single implementation which does not care what text
  3890. ** encoding is used, then the fourth argument should be [SQLITE_ANY].
  3891. **
  3892. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  3893. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  3894. **
  3895. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  3896. ** pointers to C-language functions that implement the SQL function or
  3897. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  3898. ** callback only; NULL pointers must be passed as the xStep and xFinal
  3899. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  3900. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  3901. ** SQL function or aggregate, pass NULL pointers for all three function
  3902. ** callbacks.
  3903. **
  3904. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  3905. ** then it is destructor for the application data pointer.
  3906. ** The destructor is invoked when the function is deleted, either by being
  3907. ** overloaded or when the database connection closes.)^
  3908. ** ^The destructor is also invoked if the call to
  3909. ** sqlite3_create_function_v2() fails.
  3910. ** ^When the destructor callback of the tenth parameter is invoked, it
  3911. ** is passed a single argument which is a copy of the application data
  3912. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  3913. **
  3914. ** ^It is permitted to register multiple implementations of the same
  3915. ** functions with the same name but with either differing numbers of
  3916. ** arguments or differing preferred text encodings. ^SQLite will use
  3917. ** the implementation that most closely matches the way in which the
  3918. ** SQL function is used. ^A function implementation with a non-negative
  3919. ** nArg parameter is a better match than a function implementation with
  3920. ** a negative nArg. ^A function where the preferred text encoding
  3921. ** matches the database encoding is a better
  3922. ** match than a function where the encoding is different.
  3923. ** ^A function where the encoding difference is between UTF16le and UTF16be
  3924. ** is a closer match than a function where the encoding difference is
  3925. ** between UTF8 and UTF16.
  3926. **
  3927. ** ^Built-in functions may be overloaded by new application-defined functions.
  3928. **
  3929. ** ^An application-defined function is permitted to call other
  3930. ** SQLite interfaces. However, such calls must not
  3931. ** close the database connection nor finalize or reset the prepared
  3932. ** statement in which the function is running.
  3933. */
  3934. SQLITE_API int sqlite3_create_function(
  3935. sqlite3 *db,
  3936. const char *zFunctionName,
  3937. int nArg,
  3938. int eTextRep,
  3939. void *pApp,
  3940. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3941. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3942. void (*xFinal)(sqlite3_context*)
  3943. );
  3944. SQLITE_API int sqlite3_create_function16(
  3945. sqlite3 *db,
  3946. const void *zFunctionName,
  3947. int nArg,
  3948. int eTextRep,
  3949. void *pApp,
  3950. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3951. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3952. void (*xFinal)(sqlite3_context*)
  3953. );
  3954. SQLITE_API int sqlite3_create_function_v2(
  3955. sqlite3 *db,
  3956. const char *zFunctionName,
  3957. int nArg,
  3958. int eTextRep,
  3959. void *pApp,
  3960. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3961. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3962. void (*xFinal)(sqlite3_context*),
  3963. void(*xDestroy)(void*)
  3964. );
  3965. /*
  3966. ** CAPI3REF: Text Encodings
  3967. **
  3968. ** These constant define integer codes that represent the various
  3969. ** text encodings supported by SQLite.
  3970. */
  3971. #define SQLITE_UTF8 1
  3972. #define SQLITE_UTF16LE 2
  3973. #define SQLITE_UTF16BE 3
  3974. #define SQLITE_UTF16 4 /* Use native byte order */
  3975. #define SQLITE_ANY 5 /* sqlite3_create_function only */
  3976. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  3977. /*
  3978. ** CAPI3REF: Deprecated Functions
  3979. ** DEPRECATED
  3980. **
  3981. ** These functions are [deprecated]. In order to maintain
  3982. ** backwards compatibility with older code, these functions continue
  3983. ** to be supported. However, new applications should avoid
  3984. ** the use of these functions. To help encourage people to avoid
  3985. ** using these functions, we are not going to tell you what they do.
  3986. */
  3987. #ifndef SQLITE_OMIT_DEPRECATED
  3988. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  3989. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  3990. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  3991. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  3992. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  3993. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  3994. void*,sqlite3_int64);
  3995. #endif
  3996. /*
  3997. ** CAPI3REF: Obtaining SQL Function Parameter Values
  3998. **
  3999. ** The C-language implementation of SQL functions and aggregates uses
  4000. ** this set of interface routines to access the parameter values on
  4001. ** the function or aggregate.
  4002. **
  4003. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4004. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4005. ** define callbacks that implement the SQL functions and aggregates.
  4006. ** The 3rd parameter to these callbacks is an array of pointers to
  4007. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4008. ** each parameter to the SQL function. These routines are used to
  4009. ** extract values from the [sqlite3_value] objects.
  4010. **
  4011. ** These routines work only with [protected sqlite3_value] objects.
  4012. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4013. ** object results in undefined behavior.
  4014. **
  4015. ** ^These routines work just like the corresponding [column access functions]
  4016. ** except that these routines take a single [protected sqlite3_value] object
  4017. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4018. **
  4019. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4020. ** in the native byte-order of the host machine. ^The
  4021. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4022. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4023. **
  4024. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4025. ** numeric affinity to the value. This means that an attempt is
  4026. ** made to convert the value to an integer or floating point. If
  4027. ** such a conversion is possible without loss of information (in other
  4028. ** words, if the value is a string that looks like a number)
  4029. ** then the conversion is performed. Otherwise no conversion occurs.
  4030. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4031. **
  4032. ** Please pay particular attention to the fact that the pointer returned
  4033. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4034. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4035. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4036. ** or [sqlite3_value_text16()].
  4037. **
  4038. ** These routines must be called from the same thread as
  4039. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4040. */
  4041. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4042. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4043. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4044. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4045. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4046. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4047. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4048. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4049. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4050. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4051. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4052. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4053. /*
  4054. ** CAPI3REF: Obtain Aggregate Function Context
  4055. **
  4056. ** Implementations of aggregate SQL functions use this
  4057. ** routine to allocate memory for storing their state.
  4058. **
  4059. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4060. ** for a particular aggregate function, SQLite
  4061. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4062. ** to the new memory. ^On second and subsequent calls to
  4063. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4064. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4065. ** called once for each invocation of the xStep callback and then one
  4066. ** last time when the xFinal callback is invoked. ^(When no rows match
  4067. ** an aggregate query, the xStep() callback of the aggregate function
  4068. ** implementation is never called and xFinal() is called exactly once.
  4069. ** In those cases, sqlite3_aggregate_context() might be called for the
  4070. ** first time from within xFinal().)^
  4071. **
  4072. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4073. ** when first called if N is less than or equal to zero or if a memory
  4074. ** allocate error occurs.
  4075. **
  4076. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4077. ** determined by the N parameter on first successful call. Changing the
  4078. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4079. ** the same aggregate function instance will not resize the memory
  4080. ** allocation.)^ Within the xFinal callback, it is customary to set
  4081. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4082. ** pointless memory allocations occur.
  4083. **
  4084. ** ^SQLite automatically frees the memory allocated by
  4085. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4086. **
  4087. ** The first parameter must be a copy of the
  4088. ** [sqlite3_context | SQL function context] that is the first parameter
  4089. ** to the xStep or xFinal callback routine that implements the aggregate
  4090. ** function.
  4091. **
  4092. ** This routine must be called from the same thread in which
  4093. ** the aggregate SQL function is running.
  4094. */
  4095. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4096. /*
  4097. ** CAPI3REF: User Data For Functions
  4098. **
  4099. ** ^The sqlite3_user_data() interface returns a copy of
  4100. ** the pointer that was the pUserData parameter (the 5th parameter)
  4101. ** of the [sqlite3_create_function()]
  4102. ** and [sqlite3_create_function16()] routines that originally
  4103. ** registered the application defined function.
  4104. **
  4105. ** This routine must be called from the same thread in which
  4106. ** the application-defined function is running.
  4107. */
  4108. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4109. /*
  4110. ** CAPI3REF: Database Connection For Functions
  4111. **
  4112. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4113. ** the pointer to the [database connection] (the 1st parameter)
  4114. ** of the [sqlite3_create_function()]
  4115. ** and [sqlite3_create_function16()] routines that originally
  4116. ** registered the application defined function.
  4117. */
  4118. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4119. /*
  4120. ** CAPI3REF: Function Auxiliary Data
  4121. **
  4122. ** These functions may be used by (non-aggregate) SQL functions to
  4123. ** associate metadata with argument values. If the same value is passed to
  4124. ** multiple invocations of the same SQL function during query execution, under
  4125. ** some circumstances the associated metadata may be preserved. An example
  4126. ** of where this might be useful is in a regular-expression matching
  4127. ** function. The compiled version of the regular expression can be stored as
  4128. ** metadata associated with the pattern string.
  4129. ** Then as long as the pattern string remains the same,
  4130. ** the compiled regular expression can be reused on multiple
  4131. ** invocations of the same function.
  4132. **
  4133. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4134. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4135. ** value to the application-defined function. ^If there is no metadata
  4136. ** associated with the function argument, this sqlite3_get_auxdata() interface
  4137. ** returns a NULL pointer.
  4138. **
  4139. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4140. ** argument of the application-defined function. ^Subsequent
  4141. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4142. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4143. ** NULL if the metadata has been discarded.
  4144. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4145. ** SQLite will invoke the destructor function X with parameter P exactly
  4146. ** once, when the metadata is discarded.
  4147. ** SQLite is free to discard the metadata at any time, including: <ul>
  4148. ** <li> when the corresponding function parameter changes, or
  4149. ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4150. ** SQL statement, or
  4151. ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  4152. ** <li> during the original sqlite3_set_auxdata() call when a memory
  4153. ** allocation error occurs. </ul>)^
  4154. **
  4155. ** Note the last bullet in particular. The destructor X in
  4156. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4157. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4158. ** should be called near the end of the function implementation and the
  4159. ** function implementation should not make any use of P after
  4160. ** sqlite3_set_auxdata() has been called.
  4161. **
  4162. ** ^(In practice, metadata is preserved between function calls for
  4163. ** function parameters that are compile-time constants, including literal
  4164. ** values and [parameters] and expressions composed from the same.)^
  4165. **
  4166. ** These routines must be called from the same thread in which
  4167. ** the SQL function is running.
  4168. */
  4169. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4170. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4171. /*
  4172. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4173. **
  4174. ** These are special values for the destructor that is passed in as the
  4175. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4176. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4177. ** and will never change. It does not need to be destroyed. ^The
  4178. ** SQLITE_TRANSIENT value means that the content will likely change in
  4179. ** the near future and that SQLite should make its own private copy of
  4180. ** the content before returning.
  4181. **
  4182. ** The typedef is necessary to work around problems in certain
  4183. ** C++ compilers.
  4184. */
  4185. typedef void (*sqlite3_destructor_type)(void*);
  4186. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4187. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4188. /*
  4189. ** CAPI3REF: Setting The Result Of An SQL Function
  4190. **
  4191. ** These routines are used by the xFunc or xFinal callbacks that
  4192. ** implement SQL functions and aggregates. See
  4193. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4194. ** for additional information.
  4195. **
  4196. ** These functions work very much like the [parameter binding] family of
  4197. ** functions used to bind values to host parameters in prepared statements.
  4198. ** Refer to the [SQL parameter] documentation for additional information.
  4199. **
  4200. ** ^The sqlite3_result_blob() interface sets the result from
  4201. ** an application-defined function to be the BLOB whose content is pointed
  4202. ** to by the second parameter and which is N bytes long where N is the
  4203. ** third parameter.
  4204. **
  4205. ** ^The sqlite3_result_zeroblob() interfaces set the result of
  4206. ** the application-defined function to be a BLOB containing all zero
  4207. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4208. **
  4209. ** ^The sqlite3_result_double() interface sets the result from
  4210. ** an application-defined function to be a floating point value specified
  4211. ** by its 2nd argument.
  4212. **
  4213. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4214. ** cause the implemented SQL function to throw an exception.
  4215. ** ^SQLite uses the string pointed to by the
  4216. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4217. ** as the text of an error message. ^SQLite interprets the error
  4218. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4219. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4220. ** byte order. ^If the third parameter to sqlite3_result_error()
  4221. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4222. ** message all text up through the first zero character.
  4223. ** ^If the third parameter to sqlite3_result_error() or
  4224. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4225. ** bytes (not characters) from the 2nd parameter as the error message.
  4226. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4227. ** routines make a private copy of the error message text before
  4228. ** they return. Hence, the calling function can deallocate or
  4229. ** modify the text after they return without harm.
  4230. ** ^The sqlite3_result_error_code() function changes the error code
  4231. ** returned by SQLite as a result of an error in a function. ^By default,
  4232. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4233. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4234. **
  4235. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4236. ** error indicating that a string or BLOB is too long to represent.
  4237. **
  4238. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4239. ** error indicating that a memory allocation failed.
  4240. **
  4241. ** ^The sqlite3_result_int() interface sets the return value
  4242. ** of the application-defined function to be the 32-bit signed integer
  4243. ** value given in the 2nd argument.
  4244. ** ^The sqlite3_result_int64() interface sets the return value
  4245. ** of the application-defined function to be the 64-bit signed integer
  4246. ** value given in the 2nd argument.
  4247. **
  4248. ** ^The sqlite3_result_null() interface sets the return value
  4249. ** of the application-defined function to be NULL.
  4250. **
  4251. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4252. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4253. ** set the return value of the application-defined function to be
  4254. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4255. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4256. ** ^SQLite takes the text result from the application from
  4257. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4258. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4259. ** is negative, then SQLite takes result text from the 2nd parameter
  4260. ** through the first zero character.
  4261. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4262. ** is non-negative, then as many bytes (not characters) of the text
  4263. ** pointed to by the 2nd parameter are taken as the application-defined
  4264. ** function result. If the 3rd parameter is non-negative, then it
  4265. ** must be the byte offset into the string where the NUL terminator would
  4266. ** appear if the string where NUL terminated. If any NUL characters occur
  4267. ** in the string at a byte offset that is less than the value of the 3rd
  4268. ** parameter, then the resulting string will contain embedded NULs and the
  4269. ** result of expressions operating on strings with embedded NULs is undefined.
  4270. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4271. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4272. ** function as the destructor on the text or BLOB result when it has
  4273. ** finished using that result.
  4274. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4275. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4276. ** assumes that the text or BLOB result is in constant space and does not
  4277. ** copy the content of the parameter nor call a destructor on the content
  4278. ** when it has finished using that result.
  4279. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4280. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4281. ** then SQLite makes a copy of the result into space obtained from
  4282. ** from [sqlite3_malloc()] before it returns.
  4283. **
  4284. ** ^The sqlite3_result_value() interface sets the result of
  4285. ** the application-defined function to be a copy the
  4286. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4287. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4288. ** so that the [sqlite3_value] specified in the parameter may change or
  4289. ** be deallocated after sqlite3_result_value() returns without harm.
  4290. ** ^A [protected sqlite3_value] object may always be used where an
  4291. ** [unprotected sqlite3_value] object is required, so either
  4292. ** kind of [sqlite3_value] object can be used with this interface.
  4293. **
  4294. ** If these routines are called from within the different thread
  4295. ** than the one containing the application-defined function that received
  4296. ** the [sqlite3_context] pointer, the results are undefined.
  4297. */
  4298. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4299. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  4300. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  4301. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  4302. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  4303. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  4304. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  4305. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  4306. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4307. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  4308. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4309. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4310. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4311. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4312. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4313. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  4314. /*
  4315. ** CAPI3REF: Define New Collating Sequences
  4316. **
  4317. ** ^These functions add, remove, or modify a [collation] associated
  4318. ** with the [database connection] specified as the first argument.
  4319. **
  4320. ** ^The name of the collation is a UTF-8 string
  4321. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4322. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4323. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4324. ** considered to be the same name.
  4325. **
  4326. ** ^(The third argument (eTextRep) must be one of the constants:
  4327. ** <ul>
  4328. ** <li> [SQLITE_UTF8],
  4329. ** <li> [SQLITE_UTF16LE],
  4330. ** <li> [SQLITE_UTF16BE],
  4331. ** <li> [SQLITE_UTF16], or
  4332. ** <li> [SQLITE_UTF16_ALIGNED].
  4333. ** </ul>)^
  4334. ** ^The eTextRep argument determines the encoding of strings passed
  4335. ** to the collating function callback, xCallback.
  4336. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4337. ** force strings to be UTF16 with native byte order.
  4338. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4339. ** on an even byte address.
  4340. **
  4341. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4342. ** through as the first argument to the collating function callback.
  4343. **
  4344. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4345. ** ^Multiple collating functions can be registered using the same name but
  4346. ** with different eTextRep parameters and SQLite will use whichever
  4347. ** function requires the least amount of data transformation.
  4348. ** ^If the xCallback argument is NULL then the collating function is
  4349. ** deleted. ^When all collating functions having the same name are deleted,
  4350. ** that collation is no longer usable.
  4351. **
  4352. ** ^The collating function callback is invoked with a copy of the pArg
  4353. ** application data pointer and with two strings in the encoding specified
  4354. ** by the eTextRep argument. The collating function must return an
  4355. ** integer that is negative, zero, or positive
  4356. ** if the first string is less than, equal to, or greater than the second,
  4357. ** respectively. A collating function must always return the same answer
  4358. ** given the same inputs. If two or more collating functions are registered
  4359. ** to the same collation name (using different eTextRep values) then all
  4360. ** must give an equivalent answer when invoked with equivalent strings.
  4361. ** The collating function must obey the following properties for all
  4362. ** strings A, B, and C:
  4363. **
  4364. ** <ol>
  4365. ** <li> If A==B then B==A.
  4366. ** <li> If A==B and B==C then A==C.
  4367. ** <li> If A&lt;B THEN B&gt;A.
  4368. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4369. ** </ol>
  4370. **
  4371. ** If a collating function fails any of the above constraints and that
  4372. ** collating function is registered and used, then the behavior of SQLite
  4373. ** is undefined.
  4374. **
  4375. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4376. ** with the addition that the xDestroy callback is invoked on pArg when
  4377. ** the collating function is deleted.
  4378. ** ^Collating functions are deleted when they are overridden by later
  4379. ** calls to the collation creation functions or when the
  4380. ** [database connection] is closed using [sqlite3_close()].
  4381. **
  4382. ** ^The xDestroy callback is <u>not</u> called if the
  4383. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4384. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4385. ** check the return code and dispose of the application data pointer
  4386. ** themselves rather than expecting SQLite to deal with it for them.
  4387. ** This is different from every other SQLite interface. The inconsistency
  4388. ** is unfortunate but cannot be changed without breaking backwards
  4389. ** compatibility.
  4390. **
  4391. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4392. */
  4393. SQLITE_API int sqlite3_create_collation(
  4394. sqlite3*,
  4395. const char *zName,
  4396. int eTextRep,
  4397. void *pArg,
  4398. int(*xCompare)(void*,int,const void*,int,const void*)
  4399. );
  4400. SQLITE_API int sqlite3_create_collation_v2(
  4401. sqlite3*,
  4402. const char *zName,
  4403. int eTextRep,
  4404. void *pArg,
  4405. int(*xCompare)(void*,int,const void*,int,const void*),
  4406. void(*xDestroy)(void*)
  4407. );
  4408. SQLITE_API int sqlite3_create_collation16(
  4409. sqlite3*,
  4410. const void *zName,
  4411. int eTextRep,
  4412. void *pArg,
  4413. int(*xCompare)(void*,int,const void*,int,const void*)
  4414. );
  4415. /*
  4416. ** CAPI3REF: Collation Needed Callbacks
  4417. **
  4418. ** ^To avoid having to register all collation sequences before a database
  4419. ** can be used, a single callback function may be registered with the
  4420. ** [database connection] to be invoked whenever an undefined collation
  4421. ** sequence is required.
  4422. **
  4423. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4424. ** then it is passed the names of undefined collation sequences as strings
  4425. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4426. ** the names are passed as UTF-16 in machine native byte order.
  4427. ** ^A call to either function replaces the existing collation-needed callback.
  4428. **
  4429. ** ^(When the callback is invoked, the first argument passed is a copy
  4430. ** of the second argument to sqlite3_collation_needed() or
  4431. ** sqlite3_collation_needed16(). The second argument is the database
  4432. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4433. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4434. ** sequence function required. The fourth parameter is the name of the
  4435. ** required collation sequence.)^
  4436. **
  4437. ** The callback function should register the desired collation using
  4438. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4439. ** [sqlite3_create_collation_v2()].
  4440. */
  4441. SQLITE_API int sqlite3_collation_needed(
  4442. sqlite3*,
  4443. void*,
  4444. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4445. );
  4446. SQLITE_API int sqlite3_collation_needed16(
  4447. sqlite3*,
  4448. void*,
  4449. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4450. );
  4451. #ifdef SQLITE_HAS_CODEC
  4452. /*
  4453. ** Specify the key for an encrypted database. This routine should be
  4454. ** called right after sqlite3_open().
  4455. **
  4456. ** The code to implement this API is not available in the public release
  4457. ** of SQLite.
  4458. */
  4459. SQLITE_API int sqlite3_key(
  4460. sqlite3 *db, /* Database to be rekeyed */
  4461. const void *pKey, int nKey /* The key */
  4462. );
  4463. SQLITE_API int sqlite3_key_v2(
  4464. sqlite3 *db, /* Database to be rekeyed */
  4465. const char *zDbName, /* Name of the database */
  4466. const void *pKey, int nKey /* The key */
  4467. );
  4468. /*
  4469. ** Change the key on an open database. If the current database is not
  4470. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4471. ** database is decrypted.
  4472. **
  4473. ** The code to implement this API is not available in the public release
  4474. ** of SQLite.
  4475. */
  4476. SQLITE_API int sqlite3_rekey(
  4477. sqlite3 *db, /* Database to be rekeyed */
  4478. const void *pKey, int nKey /* The new key */
  4479. );
  4480. SQLITE_API int sqlite3_rekey_v2(
  4481. sqlite3 *db, /* Database to be rekeyed */
  4482. const char *zDbName, /* Name of the database */
  4483. const void *pKey, int nKey /* The new key */
  4484. );
  4485. /*
  4486. ** Specify the activation key for a SEE database. Unless
  4487. ** activated, none of the SEE routines will work.
  4488. */
  4489. SQLITE_API void sqlite3_activate_see(
  4490. const char *zPassPhrase /* Activation phrase */
  4491. );
  4492. #endif
  4493. #ifdef SQLITE_ENABLE_CEROD
  4494. /*
  4495. ** Specify the activation key for a CEROD database. Unless
  4496. ** activated, none of the CEROD routines will work.
  4497. */
  4498. SQLITE_API void sqlite3_activate_cerod(
  4499. const char *zPassPhrase /* Activation phrase */
  4500. );
  4501. #endif
  4502. /*
  4503. ** CAPI3REF: Suspend Execution For A Short Time
  4504. **
  4505. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4506. ** for at least a number of milliseconds specified in its parameter.
  4507. **
  4508. ** If the operating system does not support sleep requests with
  4509. ** millisecond time resolution, then the time will be rounded up to
  4510. ** the nearest second. The number of milliseconds of sleep actually
  4511. ** requested from the operating system is returned.
  4512. **
  4513. ** ^SQLite implements this interface by calling the xSleep()
  4514. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4515. ** of the default VFS is not implemented correctly, or not implemented at
  4516. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4517. ** in the previous paragraphs.
  4518. */
  4519. SQLITE_API int sqlite3_sleep(int);
  4520. /*
  4521. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4522. **
  4523. ** ^(If this global variable is made to point to a string which is
  4524. ** the name of a folder (a.k.a. directory), then all temporary files
  4525. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  4526. ** will be placed in that directory.)^ ^If this variable
  4527. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4528. ** temporary file directory.
  4529. **
  4530. ** It is not safe to read or modify this variable in more than one
  4531. ** thread at a time. It is not safe to read or modify this variable
  4532. ** if a [database connection] is being used at the same time in a separate
  4533. ** thread.
  4534. ** It is intended that this variable be set once
  4535. ** as part of process initialization and before any SQLite interface
  4536. ** routines have been called and that this variable remain unchanged
  4537. ** thereafter.
  4538. **
  4539. ** ^The [temp_store_directory pragma] may modify this variable and cause
  4540. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4541. ** the [temp_store_directory pragma] always assumes that any string
  4542. ** that this variable points to is held in memory obtained from
  4543. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4544. ** using [sqlite3_free].
  4545. ** Hence, if this variable is modified directly, either it should be
  4546. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4547. ** or else the use of the [temp_store_directory pragma] should be avoided.
  4548. **
  4549. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4550. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  4551. ** features that require the use of temporary files may fail. Here is an
  4552. ** example of how to do this using C++ with the Windows Runtime:
  4553. **
  4554. ** <blockquote><pre>
  4555. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  4556. ** &nbsp; TemporaryFolder->Path->Data();
  4557. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  4558. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  4559. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  4560. ** &nbsp; NULL, NULL);
  4561. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  4562. ** </pre></blockquote>
  4563. */
  4564. SQLITE_API char *sqlite3_temp_directory;
  4565. /*
  4566. ** CAPI3REF: Name Of The Folder Holding Database Files
  4567. **
  4568. ** ^(If this global variable is made to point to a string which is
  4569. ** the name of a folder (a.k.a. directory), then all database files
  4570. ** specified with a relative pathname and created or accessed by
  4571. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  4572. ** to be relative to that directory.)^ ^If this variable is a NULL
  4573. ** pointer, then SQLite assumes that all database files specified
  4574. ** with a relative pathname are relative to the current directory
  4575. ** for the process. Only the windows VFS makes use of this global
  4576. ** variable; it is ignored by the unix VFS.
  4577. **
  4578. ** Changing the value of this variable while a database connection is
  4579. ** open can result in a corrupt database.
  4580. **
  4581. ** It is not safe to read or modify this variable in more than one
  4582. ** thread at a time. It is not safe to read or modify this variable
  4583. ** if a [database connection] is being used at the same time in a separate
  4584. ** thread.
  4585. ** It is intended that this variable be set once
  4586. ** as part of process initialization and before any SQLite interface
  4587. ** routines have been called and that this variable remain unchanged
  4588. ** thereafter.
  4589. **
  4590. ** ^The [data_store_directory pragma] may modify this variable and cause
  4591. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4592. ** the [data_store_directory pragma] always assumes that any string
  4593. ** that this variable points to is held in memory obtained from
  4594. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4595. ** using [sqlite3_free].
  4596. ** Hence, if this variable is modified directly, either it should be
  4597. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4598. ** or else the use of the [data_store_directory pragma] should be avoided.
  4599. */
  4600. SQLITE_API char *sqlite3_data_directory;
  4601. /*
  4602. ** CAPI3REF: Test For Auto-Commit Mode
  4603. ** KEYWORDS: {autocommit mode}
  4604. **
  4605. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  4606. ** zero if the given database connection is or is not in autocommit mode,
  4607. ** respectively. ^Autocommit mode is on by default.
  4608. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  4609. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  4610. **
  4611. ** If certain kinds of errors occur on a statement within a multi-statement
  4612. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  4613. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  4614. ** transaction might be rolled back automatically. The only way to
  4615. ** find out whether SQLite automatically rolled back the transaction after
  4616. ** an error is to use this function.
  4617. **
  4618. ** If another thread changes the autocommit status of the database
  4619. ** connection while this routine is running, then the return value
  4620. ** is undefined.
  4621. */
  4622. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  4623. /*
  4624. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  4625. **
  4626. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  4627. ** to which a [prepared statement] belongs. ^The [database connection]
  4628. ** returned by sqlite3_db_handle is the same [database connection]
  4629. ** that was the first argument
  4630. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  4631. ** create the statement in the first place.
  4632. */
  4633. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  4634. /*
  4635. ** CAPI3REF: Return The Filename For A Database Connection
  4636. **
  4637. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  4638. ** associated with database N of connection D. ^The main database file
  4639. ** has the name "main". If there is no attached database N on the database
  4640. ** connection D, or if database N is a temporary or in-memory database, then
  4641. ** a NULL pointer is returned.
  4642. **
  4643. ** ^The filename returned by this function is the output of the
  4644. ** xFullPathname method of the [VFS]. ^In other words, the filename
  4645. ** will be an absolute pathname, even if the filename used
  4646. ** to open the database originally was a URI or relative pathname.
  4647. */
  4648. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  4649. /*
  4650. ** CAPI3REF: Determine if a database is read-only
  4651. **
  4652. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  4653. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  4654. ** the name of a database on connection D.
  4655. */
  4656. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  4657. /*
  4658. ** CAPI3REF: Find the next prepared statement
  4659. **
  4660. ** ^This interface returns a pointer to the next [prepared statement] after
  4661. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  4662. ** then this interface returns a pointer to the first prepared statement
  4663. ** associated with the database connection pDb. ^If no prepared statement
  4664. ** satisfies the conditions of this routine, it returns NULL.
  4665. **
  4666. ** The [database connection] pointer D in a call to
  4667. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  4668. ** connection and in particular must not be a NULL pointer.
  4669. */
  4670. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  4671. /*
  4672. ** CAPI3REF: Commit And Rollback Notification Callbacks
  4673. **
  4674. ** ^The sqlite3_commit_hook() interface registers a callback
  4675. ** function to be invoked whenever a transaction is [COMMIT | committed].
  4676. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  4677. ** for the same database connection is overridden.
  4678. ** ^The sqlite3_rollback_hook() interface registers a callback
  4679. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  4680. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  4681. ** for the same database connection is overridden.
  4682. ** ^The pArg argument is passed through to the callback.
  4683. ** ^If the callback on a commit hook function returns non-zero,
  4684. ** then the commit is converted into a rollback.
  4685. **
  4686. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  4687. ** return the P argument from the previous call of the same function
  4688. ** on the same [database connection] D, or NULL for
  4689. ** the first call for each function on D.
  4690. **
  4691. ** The commit and rollback hook callbacks are not reentrant.
  4692. ** The callback implementation must not do anything that will modify
  4693. ** the database connection that invoked the callback. Any actions
  4694. ** to modify the database connection must be deferred until after the
  4695. ** completion of the [sqlite3_step()] call that triggered the commit
  4696. ** or rollback hook in the first place.
  4697. ** Note that running any other SQL statements, including SELECT statements,
  4698. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  4699. ** the database connections for the meaning of "modify" in this paragraph.
  4700. **
  4701. ** ^Registering a NULL function disables the callback.
  4702. **
  4703. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  4704. ** operation is allowed to continue normally. ^If the commit hook
  4705. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  4706. ** ^The rollback hook is invoked on a rollback that results from a commit
  4707. ** hook returning non-zero, just as it would be with any other rollback.
  4708. **
  4709. ** ^For the purposes of this API, a transaction is said to have been
  4710. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  4711. ** an error or constraint causes an implicit rollback to occur.
  4712. ** ^The rollback callback is not invoked if a transaction is
  4713. ** automatically rolled back because the database connection is closed.
  4714. **
  4715. ** See also the [sqlite3_update_hook()] interface.
  4716. */
  4717. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  4718. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  4719. /*
  4720. ** CAPI3REF: Data Change Notification Callbacks
  4721. **
  4722. ** ^The sqlite3_update_hook() interface registers a callback function
  4723. ** with the [database connection] identified by the first argument
  4724. ** to be invoked whenever a row is updated, inserted or deleted.
  4725. ** ^Any callback set by a previous call to this function
  4726. ** for the same database connection is overridden.
  4727. **
  4728. ** ^The second argument is a pointer to the function to invoke when a
  4729. ** row is updated, inserted or deleted.
  4730. ** ^The first argument to the callback is a copy of the third argument
  4731. ** to sqlite3_update_hook().
  4732. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  4733. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  4734. ** to be invoked.
  4735. ** ^The third and fourth arguments to the callback contain pointers to the
  4736. ** database and table name containing the affected row.
  4737. ** ^The final callback parameter is the [rowid] of the row.
  4738. ** ^In the case of an update, this is the [rowid] after the update takes place.
  4739. **
  4740. ** ^(The update hook is not invoked when internal system tables are
  4741. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  4742. **
  4743. ** ^In the current implementation, the update hook
  4744. ** is not invoked when duplication rows are deleted because of an
  4745. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  4746. ** invoked when rows are deleted using the [truncate optimization].
  4747. ** The exceptions defined in this paragraph might change in a future
  4748. ** release of SQLite.
  4749. **
  4750. ** The update hook implementation must not do anything that will modify
  4751. ** the database connection that invoked the update hook. Any actions
  4752. ** to modify the database connection must be deferred until after the
  4753. ** completion of the [sqlite3_step()] call that triggered the update hook.
  4754. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4755. ** database connections for the meaning of "modify" in this paragraph.
  4756. **
  4757. ** ^The sqlite3_update_hook(D,C,P) function
  4758. ** returns the P argument from the previous call
  4759. ** on the same [database connection] D, or NULL for
  4760. ** the first call on D.
  4761. **
  4762. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  4763. ** interfaces.
  4764. */
  4765. SQLITE_API void *sqlite3_update_hook(
  4766. sqlite3*,
  4767. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  4768. void*
  4769. );
  4770. /*
  4771. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  4772. **
  4773. ** ^(This routine enables or disables the sharing of the database cache
  4774. ** and schema data structures between [database connection | connections]
  4775. ** to the same database. Sharing is enabled if the argument is true
  4776. ** and disabled if the argument is false.)^
  4777. **
  4778. ** ^Cache sharing is enabled and disabled for an entire process.
  4779. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  4780. ** sharing was enabled or disabled for each thread separately.
  4781. **
  4782. ** ^(The cache sharing mode set by this interface effects all subsequent
  4783. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  4784. ** Existing database connections continue use the sharing mode
  4785. ** that was in effect at the time they were opened.)^
  4786. **
  4787. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  4788. ** successfully. An [error code] is returned otherwise.)^
  4789. **
  4790. ** ^Shared cache is disabled by default. But this might change in
  4791. ** future releases of SQLite. Applications that care about shared
  4792. ** cache setting should set it explicitly.
  4793. **
  4794. ** This interface is threadsafe on processors where writing a
  4795. ** 32-bit integer is atomic.
  4796. **
  4797. ** See Also: [SQLite Shared-Cache Mode]
  4798. */
  4799. SQLITE_API int sqlite3_enable_shared_cache(int);
  4800. /*
  4801. ** CAPI3REF: Attempt To Free Heap Memory
  4802. **
  4803. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  4804. ** of heap memory by deallocating non-essential memory allocations
  4805. ** held by the database library. Memory used to cache database
  4806. ** pages to improve performance is an example of non-essential memory.
  4807. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  4808. ** which might be more or less than the amount requested.
  4809. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  4810. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  4811. **
  4812. ** See also: [sqlite3_db_release_memory()]
  4813. */
  4814. SQLITE_API int sqlite3_release_memory(int);
  4815. /*
  4816. ** CAPI3REF: Free Memory Used By A Database Connection
  4817. **
  4818. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  4819. ** memory as possible from database connection D. Unlike the
  4820. ** [sqlite3_release_memory()] interface, this interface is effect even
  4821. ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  4822. ** omitted.
  4823. **
  4824. ** See also: [sqlite3_release_memory()]
  4825. */
  4826. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  4827. /*
  4828. ** CAPI3REF: Impose A Limit On Heap Size
  4829. **
  4830. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  4831. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  4832. ** ^SQLite strives to keep heap memory utilization below the soft heap
  4833. ** limit by reducing the number of pages held in the page cache
  4834. ** as heap memory usages approaches the limit.
  4835. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  4836. ** below the limit, it will exceed the limit rather than generate
  4837. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  4838. ** is advisory only.
  4839. **
  4840. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  4841. ** the soft heap limit prior to the call, or negative in the case of an
  4842. ** error. ^If the argument N is negative
  4843. ** then no change is made to the soft heap limit. Hence, the current
  4844. ** size of the soft heap limit can be determined by invoking
  4845. ** sqlite3_soft_heap_limit64() with a negative argument.
  4846. **
  4847. ** ^If the argument N is zero then the soft heap limit is disabled.
  4848. **
  4849. ** ^(The soft heap limit is not enforced in the current implementation
  4850. ** if one or more of following conditions are true:
  4851. **
  4852. ** <ul>
  4853. ** <li> The soft heap limit is set to zero.
  4854. ** <li> Memory accounting is disabled using a combination of the
  4855. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  4856. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  4857. ** <li> An alternative page cache implementation is specified using
  4858. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  4859. ** <li> The page cache allocates from its own memory pool supplied
  4860. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  4861. ** from the heap.
  4862. ** </ul>)^
  4863. **
  4864. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  4865. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  4866. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  4867. ** the soft heap limit is enforced on every memory allocation. Without
  4868. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  4869. ** when memory is allocated by the page cache. Testing suggests that because
  4870. ** the page cache is the predominate memory user in SQLite, most
  4871. ** applications will achieve adequate soft heap limit enforcement without
  4872. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  4873. **
  4874. ** The circumstances under which SQLite will enforce the soft heap limit may
  4875. ** changes in future releases of SQLite.
  4876. */
  4877. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  4878. /*
  4879. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  4880. ** DEPRECATED
  4881. **
  4882. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  4883. ** interface. This routine is provided for historical compatibility
  4884. ** only. All new applications should use the
  4885. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  4886. */
  4887. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  4888. /*
  4889. ** CAPI3REF: Extract Metadata About A Column Of A Table
  4890. **
  4891. ** ^This routine returns metadata about a specific column of a specific
  4892. ** database table accessible using the [database connection] handle
  4893. ** passed as the first function argument.
  4894. **
  4895. ** ^The column is identified by the second, third and fourth parameters to
  4896. ** this function. ^The second parameter is either the name of the database
  4897. ** (i.e. "main", "temp", or an attached database) containing the specified
  4898. ** table or NULL. ^If it is NULL, then all attached databases are searched
  4899. ** for the table using the same algorithm used by the database engine to
  4900. ** resolve unqualified table references.
  4901. **
  4902. ** ^The third and fourth parameters to this function are the table and column
  4903. ** name of the desired column, respectively. Neither of these parameters
  4904. ** may be NULL.
  4905. **
  4906. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  4907. ** and subsequent parameters to this function. ^Any of these arguments may be
  4908. ** NULL, in which case the corresponding element of metadata is omitted.
  4909. **
  4910. ** ^(<blockquote>
  4911. ** <table border="1">
  4912. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  4913. **
  4914. ** <tr><td> 5th <td> const char* <td> Data type
  4915. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  4916. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  4917. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  4918. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  4919. ** </table>
  4920. ** </blockquote>)^
  4921. **
  4922. ** ^The memory pointed to by the character pointers returned for the
  4923. ** declaration type and collation sequence is valid only until the next
  4924. ** call to any SQLite API function.
  4925. **
  4926. ** ^If the specified table is actually a view, an [error code] is returned.
  4927. **
  4928. ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
  4929. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  4930. ** parameters are set for the explicitly declared column. ^(If there is no
  4931. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  4932. ** parameters are set as follows:
  4933. **
  4934. ** <pre>
  4935. ** data type: "INTEGER"
  4936. ** collation sequence: "BINARY"
  4937. ** not null: 0
  4938. ** primary key: 1
  4939. ** auto increment: 0
  4940. ** </pre>)^
  4941. **
  4942. ** ^(This function may load one or more schemas from database files. If an
  4943. ** error occurs during this process, or if the requested table or column
  4944. ** cannot be found, an [error code] is returned and an error message left
  4945. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
  4946. **
  4947. ** ^This API is only available if the library was compiled with the
  4948. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  4949. */
  4950. SQLITE_API int sqlite3_table_column_metadata(
  4951. sqlite3 *db, /* Connection handle */
  4952. const char *zDbName, /* Database name or NULL */
  4953. const char *zTableName, /* Table name */
  4954. const char *zColumnName, /* Column name */
  4955. char const **pzDataType, /* OUTPUT: Declared data type */
  4956. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  4957. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  4958. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  4959. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  4960. );
  4961. /*
  4962. ** CAPI3REF: Load An Extension
  4963. **
  4964. ** ^This interface loads an SQLite extension library from the named file.
  4965. **
  4966. ** ^The sqlite3_load_extension() interface attempts to load an
  4967. ** [SQLite extension] library contained in the file zFile. If
  4968. ** the file cannot be loaded directly, attempts are made to load
  4969. ** with various operating-system specific extensions added.
  4970. ** So for example, if "samplelib" cannot be loaded, then names like
  4971. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  4972. ** be tried also.
  4973. **
  4974. ** ^The entry point is zProc.
  4975. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  4976. ** entry point name on its own. It first tries "sqlite3_extension_init".
  4977. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  4978. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  4979. ** characters in the filename from the last "/" to the first following
  4980. ** "." and omitting any initial "lib".)^
  4981. ** ^The sqlite3_load_extension() interface returns
  4982. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  4983. ** ^If an error occurs and pzErrMsg is not 0, then the
  4984. ** [sqlite3_load_extension()] interface shall attempt to
  4985. ** fill *pzErrMsg with error message text stored in memory
  4986. ** obtained from [sqlite3_malloc()]. The calling function
  4987. ** should free this memory by calling [sqlite3_free()].
  4988. **
  4989. ** ^Extension loading must be enabled using
  4990. ** [sqlite3_enable_load_extension()] prior to calling this API,
  4991. ** otherwise an error will be returned.
  4992. **
  4993. ** See also the [load_extension() SQL function].
  4994. */
  4995. SQLITE_API int sqlite3_load_extension(
  4996. sqlite3 *db, /* Load the extension into this database connection */
  4997. const char *zFile, /* Name of the shared library containing extension */
  4998. const char *zProc, /* Entry point. Derived from zFile if 0 */
  4999. char **pzErrMsg /* Put error message here if not 0 */
  5000. );
  5001. /*
  5002. ** CAPI3REF: Enable Or Disable Extension Loading
  5003. **
  5004. ** ^So as not to open security holes in older applications that are
  5005. ** unprepared to deal with [extension loading], and as a means of disabling
  5006. ** [extension loading] while evaluating user-entered SQL, the following API
  5007. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5008. **
  5009. ** ^Extension loading is off by default.
  5010. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5011. ** to turn extension loading on and call it with onoff==0 to turn
  5012. ** it back off again.
  5013. */
  5014. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5015. /*
  5016. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5017. **
  5018. ** ^This interface causes the xEntryPoint() function to be invoked for
  5019. ** each new [database connection] that is created. The idea here is that
  5020. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5021. ** that is to be automatically loaded into all new database connections.
  5022. **
  5023. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5024. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5025. ** arguments and expects and integer result as if the signature of the
  5026. ** entry point where as follows:
  5027. **
  5028. ** <blockquote><pre>
  5029. ** &nbsp; int xEntryPoint(
  5030. ** &nbsp; sqlite3 *db,
  5031. ** &nbsp; const char **pzErrMsg,
  5032. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5033. ** &nbsp; );
  5034. ** </pre></blockquote>)^
  5035. **
  5036. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5037. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5038. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5039. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5040. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5041. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5042. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5043. **
  5044. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5045. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5046. ** will be called more than once for each database connection that is opened.
  5047. **
  5048. ** See also: [sqlite3_reset_auto_extension()]
  5049. ** and [sqlite3_cancel_auto_extension()]
  5050. */
  5051. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  5052. /*
  5053. ** CAPI3REF: Cancel Automatic Extension Loading
  5054. **
  5055. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5056. ** initialization routine X that was registered using a prior call to
  5057. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5058. ** routine returns 1 if initialization routine X was successfully
  5059. ** unregistered and it returns 0 if X was not on the list of initialization
  5060. ** routines.
  5061. */
  5062. SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  5063. /*
  5064. ** CAPI3REF: Reset Automatic Extension Loading
  5065. **
  5066. ** ^This interface disables all automatic extensions previously
  5067. ** registered using [sqlite3_auto_extension()].
  5068. */
  5069. SQLITE_API void sqlite3_reset_auto_extension(void);
  5070. /*
  5071. ** The interface to the virtual-table mechanism is currently considered
  5072. ** to be experimental. The interface might change in incompatible ways.
  5073. ** If this is a problem for you, do not use the interface at this time.
  5074. **
  5075. ** When the virtual-table mechanism stabilizes, we will declare the
  5076. ** interface fixed, support it indefinitely, and remove this comment.
  5077. */
  5078. /*
  5079. ** Structures used by the virtual table interface
  5080. */
  5081. typedef struct sqlite3_vtab sqlite3_vtab;
  5082. typedef struct sqlite3_index_info sqlite3_index_info;
  5083. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5084. typedef struct sqlite3_module sqlite3_module;
  5085. /*
  5086. ** CAPI3REF: Virtual Table Object
  5087. ** KEYWORDS: sqlite3_module {virtual table module}
  5088. **
  5089. ** This structure, sometimes called a "virtual table module",
  5090. ** defines the implementation of a [virtual tables].
  5091. ** This structure consists mostly of methods for the module.
  5092. **
  5093. ** ^A virtual table module is created by filling in a persistent
  5094. ** instance of this structure and passing a pointer to that instance
  5095. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5096. ** ^The registration remains valid until it is replaced by a different
  5097. ** module or until the [database connection] closes. The content
  5098. ** of this structure must not change while it is registered with
  5099. ** any database connection.
  5100. */
  5101. struct sqlite3_module {
  5102. int iVersion;
  5103. int (*xCreate)(sqlite3*, void *pAux,
  5104. int argc, const char *const*argv,
  5105. sqlite3_vtab **ppVTab, char**);
  5106. int (*xConnect)(sqlite3*, void *pAux,
  5107. int argc, const char *const*argv,
  5108. sqlite3_vtab **ppVTab, char**);
  5109. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5110. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5111. int (*xDestroy)(sqlite3_vtab *pVTab);
  5112. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5113. int (*xClose)(sqlite3_vtab_cursor*);
  5114. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5115. int argc, sqlite3_value **argv);
  5116. int (*xNext)(sqlite3_vtab_cursor*);
  5117. int (*xEof)(sqlite3_vtab_cursor*);
  5118. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5119. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5120. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5121. int (*xBegin)(sqlite3_vtab *pVTab);
  5122. int (*xSync)(sqlite3_vtab *pVTab);
  5123. int (*xCommit)(sqlite3_vtab *pVTab);
  5124. int (*xRollback)(sqlite3_vtab *pVTab);
  5125. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5126. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5127. void **ppArg);
  5128. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5129. /* The methods above are in version 1 of the sqlite_module object. Those
  5130. ** below are for version 2 and greater. */
  5131. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5132. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5133. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5134. };
  5135. /*
  5136. ** CAPI3REF: Virtual Table Indexing Information
  5137. ** KEYWORDS: sqlite3_index_info
  5138. **
  5139. ** The sqlite3_index_info structure and its substructures is used as part
  5140. ** of the [virtual table] interface to
  5141. ** pass information into and receive the reply from the [xBestIndex]
  5142. ** method of a [virtual table module]. The fields under **Inputs** are the
  5143. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5144. ** results into the **Outputs** fields.
  5145. **
  5146. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5147. **
  5148. ** <blockquote>column OP expr</blockquote>
  5149. **
  5150. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5151. ** stored in aConstraint[].op using one of the
  5152. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5153. ** ^(The index of the column is stored in
  5154. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5155. ** expr on the right-hand side can be evaluated (and thus the constraint
  5156. ** is usable) and false if it cannot.)^
  5157. **
  5158. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5159. ** and makes other simplifications to the WHERE clause in an attempt to
  5160. ** get as many WHERE clause terms into the form shown above as possible.
  5161. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5162. ** relevant to the particular virtual table being queried.
  5163. **
  5164. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5165. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5166. **
  5167. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5168. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5169. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5170. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5171. ** is true, then the constraint is assumed to be fully handled by the
  5172. ** virtual table and is not checked again by SQLite.)^
  5173. **
  5174. ** ^The idxNum and idxPtr values are recorded and passed into the
  5175. ** [xFilter] method.
  5176. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5177. ** needToFreeIdxPtr is true.
  5178. **
  5179. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5180. ** the correct order to satisfy the ORDER BY clause so that no separate
  5181. ** sorting step is required.
  5182. **
  5183. ** ^The estimatedCost value is an estimate of the cost of doing the
  5184. ** particular lookup. A full scan of a table with N entries should have
  5185. ** a cost of N. A binary search of a table of N entries should have a
  5186. ** cost of approximately log(N).
  5187. */
  5188. struct sqlite3_index_info {
  5189. /* Inputs */
  5190. int nConstraint; /* Number of entries in aConstraint */
  5191. struct sqlite3_index_constraint {
  5192. int iColumn; /* Column on left-hand side of constraint */
  5193. unsigned char op; /* Constraint operator */
  5194. unsigned char usable; /* True if this constraint is usable */
  5195. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5196. } *aConstraint; /* Table of WHERE clause constraints */
  5197. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5198. struct sqlite3_index_orderby {
  5199. int iColumn; /* Column number */
  5200. unsigned char desc; /* True for DESC. False for ASC. */
  5201. } *aOrderBy; /* The ORDER BY clause */
  5202. /* Outputs */
  5203. struct sqlite3_index_constraint_usage {
  5204. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5205. unsigned char omit; /* Do not code a test for this constraint */
  5206. } *aConstraintUsage;
  5207. int idxNum; /* Number used to identify the index */
  5208. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5209. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5210. int orderByConsumed; /* True if output is already ordered */
  5211. double estimatedCost; /* Estimated cost of using this index */
  5212. };
  5213. /*
  5214. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5215. **
  5216. ** These macros defined the allowed values for the
  5217. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5218. ** an operator that is part of a constraint term in the wHERE clause of
  5219. ** a query that uses a [virtual table].
  5220. */
  5221. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5222. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5223. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5224. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5225. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5226. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5227. /*
  5228. ** CAPI3REF: Register A Virtual Table Implementation
  5229. **
  5230. ** ^These routines are used to register a new [virtual table module] name.
  5231. ** ^Module names must be registered before
  5232. ** creating a new [virtual table] using the module and before using a
  5233. ** preexisting [virtual table] for the module.
  5234. **
  5235. ** ^The module name is registered on the [database connection] specified
  5236. ** by the first parameter. ^The name of the module is given by the
  5237. ** second parameter. ^The third parameter is a pointer to
  5238. ** the implementation of the [virtual table module]. ^The fourth
  5239. ** parameter is an arbitrary client data pointer that is passed through
  5240. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5241. ** when a new virtual table is be being created or reinitialized.
  5242. **
  5243. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5244. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5245. ** invoke the destructor function (if it is not NULL) when SQLite
  5246. ** no longer needs the pClientData pointer. ^The destructor will also
  5247. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5248. ** ^The sqlite3_create_module()
  5249. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5250. ** destructor.
  5251. */
  5252. SQLITE_API int sqlite3_create_module(
  5253. sqlite3 *db, /* SQLite connection to register module with */
  5254. const char *zName, /* Name of the module */
  5255. const sqlite3_module *p, /* Methods for the module */
  5256. void *pClientData /* Client data for xCreate/xConnect */
  5257. );
  5258. SQLITE_API int sqlite3_create_module_v2(
  5259. sqlite3 *db, /* SQLite connection to register module with */
  5260. const char *zName, /* Name of the module */
  5261. const sqlite3_module *p, /* Methods for the module */
  5262. void *pClientData, /* Client data for xCreate/xConnect */
  5263. void(*xDestroy)(void*) /* Module destructor function */
  5264. );
  5265. /*
  5266. ** CAPI3REF: Virtual Table Instance Object
  5267. ** KEYWORDS: sqlite3_vtab
  5268. **
  5269. ** Every [virtual table module] implementation uses a subclass
  5270. ** of this object to describe a particular instance
  5271. ** of the [virtual table]. Each subclass will
  5272. ** be tailored to the specific needs of the module implementation.
  5273. ** The purpose of this superclass is to define certain fields that are
  5274. ** common to all module implementations.
  5275. **
  5276. ** ^Virtual tables methods can set an error message by assigning a
  5277. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5278. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5279. ** prior to assigning a new string to zErrMsg. ^After the error message
  5280. ** is delivered up to the client application, the string will be automatically
  5281. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5282. */
  5283. struct sqlite3_vtab {
  5284. const sqlite3_module *pModule; /* The module for this virtual table */
  5285. int nRef; /* NO LONGER USED */
  5286. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5287. /* Virtual table implementations will typically add additional fields */
  5288. };
  5289. /*
  5290. ** CAPI3REF: Virtual Table Cursor Object
  5291. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5292. **
  5293. ** Every [virtual table module] implementation uses a subclass of the
  5294. ** following structure to describe cursors that point into the
  5295. ** [virtual table] and are used
  5296. ** to loop through the virtual table. Cursors are created using the
  5297. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5298. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5299. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5300. ** of the module. Each module implementation will define
  5301. ** the content of a cursor structure to suit its own needs.
  5302. **
  5303. ** This superclass exists in order to define fields of the cursor that
  5304. ** are common to all implementations.
  5305. */
  5306. struct sqlite3_vtab_cursor {
  5307. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5308. /* Virtual table implementations will typically add additional fields */
  5309. };
  5310. /*
  5311. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5312. **
  5313. ** ^The [xCreate] and [xConnect] methods of a
  5314. ** [virtual table module] call this interface
  5315. ** to declare the format (the names and datatypes of the columns) of
  5316. ** the virtual tables they implement.
  5317. */
  5318. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5319. /*
  5320. ** CAPI3REF: Overload A Function For A Virtual Table
  5321. **
  5322. ** ^(Virtual tables can provide alternative implementations of functions
  5323. ** using the [xFindFunction] method of the [virtual table module].
  5324. ** But global versions of those functions
  5325. ** must exist in order to be overloaded.)^
  5326. **
  5327. ** ^(This API makes sure a global version of a function with a particular
  5328. ** name and number of parameters exists. If no such function exists
  5329. ** before this API is called, a new function is created.)^ ^The implementation
  5330. ** of the new function always causes an exception to be thrown. So
  5331. ** the new function is not good for anything by itself. Its only
  5332. ** purpose is to be a placeholder function that can be overloaded
  5333. ** by a [virtual table].
  5334. */
  5335. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5336. /*
  5337. ** The interface to the virtual-table mechanism defined above (back up
  5338. ** to a comment remarkably similar to this one) is currently considered
  5339. ** to be experimental. The interface might change in incompatible ways.
  5340. ** If this is a problem for you, do not use the interface at this time.
  5341. **
  5342. ** When the virtual-table mechanism stabilizes, we will declare the
  5343. ** interface fixed, support it indefinitely, and remove this comment.
  5344. */
  5345. /*
  5346. ** CAPI3REF: A Handle To An Open BLOB
  5347. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5348. **
  5349. ** An instance of this object represents an open BLOB on which
  5350. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5351. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5352. ** and destroyed by [sqlite3_blob_close()].
  5353. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5354. ** can be used to read or write small subsections of the BLOB.
  5355. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5356. */
  5357. typedef struct sqlite3_blob sqlite3_blob;
  5358. /*
  5359. ** CAPI3REF: Open A BLOB For Incremental I/O
  5360. **
  5361. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5362. ** in row iRow, column zColumn, table zTable in database zDb;
  5363. ** in other words, the same BLOB that would be selected by:
  5364. **
  5365. ** <pre>
  5366. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5367. ** </pre>)^
  5368. **
  5369. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5370. ** and write access. ^If it is zero, the BLOB is opened for read access.
  5371. ** ^It is not possible to open a column that is part of an index or primary
  5372. ** key for writing. ^If [foreign key constraints] are enabled, it is
  5373. ** not possible to open a column that is part of a [child key] for writing.
  5374. **
  5375. ** ^Note that the database name is not the filename that contains
  5376. ** the database but rather the symbolic name of the database that
  5377. ** appears after the AS keyword when the database is connected using [ATTACH].
  5378. ** ^For the main database file, the database name is "main".
  5379. ** ^For TEMP tables, the database name is "temp".
  5380. **
  5381. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  5382. ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
  5383. ** to be a null pointer.)^
  5384. ** ^This function sets the [database connection] error code and message
  5385. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
  5386. ** functions. ^Note that the *ppBlob variable is always initialized in a
  5387. ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
  5388. ** regardless of the success or failure of this routine.
  5389. **
  5390. ** ^(If the row that a BLOB handle points to is modified by an
  5391. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5392. ** then the BLOB handle is marked as "expired".
  5393. ** This is true if any column of the row is changed, even a column
  5394. ** other than the one the BLOB handle is open on.)^
  5395. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5396. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5397. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5398. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5399. ** commit if the transaction continues to completion.)^
  5400. **
  5401. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5402. ** the opened blob. ^The size of a blob may not be changed by this
  5403. ** interface. Use the [UPDATE] SQL command to change the size of a
  5404. ** blob.
  5405. **
  5406. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5407. ** and the built-in [zeroblob] SQL function can be used, if desired,
  5408. ** to create an empty, zero-filled blob in which to read or write using
  5409. ** this interface.
  5410. **
  5411. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5412. ** be released by a call to [sqlite3_blob_close()].
  5413. */
  5414. SQLITE_API int sqlite3_blob_open(
  5415. sqlite3*,
  5416. const char *zDb,
  5417. const char *zTable,
  5418. const char *zColumn,
  5419. sqlite3_int64 iRow,
  5420. int flags,
  5421. sqlite3_blob **ppBlob
  5422. );
  5423. /*
  5424. ** CAPI3REF: Move a BLOB Handle to a New Row
  5425. **
  5426. ** ^This function is used to move an existing blob handle so that it points
  5427. ** to a different row of the same database table. ^The new row is identified
  5428. ** by the rowid value passed as the second argument. Only the row can be
  5429. ** changed. ^The database, table and column on which the blob handle is open
  5430. ** remain the same. Moving an existing blob handle to a new row can be
  5431. ** faster than closing the existing handle and opening a new one.
  5432. **
  5433. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5434. ** it must exist and there must be either a blob or text value stored in
  5435. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5436. ** it does not contain a blob or text value, or if another error occurs, an
  5437. ** SQLite error code is returned and the blob handle is considered aborted.
  5438. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5439. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5440. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5441. ** always returns zero.
  5442. **
  5443. ** ^This function sets the database handle error code and message.
  5444. */
  5445. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5446. /*
  5447. ** CAPI3REF: Close A BLOB Handle
  5448. **
  5449. ** ^Closes an open [BLOB handle].
  5450. **
  5451. ** ^Closing a BLOB shall cause the current transaction to commit
  5452. ** if there are no other BLOBs, no pending prepared statements, and the
  5453. ** database connection is in [autocommit mode].
  5454. ** ^If any writes were made to the BLOB, they might be held in cache
  5455. ** until the close operation if they will fit.
  5456. **
  5457. ** ^(Closing the BLOB often forces the changes
  5458. ** out to disk and so if any I/O errors occur, they will likely occur
  5459. ** at the time when the BLOB is closed. Any errors that occur during
  5460. ** closing are reported as a non-zero return value.)^
  5461. **
  5462. ** ^(The BLOB is closed unconditionally. Even if this routine returns
  5463. ** an error code, the BLOB is still closed.)^
  5464. **
  5465. ** ^Calling this routine with a null pointer (such as would be returned
  5466. ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
  5467. */
  5468. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  5469. /*
  5470. ** CAPI3REF: Return The Size Of An Open BLOB
  5471. **
  5472. ** ^Returns the size in bytes of the BLOB accessible via the
  5473. ** successfully opened [BLOB handle] in its only argument. ^The
  5474. ** incremental blob I/O routines can only read or overwriting existing
  5475. ** blob content; they cannot change the size of a blob.
  5476. **
  5477. ** This routine only works on a [BLOB handle] which has been created
  5478. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5479. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5480. ** to this routine results in undefined and probably undesirable behavior.
  5481. */
  5482. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  5483. /*
  5484. ** CAPI3REF: Read Data From A BLOB Incrementally
  5485. **
  5486. ** ^(This function is used to read data from an open [BLOB handle] into a
  5487. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  5488. ** from the open BLOB, starting at offset iOffset.)^
  5489. **
  5490. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5491. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  5492. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  5493. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  5494. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5495. **
  5496. ** ^An attempt to read from an expired [BLOB handle] fails with an
  5497. ** error code of [SQLITE_ABORT].
  5498. **
  5499. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  5500. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5501. **
  5502. ** This routine only works on a [BLOB handle] which has been created
  5503. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5504. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5505. ** to this routine results in undefined and probably undesirable behavior.
  5506. **
  5507. ** See also: [sqlite3_blob_write()].
  5508. */
  5509. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  5510. /*
  5511. ** CAPI3REF: Write Data Into A BLOB Incrementally
  5512. **
  5513. ** ^This function is used to write data into an open [BLOB handle] from a
  5514. ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
  5515. ** into the open BLOB, starting at offset iOffset.
  5516. **
  5517. ** ^If the [BLOB handle] passed as the first argument was not opened for
  5518. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  5519. ** this function returns [SQLITE_READONLY].
  5520. **
  5521. ** ^This function may only modify the contents of the BLOB; it is
  5522. ** not possible to increase the size of a BLOB using this API.
  5523. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5524. ** [SQLITE_ERROR] is returned and no data is written. ^If N is
  5525. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  5526. ** The size of the BLOB (and hence the maximum value of N+iOffset)
  5527. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5528. **
  5529. ** ^An attempt to write to an expired [BLOB handle] fails with an
  5530. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  5531. ** before the [BLOB handle] expired are not rolled back by the
  5532. ** expiration of the handle, though of course those changes might
  5533. ** have been overwritten by the statement that expired the BLOB handle
  5534. ** or by other independent statements.
  5535. **
  5536. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  5537. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5538. **
  5539. ** This routine only works on a [BLOB handle] which has been created
  5540. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5541. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5542. ** to this routine results in undefined and probably undesirable behavior.
  5543. **
  5544. ** See also: [sqlite3_blob_read()].
  5545. */
  5546. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  5547. /*
  5548. ** CAPI3REF: Virtual File System Objects
  5549. **
  5550. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  5551. ** that SQLite uses to interact
  5552. ** with the underlying operating system. Most SQLite builds come with a
  5553. ** single default VFS that is appropriate for the host computer.
  5554. ** New VFSes can be registered and existing VFSes can be unregistered.
  5555. ** The following interfaces are provided.
  5556. **
  5557. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  5558. ** ^Names are case sensitive.
  5559. ** ^Names are zero-terminated UTF-8 strings.
  5560. ** ^If there is no match, a NULL pointer is returned.
  5561. ** ^If zVfsName is NULL then the default VFS is returned.
  5562. **
  5563. ** ^New VFSes are registered with sqlite3_vfs_register().
  5564. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  5565. ** ^The same VFS can be registered multiple times without injury.
  5566. ** ^To make an existing VFS into the default VFS, register it again
  5567. ** with the makeDflt flag set. If two different VFSes with the
  5568. ** same name are registered, the behavior is undefined. If a
  5569. ** VFS is registered with a name that is NULL or an empty string,
  5570. ** then the behavior is undefined.
  5571. **
  5572. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  5573. ** ^(If the default VFS is unregistered, another VFS is chosen as
  5574. ** the default. The choice for the new VFS is arbitrary.)^
  5575. */
  5576. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  5577. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  5578. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  5579. /*
  5580. ** CAPI3REF: Mutexes
  5581. **
  5582. ** The SQLite core uses these routines for thread
  5583. ** synchronization. Though they are intended for internal
  5584. ** use by SQLite, code that links against SQLite is
  5585. ** permitted to use any of these routines.
  5586. **
  5587. ** The SQLite source code contains multiple implementations
  5588. ** of these mutex routines. An appropriate implementation
  5589. ** is selected automatically at compile-time. ^(The following
  5590. ** implementations are available in the SQLite core:
  5591. **
  5592. ** <ul>
  5593. ** <li> SQLITE_MUTEX_PTHREADS
  5594. ** <li> SQLITE_MUTEX_W32
  5595. ** <li> SQLITE_MUTEX_NOOP
  5596. ** </ul>)^
  5597. **
  5598. ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  5599. ** that does no real locking and is appropriate for use in
  5600. ** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and
  5601. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  5602. ** and Windows.
  5603. **
  5604. ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  5605. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  5606. ** implementation is included with the library. In this case the
  5607. ** application must supply a custom mutex implementation using the
  5608. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  5609. ** before calling sqlite3_initialize() or any other public sqlite3_
  5610. ** function that calls sqlite3_initialize().)^
  5611. **
  5612. ** ^The sqlite3_mutex_alloc() routine allocates a new
  5613. ** mutex and returns a pointer to it. ^If it returns NULL
  5614. ** that means that a mutex could not be allocated. ^SQLite
  5615. ** will unwind its stack and return an error. ^(The argument
  5616. ** to sqlite3_mutex_alloc() is one of these integer constants:
  5617. **
  5618. ** <ul>
  5619. ** <li> SQLITE_MUTEX_FAST
  5620. ** <li> SQLITE_MUTEX_RECURSIVE
  5621. ** <li> SQLITE_MUTEX_STATIC_MASTER
  5622. ** <li> SQLITE_MUTEX_STATIC_MEM
  5623. ** <li> SQLITE_MUTEX_STATIC_MEM2
  5624. ** <li> SQLITE_MUTEX_STATIC_PRNG
  5625. ** <li> SQLITE_MUTEX_STATIC_LRU
  5626. ** <li> SQLITE_MUTEX_STATIC_LRU2
  5627. ** </ul>)^
  5628. **
  5629. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  5630. ** cause sqlite3_mutex_alloc() to create
  5631. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  5632. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  5633. ** The mutex implementation does not need to make a distinction
  5634. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  5635. ** not want to. ^SQLite will only request a recursive mutex in
  5636. ** cases where it really needs one. ^If a faster non-recursive mutex
  5637. ** implementation is available on the host platform, the mutex subsystem
  5638. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  5639. **
  5640. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  5641. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  5642. ** a pointer to a static preexisting mutex. ^Six static mutexes are
  5643. ** used by the current version of SQLite. Future versions of SQLite
  5644. ** may add additional static mutexes. Static mutexes are for internal
  5645. ** use by SQLite only. Applications that use SQLite mutexes should
  5646. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  5647. ** SQLITE_MUTEX_RECURSIVE.
  5648. **
  5649. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  5650. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  5651. ** returns a different mutex on every call. ^But for the static
  5652. ** mutex types, the same mutex is returned on every call that has
  5653. ** the same type number.
  5654. **
  5655. ** ^The sqlite3_mutex_free() routine deallocates a previously
  5656. ** allocated dynamic mutex. ^SQLite is careful to deallocate every
  5657. ** dynamic mutex that it allocates. The dynamic mutexes must not be in
  5658. ** use when they are deallocated. Attempting to deallocate a static
  5659. ** mutex results in undefined behavior. ^SQLite never deallocates
  5660. ** a static mutex.
  5661. **
  5662. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  5663. ** to enter a mutex. ^If another thread is already within the mutex,
  5664. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  5665. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  5666. ** upon successful entry. ^(Mutexes created using
  5667. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  5668. ** In such cases the,
  5669. ** mutex must be exited an equal number of times before another thread
  5670. ** can enter.)^ ^(If the same thread tries to enter any other
  5671. ** kind of mutex more than once, the behavior is undefined.
  5672. ** SQLite will never exhibit
  5673. ** such behavior in its own use of mutexes.)^
  5674. **
  5675. ** ^(Some systems (for example, Windows 95) do not support the operation
  5676. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  5677. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  5678. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
  5679. **
  5680. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  5681. ** previously entered by the same thread. ^(The behavior
  5682. ** is undefined if the mutex is not currently entered by the
  5683. ** calling thread or is not currently allocated. SQLite will
  5684. ** never do either.)^
  5685. **
  5686. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  5687. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  5688. ** behave as no-ops.
  5689. **
  5690. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  5691. */
  5692. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  5693. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  5694. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  5695. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  5696. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  5697. /*
  5698. ** CAPI3REF: Mutex Methods Object
  5699. **
  5700. ** An instance of this structure defines the low-level routines
  5701. ** used to allocate and use mutexes.
  5702. **
  5703. ** Usually, the default mutex implementations provided by SQLite are
  5704. ** sufficient, however the user has the option of substituting a custom
  5705. ** implementation for specialized deployments or systems for which SQLite
  5706. ** does not provide a suitable implementation. In this case, the user
  5707. ** creates and populates an instance of this structure to pass
  5708. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  5709. ** Additionally, an instance of this structure can be used as an
  5710. ** output variable when querying the system for the current mutex
  5711. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  5712. **
  5713. ** ^The xMutexInit method defined by this structure is invoked as
  5714. ** part of system initialization by the sqlite3_initialize() function.
  5715. ** ^The xMutexInit routine is called by SQLite exactly once for each
  5716. ** effective call to [sqlite3_initialize()].
  5717. **
  5718. ** ^The xMutexEnd method defined by this structure is invoked as
  5719. ** part of system shutdown by the sqlite3_shutdown() function. The
  5720. ** implementation of this method is expected to release all outstanding
  5721. ** resources obtained by the mutex methods implementation, especially
  5722. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  5723. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  5724. **
  5725. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  5726. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  5727. ** xMutexNotheld) implement the following interfaces (respectively):
  5728. **
  5729. ** <ul>
  5730. ** <li> [sqlite3_mutex_alloc()] </li>
  5731. ** <li> [sqlite3_mutex_free()] </li>
  5732. ** <li> [sqlite3_mutex_enter()] </li>
  5733. ** <li> [sqlite3_mutex_try()] </li>
  5734. ** <li> [sqlite3_mutex_leave()] </li>
  5735. ** <li> [sqlite3_mutex_held()] </li>
  5736. ** <li> [sqlite3_mutex_notheld()] </li>
  5737. ** </ul>)^
  5738. **
  5739. ** The only difference is that the public sqlite3_XXX functions enumerated
  5740. ** above silently ignore any invocations that pass a NULL pointer instead
  5741. ** of a valid mutex handle. The implementations of the methods defined
  5742. ** by this structure are not required to handle this case, the results
  5743. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  5744. ** (i.e. it is acceptable to provide an implementation that segfaults if
  5745. ** it is passed a NULL pointer).
  5746. **
  5747. ** The xMutexInit() method must be threadsafe. ^It must be harmless to
  5748. ** invoke xMutexInit() multiple times within the same process and without
  5749. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  5750. ** xMutexInit() must be no-ops.
  5751. **
  5752. ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  5753. ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
  5754. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  5755. ** memory allocation for a fast or recursive mutex.
  5756. **
  5757. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  5758. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  5759. ** If xMutexInit fails in any way, it is expected to clean up after itself
  5760. ** prior to returning.
  5761. */
  5762. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  5763. struct sqlite3_mutex_methods {
  5764. int (*xMutexInit)(void);
  5765. int (*xMutexEnd)(void);
  5766. sqlite3_mutex *(*xMutexAlloc)(int);
  5767. void (*xMutexFree)(sqlite3_mutex *);
  5768. void (*xMutexEnter)(sqlite3_mutex *);
  5769. int (*xMutexTry)(sqlite3_mutex *);
  5770. void (*xMutexLeave)(sqlite3_mutex *);
  5771. int (*xMutexHeld)(sqlite3_mutex *);
  5772. int (*xMutexNotheld)(sqlite3_mutex *);
  5773. };
  5774. /*
  5775. ** CAPI3REF: Mutex Verification Routines
  5776. **
  5777. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  5778. ** are intended for use inside assert() statements. ^The SQLite core
  5779. ** never uses these routines except inside an assert() and applications
  5780. ** are advised to follow the lead of the core. ^The SQLite core only
  5781. ** provides implementations for these routines when it is compiled
  5782. ** with the SQLITE_DEBUG flag. ^External mutex implementations
  5783. ** are only required to provide these routines if SQLITE_DEBUG is
  5784. ** defined and if NDEBUG is not defined.
  5785. **
  5786. ** ^These routines should return true if the mutex in their argument
  5787. ** is held or not held, respectively, by the calling thread.
  5788. **
  5789. ** ^The implementation is not required to provide versions of these
  5790. ** routines that actually work. If the implementation does not provide working
  5791. ** versions of these routines, it should at least provide stubs that always
  5792. ** return true so that one does not get spurious assertion failures.
  5793. **
  5794. ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  5795. ** the routine should return 1. This seems counter-intuitive since
  5796. ** clearly the mutex cannot be held if it does not exist. But
  5797. ** the reason the mutex does not exist is because the build is not
  5798. ** using mutexes. And we do not want the assert() containing the
  5799. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  5800. ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
  5801. ** interface should also return 1 when given a NULL pointer.
  5802. */
  5803. #ifndef NDEBUG
  5804. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  5805. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  5806. #endif
  5807. /*
  5808. ** CAPI3REF: Mutex Types
  5809. **
  5810. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  5811. ** which is one of these integer constants.
  5812. **
  5813. ** The set of static mutexes may change from one SQLite release to the
  5814. ** next. Applications that override the built-in mutex logic must be
  5815. ** prepared to accommodate additional static mutexes.
  5816. */
  5817. #define SQLITE_MUTEX_FAST 0
  5818. #define SQLITE_MUTEX_RECURSIVE 1
  5819. #define SQLITE_MUTEX_STATIC_MASTER 2
  5820. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  5821. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  5822. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  5823. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  5824. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  5825. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  5826. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  5827. /*
  5828. ** CAPI3REF: Retrieve the mutex for a database connection
  5829. **
  5830. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  5831. ** serializes access to the [database connection] given in the argument
  5832. ** when the [threading mode] is Serialized.
  5833. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  5834. ** routine returns a NULL pointer.
  5835. */
  5836. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  5837. /*
  5838. ** CAPI3REF: Low-Level Control Of Database Files
  5839. **
  5840. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  5841. ** xFileControl method for the [sqlite3_io_methods] object associated
  5842. ** with a particular database identified by the second argument. ^The
  5843. ** name of the database is "main" for the main database or "temp" for the
  5844. ** TEMP database, or the name that appears after the AS keyword for
  5845. ** databases that are added using the [ATTACH] SQL command.
  5846. ** ^A NULL pointer can be used in place of "main" to refer to the
  5847. ** main database file.
  5848. ** ^The third and fourth parameters to this routine
  5849. ** are passed directly through to the second and third parameters of
  5850. ** the xFileControl method. ^The return value of the xFileControl
  5851. ** method becomes the return value of this routine.
  5852. **
  5853. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  5854. ** a pointer to the underlying [sqlite3_file] object to be written into
  5855. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  5856. ** case is a short-circuit path which does not actually invoke the
  5857. ** underlying sqlite3_io_methods.xFileControl method.
  5858. **
  5859. ** ^If the second parameter (zDbName) does not match the name of any
  5860. ** open database file, then SQLITE_ERROR is returned. ^This error
  5861. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  5862. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  5863. ** also return SQLITE_ERROR. There is no way to distinguish between
  5864. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  5865. ** xFileControl method.
  5866. **
  5867. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  5868. */
  5869. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  5870. /*
  5871. ** CAPI3REF: Testing Interface
  5872. **
  5873. ** ^The sqlite3_test_control() interface is used to read out internal
  5874. ** state of SQLite and to inject faults into SQLite for testing
  5875. ** purposes. ^The first parameter is an operation code that determines
  5876. ** the number, meaning, and operation of all subsequent parameters.
  5877. **
  5878. ** This interface is not for use by applications. It exists solely
  5879. ** for verifying the correct operation of the SQLite library. Depending
  5880. ** on how the SQLite library is compiled, this interface might not exist.
  5881. **
  5882. ** The details of the operation codes, their meanings, the parameters
  5883. ** they take, and what they do are all subject to change without notice.
  5884. ** Unlike most of the SQLite API, this function is not guaranteed to
  5885. ** operate consistently from one release to the next.
  5886. */
  5887. SQLITE_API int sqlite3_test_control(int op, ...);
  5888. /*
  5889. ** CAPI3REF: Testing Interface Operation Codes
  5890. **
  5891. ** These constants are the valid operation code parameters used
  5892. ** as the first argument to [sqlite3_test_control()].
  5893. **
  5894. ** These parameters and their meanings are subject to change
  5895. ** without notice. These values are for testing purposes only.
  5896. ** Applications should not use any of these parameters or the
  5897. ** [sqlite3_test_control()] interface.
  5898. */
  5899. #define SQLITE_TESTCTRL_FIRST 5
  5900. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  5901. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  5902. #define SQLITE_TESTCTRL_PRNG_RESET 7
  5903. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  5904. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  5905. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  5906. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  5907. #define SQLITE_TESTCTRL_ASSERT 12
  5908. #define SQLITE_TESTCTRL_ALWAYS 13
  5909. #define SQLITE_TESTCTRL_RESERVE 14
  5910. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  5911. #define SQLITE_TESTCTRL_ISKEYWORD 16
  5912. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  5913. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  5914. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19
  5915. #define SQLITE_TESTCTRL_LAST 19
  5916. /*
  5917. ** CAPI3REF: SQLite Runtime Status
  5918. **
  5919. ** ^This interface is used to retrieve runtime status information
  5920. ** about the performance of SQLite, and optionally to reset various
  5921. ** highwater marks. ^The first argument is an integer code for
  5922. ** the specific parameter to measure. ^(Recognized integer codes
  5923. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  5924. ** ^The current value of the parameter is returned into *pCurrent.
  5925. ** ^The highest recorded value is returned in *pHighwater. ^If the
  5926. ** resetFlag is true, then the highest record value is reset after
  5927. ** *pHighwater is written. ^(Some parameters do not record the highest
  5928. ** value. For those parameters
  5929. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  5930. ** ^(Other parameters record only the highwater mark and not the current
  5931. ** value. For these latter parameters nothing is written into *pCurrent.)^
  5932. **
  5933. ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
  5934. ** non-zero [error code] on failure.
  5935. **
  5936. ** This routine is threadsafe but is not atomic. This routine can be
  5937. ** called while other threads are running the same or different SQLite
  5938. ** interfaces. However the values returned in *pCurrent and
  5939. ** *pHighwater reflect the status of SQLite at different points in time
  5940. ** and it is possible that another thread might change the parameter
  5941. ** in between the times when *pCurrent and *pHighwater are written.
  5942. **
  5943. ** See also: [sqlite3_db_status()]
  5944. */
  5945. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  5946. /*
  5947. ** CAPI3REF: Status Parameters
  5948. ** KEYWORDS: {status parameters}
  5949. **
  5950. ** These integer constants designate various run-time status parameters
  5951. ** that can be returned by [sqlite3_status()].
  5952. **
  5953. ** <dl>
  5954. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  5955. ** <dd>This parameter is the current amount of memory checked out
  5956. ** using [sqlite3_malloc()], either directly or indirectly. The
  5957. ** figure includes calls made to [sqlite3_malloc()] by the application
  5958. ** and internal memory usage by the SQLite library. Scratch memory
  5959. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  5960. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  5961. ** this parameter. The amount returned is the sum of the allocation
  5962. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  5963. **
  5964. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  5965. ** <dd>This parameter records the largest memory allocation request
  5966. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  5967. ** internal equivalents). Only the value returned in the
  5968. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5969. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  5970. **
  5971. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  5972. ** <dd>This parameter records the number of separate memory allocations
  5973. ** currently checked out.</dd>)^
  5974. **
  5975. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  5976. ** <dd>This parameter returns the number of pages used out of the
  5977. ** [pagecache memory allocator] that was configured using
  5978. ** [SQLITE_CONFIG_PAGECACHE]. The
  5979. ** value returned is in pages, not in bytes.</dd>)^
  5980. **
  5981. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  5982. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  5983. ** <dd>This parameter returns the number of bytes of page cache
  5984. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  5985. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  5986. ** returned value includes allocations that overflowed because they
  5987. ** where too large (they were larger than the "sz" parameter to
  5988. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  5989. ** no space was left in the page cache.</dd>)^
  5990. **
  5991. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  5992. ** <dd>This parameter records the largest memory allocation request
  5993. ** handed to [pagecache memory allocator]. Only the value returned in the
  5994. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5995. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  5996. **
  5997. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  5998. ** <dd>This parameter returns the number of allocations used out of the
  5999. ** [scratch memory allocator] configured using
  6000. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6001. ** in bytes. Since a single thread may only have one scratch allocation
  6002. ** outstanding at time, this parameter also reports the number of threads
  6003. ** using scratch memory at the same time.</dd>)^
  6004. **
  6005. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6006. ** <dd>This parameter returns the number of bytes of scratch memory
  6007. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6008. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6009. ** returned include overflows because the requested allocation was too
  6010. ** larger (that is, because the requested allocation was larger than the
  6011. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6012. ** slots were available.
  6013. ** </dd>)^
  6014. **
  6015. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6016. ** <dd>This parameter records the largest memory allocation request
  6017. ** handed to [scratch memory allocator]. Only the value returned in the
  6018. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6019. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6020. **
  6021. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6022. ** <dd>This parameter records the deepest parser stack. It is only
  6023. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6024. ** </dl>
  6025. **
  6026. ** New status parameters may be added from time to time.
  6027. */
  6028. #define SQLITE_STATUS_MEMORY_USED 0
  6029. #define SQLITE_STATUS_PAGECACHE_USED 1
  6030. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6031. #define SQLITE_STATUS_SCRATCH_USED 3
  6032. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6033. #define SQLITE_STATUS_MALLOC_SIZE 5
  6034. #define SQLITE_STATUS_PARSER_STACK 6
  6035. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6036. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6037. #define SQLITE_STATUS_MALLOC_COUNT 9
  6038. /*
  6039. ** CAPI3REF: Database Connection Status
  6040. **
  6041. ** ^This interface is used to retrieve runtime status information
  6042. ** about a single [database connection]. ^The first argument is the
  6043. ** database connection object to be interrogated. ^The second argument
  6044. ** is an integer constant, taken from the set of
  6045. ** [SQLITE_DBSTATUS options], that
  6046. ** determines the parameter to interrogate. The set of
  6047. ** [SQLITE_DBSTATUS options] is likely
  6048. ** to grow in future releases of SQLite.
  6049. **
  6050. ** ^The current value of the requested parameter is written into *pCur
  6051. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6052. ** the resetFlg is true, then the highest instantaneous value is
  6053. ** reset back down to the current value.
  6054. **
  6055. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6056. ** non-zero [error code] on failure.
  6057. **
  6058. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6059. */
  6060. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6061. /*
  6062. ** CAPI3REF: Status Parameters for database connections
  6063. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6064. **
  6065. ** These constants are the available integer "verbs" that can be passed as
  6066. ** the second argument to the [sqlite3_db_status()] interface.
  6067. **
  6068. ** New verbs may be added in future releases of SQLite. Existing verbs
  6069. ** might be discontinued. Applications should check the return code from
  6070. ** [sqlite3_db_status()] to make sure that the call worked.
  6071. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6072. ** if a discontinued or unsupported verb is invoked.
  6073. **
  6074. ** <dl>
  6075. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6076. ** <dd>This parameter returns the number of lookaside memory slots currently
  6077. ** checked out.</dd>)^
  6078. **
  6079. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6080. ** <dd>This parameter returns the number malloc attempts that were
  6081. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6082. ** the current value is always zero.)^
  6083. **
  6084. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6085. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6086. ** <dd>This parameter returns the number malloc attempts that might have
  6087. ** been satisfied using lookaside memory but failed due to the amount of
  6088. ** memory requested being larger than the lookaside slot size.
  6089. ** Only the high-water value is meaningful;
  6090. ** the current value is always zero.)^
  6091. **
  6092. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6093. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6094. ** <dd>This parameter returns the number malloc attempts that might have
  6095. ** been satisfied using lookaside memory but failed due to all lookaside
  6096. ** memory already being in use.
  6097. ** Only the high-water value is meaningful;
  6098. ** the current value is always zero.)^
  6099. **
  6100. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6101. ** <dd>This parameter returns the approximate number of of bytes of heap
  6102. ** memory used by all pager caches associated with the database connection.)^
  6103. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6104. **
  6105. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6106. ** <dd>This parameter returns the approximate number of of bytes of heap
  6107. ** memory used to store the schema for all databases associated
  6108. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6109. ** ^The full amount of memory used by the schemas is reported, even if the
  6110. ** schema memory is shared with other database connections due to
  6111. ** [shared cache mode] being enabled.
  6112. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6113. **
  6114. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6115. ** <dd>This parameter returns the approximate number of of bytes of heap
  6116. ** and lookaside memory used by all prepared statements associated with
  6117. ** the database connection.)^
  6118. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6119. ** </dd>
  6120. **
  6121. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6122. ** <dd>This parameter returns the number of pager cache hits that have
  6123. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6124. ** is always 0.
  6125. ** </dd>
  6126. **
  6127. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6128. ** <dd>This parameter returns the number of pager cache misses that have
  6129. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6130. ** is always 0.
  6131. ** </dd>
  6132. **
  6133. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6134. ** <dd>This parameter returns the number of dirty cache entries that have
  6135. ** been written to disk. Specifically, the number of pages written to the
  6136. ** wal file in wal mode databases, or the number of pages written to the
  6137. ** database file in rollback mode databases. Any pages written as part of
  6138. ** transaction rollback or database recovery operations are not included.
  6139. ** If an IO or other error occurs while writing a page to disk, the effect
  6140. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6141. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6142. ** </dd>
  6143. **
  6144. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6145. ** <dd>This parameter returns zero for the current value if and only if
  6146. ** all foreign key constraints (deferred or immediate) have been
  6147. ** resolved.)^ ^The highwater mark is always 0.
  6148. ** </dd>
  6149. ** </dl>
  6150. */
  6151. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6152. #define SQLITE_DBSTATUS_CACHE_USED 1
  6153. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6154. #define SQLITE_DBSTATUS_STMT_USED 3
  6155. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6156. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6157. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6158. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6159. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6160. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6161. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  6162. #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
  6163. /*
  6164. ** CAPI3REF: Prepared Statement Status
  6165. **
  6166. ** ^(Each prepared statement maintains various
  6167. ** [SQLITE_STMTSTATUS counters] that measure the number
  6168. ** of times it has performed specific operations.)^ These counters can
  6169. ** be used to monitor the performance characteristics of the prepared
  6170. ** statements. For example, if the number of table steps greatly exceeds
  6171. ** the number of table searches or result rows, that would tend to indicate
  6172. ** that the prepared statement is using a full table scan rather than
  6173. ** an index.
  6174. **
  6175. ** ^(This interface is used to retrieve and reset counter values from
  6176. ** a [prepared statement]. The first argument is the prepared statement
  6177. ** object to be interrogated. The second argument
  6178. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6179. ** to be interrogated.)^
  6180. ** ^The current value of the requested counter is returned.
  6181. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6182. ** interface call returns.
  6183. **
  6184. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6185. */
  6186. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6187. /*
  6188. ** CAPI3REF: Status Parameters for prepared statements
  6189. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6190. **
  6191. ** These preprocessor macros define integer codes that name counter
  6192. ** values associated with the [sqlite3_stmt_status()] interface.
  6193. ** The meanings of the various counters are as follows:
  6194. **
  6195. ** <dl>
  6196. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6197. ** <dd>^This is the number of times that SQLite has stepped forward in
  6198. ** a table as part of a full table scan. Large numbers for this counter
  6199. ** may indicate opportunities for performance improvement through
  6200. ** careful use of indices.</dd>
  6201. **
  6202. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6203. ** <dd>^This is the number of sort operations that have occurred.
  6204. ** A non-zero value in this counter may indicate an opportunity to
  6205. ** improvement performance through careful use of indices.</dd>
  6206. **
  6207. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6208. ** <dd>^This is the number of rows inserted into transient indices that
  6209. ** were created automatically in order to help joins run faster.
  6210. ** A non-zero value in this counter may indicate an opportunity to
  6211. ** improvement performance by adding permanent indices that do not
  6212. ** need to be reinitialized each time the statement is run.</dd>
  6213. **
  6214. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  6215. ** <dd>^This is the number of virtual machine operations executed
  6216. ** by the prepared statement if that number is less than or equal
  6217. ** to 2147483647. The number of virtual machine operations can be
  6218. ** used as a proxy for the total work done by the prepared statement.
  6219. ** If the number of virtual machine operations exceeds 2147483647
  6220. ** then the value returned by this statement status code is undefined.
  6221. ** </dd>
  6222. ** </dl>
  6223. */
  6224. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6225. #define SQLITE_STMTSTATUS_SORT 2
  6226. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6227. #define SQLITE_STMTSTATUS_VM_STEP 4
  6228. /*
  6229. ** CAPI3REF: Custom Page Cache Object
  6230. **
  6231. ** The sqlite3_pcache type is opaque. It is implemented by
  6232. ** the pluggable module. The SQLite core has no knowledge of
  6233. ** its size or internal structure and never deals with the
  6234. ** sqlite3_pcache object except by holding and passing pointers
  6235. ** to the object.
  6236. **
  6237. ** See [sqlite3_pcache_methods2] for additional information.
  6238. */
  6239. typedef struct sqlite3_pcache sqlite3_pcache;
  6240. /*
  6241. ** CAPI3REF: Custom Page Cache Object
  6242. **
  6243. ** The sqlite3_pcache_page object represents a single page in the
  6244. ** page cache. The page cache will allocate instances of this
  6245. ** object. Various methods of the page cache use pointers to instances
  6246. ** of this object as parameters or as their return value.
  6247. **
  6248. ** See [sqlite3_pcache_methods2] for additional information.
  6249. */
  6250. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6251. struct sqlite3_pcache_page {
  6252. void *pBuf; /* The content of the page */
  6253. void *pExtra; /* Extra information associated with the page */
  6254. };
  6255. /*
  6256. ** CAPI3REF: Application Defined Page Cache.
  6257. ** KEYWORDS: {page cache}
  6258. **
  6259. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6260. ** register an alternative page cache implementation by passing in an
  6261. ** instance of the sqlite3_pcache_methods2 structure.)^
  6262. ** In many applications, most of the heap memory allocated by
  6263. ** SQLite is used for the page cache.
  6264. ** By implementing a
  6265. ** custom page cache using this API, an application can better control
  6266. ** the amount of memory consumed by SQLite, the way in which
  6267. ** that memory is allocated and released, and the policies used to
  6268. ** determine exactly which parts of a database file are cached and for
  6269. ** how long.
  6270. **
  6271. ** The alternative page cache mechanism is an
  6272. ** extreme measure that is only needed by the most demanding applications.
  6273. ** The built-in page cache is recommended for most uses.
  6274. **
  6275. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6276. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6277. ** the application may discard the parameter after the call to
  6278. ** [sqlite3_config()] returns.)^
  6279. **
  6280. ** [[the xInit() page cache method]]
  6281. ** ^(The xInit() method is called once for each effective
  6282. ** call to [sqlite3_initialize()])^
  6283. ** (usually only once during the lifetime of the process). ^(The xInit()
  6284. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6285. ** The intent of the xInit() method is to set up global data structures
  6286. ** required by the custom page cache implementation.
  6287. ** ^(If the xInit() method is NULL, then the
  6288. ** built-in default page cache is used instead of the application defined
  6289. ** page cache.)^
  6290. **
  6291. ** [[the xShutdown() page cache method]]
  6292. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6293. ** It can be used to clean up
  6294. ** any outstanding resources before process shutdown, if required.
  6295. ** ^The xShutdown() method may be NULL.
  6296. **
  6297. ** ^SQLite automatically serializes calls to the xInit method,
  6298. ** so the xInit method need not be threadsafe. ^The
  6299. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6300. ** not need to be threadsafe either. All other methods must be threadsafe
  6301. ** in multithreaded applications.
  6302. **
  6303. ** ^SQLite will never invoke xInit() more than once without an intervening
  6304. ** call to xShutdown().
  6305. **
  6306. ** [[the xCreate() page cache methods]]
  6307. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6308. ** SQLite will typically create one cache instance for each open database file,
  6309. ** though this is not guaranteed. ^The
  6310. ** first parameter, szPage, is the size in bytes of the pages that must
  6311. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6312. ** second parameter szExtra is a number of bytes of extra storage
  6313. ** associated with each page cache entry. ^The szExtra parameter will
  6314. ** a number less than 250. SQLite will use the
  6315. ** extra szExtra bytes on each page to store metadata about the underlying
  6316. ** database page on disk. The value passed into szExtra depends
  6317. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6318. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6319. ** created will be used to cache database pages of a file stored on disk, or
  6320. ** false if it is used for an in-memory database. The cache implementation
  6321. ** does not have to do anything special based with the value of bPurgeable;
  6322. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6323. ** never invoke xUnpin() except to deliberately delete a page.
  6324. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6325. ** false will always have the "discard" flag set to true.
  6326. ** ^Hence, a cache created with bPurgeable false will
  6327. ** never contain any unpinned pages.
  6328. **
  6329. ** [[the xCachesize() page cache method]]
  6330. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6331. ** suggested maximum cache-size (number of pages stored by) the cache
  6332. ** instance passed as the first argument. This is the value configured using
  6333. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6334. ** parameter, the implementation is not required to do anything with this
  6335. ** value; it is advisory only.
  6336. **
  6337. ** [[the xPagecount() page cache methods]]
  6338. ** The xPagecount() method must return the number of pages currently
  6339. ** stored in the cache, both pinned and unpinned.
  6340. **
  6341. ** [[the xFetch() page cache methods]]
  6342. ** The xFetch() method locates a page in the cache and returns a pointer to
  6343. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6344. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6345. ** pointer to a buffer of szPage bytes used to store the content of a
  6346. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6347. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6348. ** for each entry in the page cache.
  6349. **
  6350. ** The page to be fetched is determined by the key. ^The minimum key value
  6351. ** is 1. After it has been retrieved using xFetch, the page is considered
  6352. ** to be "pinned".
  6353. **
  6354. ** If the requested page is already in the page cache, then the page cache
  6355. ** implementation must return a pointer to the page buffer with its content
  6356. ** intact. If the requested page is not already in the cache, then the
  6357. ** cache implementation should use the value of the createFlag
  6358. ** parameter to help it determined what action to take:
  6359. **
  6360. ** <table border=1 width=85% align=center>
  6361. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  6362. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6363. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6364. ** Otherwise return NULL.
  6365. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6366. ** NULL if allocating a new page is effectively impossible.
  6367. ** </table>
  6368. **
  6369. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6370. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6371. ** failed.)^ In between the to xFetch() calls, SQLite may
  6372. ** attempt to unpin one or more cache pages by spilling the content of
  6373. ** pinned pages to disk and synching the operating system disk cache.
  6374. **
  6375. ** [[the xUnpin() page cache method]]
  6376. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6377. ** as its second argument. If the third parameter, discard, is non-zero,
  6378. ** then the page must be evicted from the cache.
  6379. ** ^If the discard parameter is
  6380. ** zero, then the page may be discarded or retained at the discretion of
  6381. ** page cache implementation. ^The page cache implementation
  6382. ** may choose to evict unpinned pages at any time.
  6383. **
  6384. ** The cache must not perform any reference counting. A single
  6385. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6386. ** to xFetch().
  6387. **
  6388. ** [[the xRekey() page cache methods]]
  6389. ** The xRekey() method is used to change the key value associated with the
  6390. ** page passed as the second argument. If the cache
  6391. ** previously contains an entry associated with newKey, it must be
  6392. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6393. ** to be pinned.
  6394. **
  6395. ** When SQLite calls the xTruncate() method, the cache must discard all
  6396. ** existing cache entries with page numbers (keys) greater than or equal
  6397. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6398. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6399. ** they can be safely discarded.
  6400. **
  6401. ** [[the xDestroy() page cache method]]
  6402. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6403. ** All resources associated with the specified cache should be freed. ^After
  6404. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6405. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6406. ** functions.
  6407. **
  6408. ** [[the xShrink() page cache method]]
  6409. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  6410. ** free up as much of heap memory as possible. The page cache implementation
  6411. ** is not obligated to free any memory, but well-behaved implementations should
  6412. ** do their best.
  6413. */
  6414. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  6415. struct sqlite3_pcache_methods2 {
  6416. int iVersion;
  6417. void *pArg;
  6418. int (*xInit)(void*);
  6419. void (*xShutdown)(void*);
  6420. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  6421. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6422. int (*xPagecount)(sqlite3_pcache*);
  6423. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6424. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  6425. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  6426. unsigned oldKey, unsigned newKey);
  6427. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6428. void (*xDestroy)(sqlite3_pcache*);
  6429. void (*xShrink)(sqlite3_pcache*);
  6430. };
  6431. /*
  6432. ** This is the obsolete pcache_methods object that has now been replaced
  6433. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  6434. ** retained in the header file for backwards compatibility only.
  6435. */
  6436. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6437. struct sqlite3_pcache_methods {
  6438. void *pArg;
  6439. int (*xInit)(void*);
  6440. void (*xShutdown)(void*);
  6441. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6442. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6443. int (*xPagecount)(sqlite3_pcache*);
  6444. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6445. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6446. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6447. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6448. void (*xDestroy)(sqlite3_pcache*);
  6449. };
  6450. /*
  6451. ** CAPI3REF: Online Backup Object
  6452. **
  6453. ** The sqlite3_backup object records state information about an ongoing
  6454. ** online backup operation. ^The sqlite3_backup object is created by
  6455. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6456. ** [sqlite3_backup_finish()].
  6457. **
  6458. ** See Also: [Using the SQLite Online Backup API]
  6459. */
  6460. typedef struct sqlite3_backup sqlite3_backup;
  6461. /*
  6462. ** CAPI3REF: Online Backup API.
  6463. **
  6464. ** The backup API copies the content of one database into another.
  6465. ** It is useful either for creating backups of databases or
  6466. ** for copying in-memory databases to or from persistent files.
  6467. **
  6468. ** See Also: [Using the SQLite Online Backup API]
  6469. **
  6470. ** ^SQLite holds a write transaction open on the destination database file
  6471. ** for the duration of the backup operation.
  6472. ** ^The source database is read-locked only while it is being read;
  6473. ** it is not locked continuously for the entire backup operation.
  6474. ** ^Thus, the backup may be performed on a live source database without
  6475. ** preventing other database connections from
  6476. ** reading or writing to the source database while the backup is underway.
  6477. **
  6478. ** ^(To perform a backup operation:
  6479. ** <ol>
  6480. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  6481. ** backup,
  6482. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  6483. ** the data between the two databases, and finally
  6484. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  6485. ** associated with the backup operation.
  6486. ** </ol>)^
  6487. ** There should be exactly one call to sqlite3_backup_finish() for each
  6488. ** successful call to sqlite3_backup_init().
  6489. **
  6490. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  6491. **
  6492. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  6493. ** [database connection] associated with the destination database
  6494. ** and the database name, respectively.
  6495. ** ^The database name is "main" for the main database, "temp" for the
  6496. ** temporary database, or the name specified after the AS keyword in
  6497. ** an [ATTACH] statement for an attached database.
  6498. ** ^The S and M arguments passed to
  6499. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  6500. ** and database name of the source database, respectively.
  6501. ** ^The source and destination [database connections] (parameters S and D)
  6502. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  6503. ** an error.
  6504. **
  6505. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  6506. ** returned and an error code and error message are stored in the
  6507. ** destination [database connection] D.
  6508. ** ^The error code and message for the failed call to sqlite3_backup_init()
  6509. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  6510. ** [sqlite3_errmsg16()] functions.
  6511. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  6512. ** [sqlite3_backup] object.
  6513. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  6514. ** sqlite3_backup_finish() functions to perform the specified backup
  6515. ** operation.
  6516. **
  6517. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  6518. **
  6519. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  6520. ** the source and destination databases specified by [sqlite3_backup] object B.
  6521. ** ^If N is negative, all remaining source pages are copied.
  6522. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  6523. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  6524. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  6525. ** from source to destination, then it returns [SQLITE_DONE].
  6526. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  6527. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  6528. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  6529. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  6530. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  6531. **
  6532. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  6533. ** <ol>
  6534. ** <li> the destination database was opened read-only, or
  6535. ** <li> the destination database is using write-ahead-log journaling
  6536. ** and the destination and source page sizes differ, or
  6537. ** <li> the destination database is an in-memory database and the
  6538. ** destination and source page sizes differ.
  6539. ** </ol>)^
  6540. **
  6541. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  6542. ** the [sqlite3_busy_handler | busy-handler function]
  6543. ** is invoked (if one is specified). ^If the
  6544. ** busy-handler returns non-zero before the lock is available, then
  6545. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  6546. ** sqlite3_backup_step() can be retried later. ^If the source
  6547. ** [database connection]
  6548. ** is being used to write to the source database when sqlite3_backup_step()
  6549. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  6550. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  6551. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  6552. ** [SQLITE_READONLY] is returned, then
  6553. ** there is no point in retrying the call to sqlite3_backup_step(). These
  6554. ** errors are considered fatal.)^ The application must accept
  6555. ** that the backup operation has failed and pass the backup operation handle
  6556. ** to the sqlite3_backup_finish() to release associated resources.
  6557. **
  6558. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  6559. ** on the destination file. ^The exclusive lock is not released until either
  6560. ** sqlite3_backup_finish() is called or the backup operation is complete
  6561. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  6562. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  6563. ** lasts for the duration of the sqlite3_backup_step() call.
  6564. ** ^Because the source database is not locked between calls to
  6565. ** sqlite3_backup_step(), the source database may be modified mid-way
  6566. ** through the backup process. ^If the source database is modified by an
  6567. ** external process or via a database connection other than the one being
  6568. ** used by the backup operation, then the backup will be automatically
  6569. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  6570. ** database is modified by the using the same database connection as is used
  6571. ** by the backup operation, then the backup database is automatically
  6572. ** updated at the same time.
  6573. **
  6574. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  6575. **
  6576. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  6577. ** application wishes to abandon the backup operation, the application
  6578. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  6579. ** ^The sqlite3_backup_finish() interfaces releases all
  6580. ** resources associated with the [sqlite3_backup] object.
  6581. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  6582. ** active write-transaction on the destination database is rolled back.
  6583. ** The [sqlite3_backup] object is invalid
  6584. ** and may not be used following a call to sqlite3_backup_finish().
  6585. **
  6586. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  6587. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  6588. ** sqlite3_backup_step() completed.
  6589. ** ^If an out-of-memory condition or IO error occurred during any prior
  6590. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  6591. ** sqlite3_backup_finish() returns the corresponding [error code].
  6592. **
  6593. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  6594. ** is not a permanent error and does not affect the return value of
  6595. ** sqlite3_backup_finish().
  6596. **
  6597. ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
  6598. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  6599. **
  6600. ** ^Each call to sqlite3_backup_step() sets two values inside
  6601. ** the [sqlite3_backup] object: the number of pages still to be backed
  6602. ** up and the total number of pages in the source database file.
  6603. ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
  6604. ** retrieve these two values, respectively.
  6605. **
  6606. ** ^The values returned by these functions are only updated by
  6607. ** sqlite3_backup_step(). ^If the source database is modified during a backup
  6608. ** operation, then the values are not updated to account for any extra
  6609. ** pages that need to be updated or the size of the source database file
  6610. ** changing.
  6611. **
  6612. ** <b>Concurrent Usage of Database Handles</b>
  6613. **
  6614. ** ^The source [database connection] may be used by the application for other
  6615. ** purposes while a backup operation is underway or being initialized.
  6616. ** ^If SQLite is compiled and configured to support threadsafe database
  6617. ** connections, then the source database connection may be used concurrently
  6618. ** from within other threads.
  6619. **
  6620. ** However, the application must guarantee that the destination
  6621. ** [database connection] is not passed to any other API (by any thread) after
  6622. ** sqlite3_backup_init() is called and before the corresponding call to
  6623. ** sqlite3_backup_finish(). SQLite does not currently check to see
  6624. ** if the application incorrectly accesses the destination [database connection]
  6625. ** and so no error code is reported, but the operations may malfunction
  6626. ** nevertheless. Use of the destination database connection while a
  6627. ** backup is in progress might also also cause a mutex deadlock.
  6628. **
  6629. ** If running in [shared cache mode], the application must
  6630. ** guarantee that the shared cache used by the destination database
  6631. ** is not accessed while the backup is running. In practice this means
  6632. ** that the application must guarantee that the disk file being
  6633. ** backed up to is not accessed by any connection within the process,
  6634. ** not just the specific connection that was passed to sqlite3_backup_init().
  6635. **
  6636. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  6637. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  6638. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  6639. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  6640. ** same time as another thread is invoking sqlite3_backup_step() it is
  6641. ** possible that they return invalid values.
  6642. */
  6643. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  6644. sqlite3 *pDest, /* Destination database handle */
  6645. const char *zDestName, /* Destination database name */
  6646. sqlite3 *pSource, /* Source database handle */
  6647. const char *zSourceName /* Source database name */
  6648. );
  6649. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  6650. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  6651. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  6652. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  6653. /*
  6654. ** CAPI3REF: Unlock Notification
  6655. **
  6656. ** ^When running in shared-cache mode, a database operation may fail with
  6657. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  6658. ** individual tables within the shared-cache cannot be obtained. See
  6659. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  6660. ** ^This API may be used to register a callback that SQLite will invoke
  6661. ** when the connection currently holding the required lock relinquishes it.
  6662. ** ^This API is only available if the library was compiled with the
  6663. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  6664. **
  6665. ** See Also: [Using the SQLite Unlock Notification Feature].
  6666. **
  6667. ** ^Shared-cache locks are released when a database connection concludes
  6668. ** its current transaction, either by committing it or rolling it back.
  6669. **
  6670. ** ^When a connection (known as the blocked connection) fails to obtain a
  6671. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  6672. ** identity of the database connection (the blocking connection) that
  6673. ** has locked the required resource is stored internally. ^After an
  6674. ** application receives an SQLITE_LOCKED error, it may call the
  6675. ** sqlite3_unlock_notify() method with the blocked connection handle as
  6676. ** the first argument to register for a callback that will be invoked
  6677. ** when the blocking connections current transaction is concluded. ^The
  6678. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  6679. ** call that concludes the blocking connections transaction.
  6680. **
  6681. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  6682. ** there is a chance that the blocking connection will have already
  6683. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  6684. ** If this happens, then the specified callback is invoked immediately,
  6685. ** from within the call to sqlite3_unlock_notify().)^
  6686. **
  6687. ** ^If the blocked connection is attempting to obtain a write-lock on a
  6688. ** shared-cache table, and more than one other connection currently holds
  6689. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  6690. ** the other connections to use as the blocking connection.
  6691. **
  6692. ** ^(There may be at most one unlock-notify callback registered by a
  6693. ** blocked connection. If sqlite3_unlock_notify() is called when the
  6694. ** blocked connection already has a registered unlock-notify callback,
  6695. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  6696. ** called with a NULL pointer as its second argument, then any existing
  6697. ** unlock-notify callback is canceled. ^The blocked connections
  6698. ** unlock-notify callback may also be canceled by closing the blocked
  6699. ** connection using [sqlite3_close()].
  6700. **
  6701. ** The unlock-notify callback is not reentrant. If an application invokes
  6702. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  6703. ** crash or deadlock may be the result.
  6704. **
  6705. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  6706. ** returns SQLITE_OK.
  6707. **
  6708. ** <b>Callback Invocation Details</b>
  6709. **
  6710. ** When an unlock-notify callback is registered, the application provides a
  6711. ** single void* pointer that is passed to the callback when it is invoked.
  6712. ** However, the signature of the callback function allows SQLite to pass
  6713. ** it an array of void* context pointers. The first argument passed to
  6714. ** an unlock-notify callback is a pointer to an array of void* pointers,
  6715. ** and the second is the number of entries in the array.
  6716. **
  6717. ** When a blocking connections transaction is concluded, there may be
  6718. ** more than one blocked connection that has registered for an unlock-notify
  6719. ** callback. ^If two or more such blocked connections have specified the
  6720. ** same callback function, then instead of invoking the callback function
  6721. ** multiple times, it is invoked once with the set of void* context pointers
  6722. ** specified by the blocked connections bundled together into an array.
  6723. ** This gives the application an opportunity to prioritize any actions
  6724. ** related to the set of unblocked database connections.
  6725. **
  6726. ** <b>Deadlock Detection</b>
  6727. **
  6728. ** Assuming that after registering for an unlock-notify callback a
  6729. ** database waits for the callback to be issued before taking any further
  6730. ** action (a reasonable assumption), then using this API may cause the
  6731. ** application to deadlock. For example, if connection X is waiting for
  6732. ** connection Y's transaction to be concluded, and similarly connection
  6733. ** Y is waiting on connection X's transaction, then neither connection
  6734. ** will proceed and the system may remain deadlocked indefinitely.
  6735. **
  6736. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  6737. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  6738. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  6739. ** unlock-notify callback is registered. The system is said to be in
  6740. ** a deadlocked state if connection A has registered for an unlock-notify
  6741. ** callback on the conclusion of connection B's transaction, and connection
  6742. ** B has itself registered for an unlock-notify callback when connection
  6743. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  6744. ** the system is also considered to be deadlocked if connection B has
  6745. ** registered for an unlock-notify callback on the conclusion of connection
  6746. ** C's transaction, where connection C is waiting on connection A. ^Any
  6747. ** number of levels of indirection are allowed.
  6748. **
  6749. ** <b>The "DROP TABLE" Exception</b>
  6750. **
  6751. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  6752. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  6753. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  6754. ** SQLite checks if there are any currently executing SELECT statements
  6755. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  6756. ** returned. In this case there is no "blocking connection", so invoking
  6757. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  6758. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  6759. ** or "DROP INDEX" query, an infinite loop might be the result.
  6760. **
  6761. ** One way around this problem is to check the extended error code returned
  6762. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  6763. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  6764. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  6765. ** SQLITE_LOCKED.)^
  6766. */
  6767. SQLITE_API int sqlite3_unlock_notify(
  6768. sqlite3 *pBlocked, /* Waiting connection */
  6769. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  6770. void *pNotifyArg /* Argument to pass to xNotify */
  6771. );
  6772. /*
  6773. ** CAPI3REF: String Comparison
  6774. **
  6775. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  6776. ** and extensions to compare the contents of two buffers containing UTF-8
  6777. ** strings in a case-independent fashion, using the same definition of "case
  6778. ** independence" that SQLite uses internally when comparing identifiers.
  6779. */
  6780. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  6781. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  6782. /*
  6783. ** CAPI3REF: String Globbing
  6784. *
  6785. ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
  6786. ** the glob pattern P, and it returns non-zero if string X does not match
  6787. ** the glob pattern P. ^The definition of glob pattern matching used in
  6788. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  6789. ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
  6790. ** sensitive.
  6791. **
  6792. ** Note that this routine returns zero on a match and non-zero if the strings
  6793. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  6794. */
  6795. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  6796. /*
  6797. ** CAPI3REF: Error Logging Interface
  6798. **
  6799. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  6800. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  6801. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  6802. ** used with [sqlite3_snprintf()] to generate the final output string.
  6803. **
  6804. ** The sqlite3_log() interface is intended for use by extensions such as
  6805. ** virtual tables, collating functions, and SQL functions. While there is
  6806. ** nothing to prevent an application from calling sqlite3_log(), doing so
  6807. ** is considered bad form.
  6808. **
  6809. ** The zFormat string must not be NULL.
  6810. **
  6811. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  6812. ** will not use dynamically allocated memory. The log message is stored in
  6813. ** a fixed-length buffer on the stack. If the log message is longer than
  6814. ** a few hundred characters, it will be truncated to the length of the
  6815. ** buffer.
  6816. */
  6817. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  6818. /*
  6819. ** CAPI3REF: Write-Ahead Log Commit Hook
  6820. **
  6821. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  6822. ** will be invoked each time a database connection commits data to a
  6823. ** [write-ahead log] (i.e. whenever a transaction is committed in
  6824. ** [journal_mode | journal_mode=WAL mode]).
  6825. **
  6826. ** ^The callback is invoked by SQLite after the commit has taken place and
  6827. ** the associated write-lock on the database released, so the implementation
  6828. ** may read, write or [checkpoint] the database as required.
  6829. **
  6830. ** ^The first parameter passed to the callback function when it is invoked
  6831. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  6832. ** registering the callback. ^The second is a copy of the database handle.
  6833. ** ^The third parameter is the name of the database that was written to -
  6834. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  6835. ** is the number of pages currently in the write-ahead log file,
  6836. ** including those that were just committed.
  6837. **
  6838. ** The callback function should normally return [SQLITE_OK]. ^If an error
  6839. ** code is returned, that error will propagate back up through the
  6840. ** SQLite code base to cause the statement that provoked the callback
  6841. ** to report an error, though the commit will have still occurred. If the
  6842. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  6843. ** that does not correspond to any valid SQLite error code, the results
  6844. ** are undefined.
  6845. **
  6846. ** A single database handle may have at most a single write-ahead log callback
  6847. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  6848. ** previously registered write-ahead log callback. ^Note that the
  6849. ** [sqlite3_wal_autocheckpoint()] interface and the
  6850. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  6851. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  6852. */
  6853. SQLITE_API void *sqlite3_wal_hook(
  6854. sqlite3*,
  6855. int(*)(void *,sqlite3*,const char*,int),
  6856. void*
  6857. );
  6858. /*
  6859. ** CAPI3REF: Configure an auto-checkpoint
  6860. **
  6861. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  6862. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  6863. ** to automatically [checkpoint]
  6864. ** after committing a transaction if there are N or
  6865. ** more frames in the [write-ahead log] file. ^Passing zero or
  6866. ** a negative value as the nFrame parameter disables automatic
  6867. ** checkpoints entirely.
  6868. **
  6869. ** ^The callback registered by this function replaces any existing callback
  6870. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  6871. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  6872. ** configured by this function.
  6873. **
  6874. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  6875. ** from SQL.
  6876. **
  6877. ** ^Every new [database connection] defaults to having the auto-checkpoint
  6878. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  6879. ** pages. The use of this interface
  6880. ** is only necessary if the default setting is found to be suboptimal
  6881. ** for a particular application.
  6882. */
  6883. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  6884. /*
  6885. ** CAPI3REF: Checkpoint a database
  6886. **
  6887. ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
  6888. ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
  6889. ** empty string, then a checkpoint is run on all databases of
  6890. ** connection D. ^If the database connection D is not in
  6891. ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
  6892. **
  6893. ** ^The [wal_checkpoint pragma] can be used to invoke this interface
  6894. ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
  6895. ** [wal_autocheckpoint pragma] can be used to cause this interface to be
  6896. ** run whenever the WAL reaches a certain size threshold.
  6897. **
  6898. ** See also: [sqlite3_wal_checkpoint_v2()]
  6899. */
  6900. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  6901. /*
  6902. ** CAPI3REF: Checkpoint a database
  6903. **
  6904. ** Run a checkpoint operation on WAL database zDb attached to database
  6905. ** handle db. The specific operation is determined by the value of the
  6906. ** eMode parameter:
  6907. **
  6908. ** <dl>
  6909. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  6910. ** Checkpoint as many frames as possible without waiting for any database
  6911. ** readers or writers to finish. Sync the db file if all frames in the log
  6912. ** are checkpointed. This mode is the same as calling
  6913. ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
  6914. **
  6915. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  6916. ** This mode blocks (calls the busy-handler callback) until there is no
  6917. ** database writer and all readers are reading from the most recent database
  6918. ** snapshot. It then checkpoints all frames in the log file and syncs the
  6919. ** database file. This call blocks database writers while it is running,
  6920. ** but not database readers.
  6921. **
  6922. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  6923. ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
  6924. ** checkpointing the log file it blocks (calls the busy-handler callback)
  6925. ** until all readers are reading from the database file only. This ensures
  6926. ** that the next client to write to the database file restarts the log file
  6927. ** from the beginning. This call blocks database writers while it is running,
  6928. ** but not database readers.
  6929. ** </dl>
  6930. **
  6931. ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
  6932. ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
  6933. ** the total number of checkpointed frames (including any that were already
  6934. ** checkpointed when this function is called). *pnLog and *pnCkpt may be
  6935. ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
  6936. ** If no values are available because of an error, they are both set to -1
  6937. ** before returning to communicate this to the caller.
  6938. **
  6939. ** All calls obtain an exclusive "checkpoint" lock on the database file. If
  6940. ** any other process is running a checkpoint operation at the same time, the
  6941. ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
  6942. ** busy-handler configured, it will not be invoked in this case.
  6943. **
  6944. ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
  6945. ** "writer" lock on the database file. If the writer lock cannot be obtained
  6946. ** immediately, and a busy-handler is configured, it is invoked and the writer
  6947. ** lock retried until either the busy-handler returns 0 or the lock is
  6948. ** successfully obtained. The busy-handler is also invoked while waiting for
  6949. ** database readers as described above. If the busy-handler returns 0 before
  6950. ** the writer lock is obtained or while waiting for database readers, the
  6951. ** checkpoint operation proceeds from that point in the same way as
  6952. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  6953. ** without blocking any further. SQLITE_BUSY is returned in this case.
  6954. **
  6955. ** If parameter zDb is NULL or points to a zero length string, then the
  6956. ** specified operation is attempted on all WAL databases. In this case the
  6957. ** values written to output parameters *pnLog and *pnCkpt are undefined. If
  6958. ** an SQLITE_BUSY error is encountered when processing one or more of the
  6959. ** attached WAL databases, the operation is still attempted on any remaining
  6960. ** attached databases and SQLITE_BUSY is returned to the caller. If any other
  6961. ** error occurs while processing an attached database, processing is abandoned
  6962. ** and the error code returned to the caller immediately. If no error
  6963. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  6964. ** databases, SQLITE_OK is returned.
  6965. **
  6966. ** If database zDb is the name of an attached database that is not in WAL
  6967. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
  6968. ** zDb is not NULL (or a zero length string) and is not the name of any
  6969. ** attached database, SQLITE_ERROR is returned to the caller.
  6970. */
  6971. SQLITE_API int sqlite3_wal_checkpoint_v2(
  6972. sqlite3 *db, /* Database handle */
  6973. const char *zDb, /* Name of attached database (or NULL) */
  6974. int eMode, /* SQLITE_CHECKPOINT_* value */
  6975. int *pnLog, /* OUT: Size of WAL log in frames */
  6976. int *pnCkpt /* OUT: Total number of frames checkpointed */
  6977. );
  6978. /*
  6979. ** CAPI3REF: Checkpoint operation parameters
  6980. **
  6981. ** These constants can be used as the 3rd parameter to
  6982. ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
  6983. ** documentation for additional information about the meaning and use of
  6984. ** each of these values.
  6985. */
  6986. #define SQLITE_CHECKPOINT_PASSIVE 0
  6987. #define SQLITE_CHECKPOINT_FULL 1
  6988. #define SQLITE_CHECKPOINT_RESTART 2
  6989. /*
  6990. ** CAPI3REF: Virtual Table Interface Configuration
  6991. **
  6992. ** This function may be called by either the [xConnect] or [xCreate] method
  6993. ** of a [virtual table] implementation to configure
  6994. ** various facets of the virtual table interface.
  6995. **
  6996. ** If this interface is invoked outside the context of an xConnect or
  6997. ** xCreate virtual table method then the behavior is undefined.
  6998. **
  6999. ** At present, there is only one option that may be configured using
  7000. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7001. ** may be added in the future.
  7002. */
  7003. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  7004. /*
  7005. ** CAPI3REF: Virtual Table Configuration Options
  7006. **
  7007. ** These macros define the various options to the
  7008. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7009. ** can use to customize and optimize their behavior.
  7010. **
  7011. ** <dl>
  7012. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7013. ** <dd>Calls of the form
  7014. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7015. ** where X is an integer. If X is zero, then the [virtual table] whose
  7016. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7017. ** support constraints. In this configuration (which is the default) if
  7018. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7019. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7020. ** specified as part of the users SQL statement, regardless of the actual
  7021. ** ON CONFLICT mode specified.
  7022. **
  7023. ** If X is non-zero, then the virtual table implementation guarantees
  7024. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7025. ** any modifications to internal or persistent data structures have been made.
  7026. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7027. ** is able to roll back a statement or database transaction, and abandon
  7028. ** or continue processing the current SQL statement as appropriate.
  7029. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7030. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7031. ** had been ABORT.
  7032. **
  7033. ** Virtual table implementations that are required to handle OR REPLACE
  7034. ** must do so within the [xUpdate] method. If a call to the
  7035. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7036. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7037. ** silently replace the appropriate rows within the xUpdate callback and
  7038. ** return SQLITE_OK. Or, if this is not possible, it may return
  7039. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7040. ** constraint handling.
  7041. ** </dl>
  7042. */
  7043. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7044. /*
  7045. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7046. **
  7047. ** This function may only be called from within a call to the [xUpdate] method
  7048. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7049. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7050. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7051. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7052. ** [virtual table].
  7053. */
  7054. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  7055. /*
  7056. ** CAPI3REF: Conflict resolution modes
  7057. **
  7058. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7059. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7060. ** is for the SQL statement being evaluated.
  7061. **
  7062. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7063. ** return value from the [sqlite3_set_authorizer()] callback and that
  7064. ** [SQLITE_ABORT] is also a [result code].
  7065. */
  7066. #define SQLITE_ROLLBACK 1
  7067. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7068. #define SQLITE_FAIL 3
  7069. /* #define SQLITE_ABORT 4 // Also an error code */
  7070. #define SQLITE_REPLACE 5
  7071. /*
  7072. ** Undo the hack that converts floating point types to integer for
  7073. ** builds on processors without floating point support.
  7074. */
  7075. #ifdef SQLITE_OMIT_FLOATING_POINT
  7076. # undef double
  7077. #endif
  7078. #if 0
  7079. } /* End of the 'extern "C"' block */
  7080. #endif
  7081. #endif /* _SQLITE3_H_ */
  7082. /*
  7083. ** 2010 August 30
  7084. **
  7085. ** The author disclaims copyright to this source code. In place of
  7086. ** a legal notice, here is a blessing:
  7087. **
  7088. ** May you do good and not evil.
  7089. ** May you find forgiveness for yourself and forgive others.
  7090. ** May you share freely, never taking more than you give.
  7091. **
  7092. *************************************************************************
  7093. */
  7094. #ifndef _SQLITE3RTREE_H_
  7095. #define _SQLITE3RTREE_H_
  7096. #if 0
  7097. extern "C" {
  7098. #endif
  7099. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7100. /*
  7101. ** Register a geometry callback named zGeom that can be used as part of an
  7102. ** R-Tree geometry query as follows:
  7103. **
  7104. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7105. */
  7106. SQLITE_API int sqlite3_rtree_geometry_callback(
  7107. sqlite3 *db,
  7108. const char *zGeom,
  7109. #ifdef SQLITE_RTREE_INT_ONLY
  7110. int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
  7111. #else
  7112. int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
  7113. #endif
  7114. void *pContext
  7115. );
  7116. /*
  7117. ** A pointer to a structure of the following type is passed as the first
  7118. ** argument to callbacks registered using rtree_geometry_callback().
  7119. */
  7120. struct sqlite3_rtree_geometry {
  7121. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7122. int nParam; /* Size of array aParam[] */
  7123. double *aParam; /* Parameters passed to SQL geom function */
  7124. void *pUser; /* Callback implementation user data */
  7125. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7126. };
  7127. #if 0
  7128. } /* end of the 'extern "C"' block */
  7129. #endif
  7130. #endif /* ifndef _SQLITE3RTREE_H_ */
  7131. /************** End of sqlite3.h *********************************************/
  7132. /************** Begin file sqliteInt.h ***************************************/
  7133. /*
  7134. ** 2001 September 15
  7135. **
  7136. ** The author disclaims copyright to this source code. In place of
  7137. ** a legal notice, here is a blessing:
  7138. **
  7139. ** May you do good and not evil.
  7140. ** May you find forgiveness for yourself and forgive others.
  7141. ** May you share freely, never taking more than you give.
  7142. **
  7143. *************************************************************************
  7144. ** Internal interface definitions for SQLite.
  7145. **
  7146. */
  7147. #ifndef _SQLITEINT_H_
  7148. #define _SQLITEINT_H_
  7149. /*
  7150. ** These #defines should enable >2GB file support on POSIX if the
  7151. ** underlying operating system supports it. If the OS lacks
  7152. ** large file support, or if the OS is windows, these should be no-ops.
  7153. **
  7154. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  7155. ** system #includes. Hence, this block of code must be the very first
  7156. ** code in all source files.
  7157. **
  7158. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  7159. ** on the compiler command line. This is necessary if you are compiling
  7160. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  7161. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  7162. ** without this option, LFS is enable. But LFS does not exist in the kernel
  7163. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  7164. ** portability you should omit LFS.
  7165. **
  7166. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  7167. */
  7168. #ifndef SQLITE_DISABLE_LFS
  7169. # define _LARGE_FILE 1
  7170. # ifndef _FILE_OFFSET_BITS
  7171. # define _FILE_OFFSET_BITS 64
  7172. # endif
  7173. # define _LARGEFILE_SOURCE 1
  7174. #endif
  7175. /*
  7176. ** Include the configuration header output by 'configure' if we're using the
  7177. ** autoconf-based build
  7178. */
  7179. #ifdef _HAVE_SQLITE_CONFIG_H
  7180. #include "config.h"
  7181. #endif
  7182. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  7183. /************** Begin file sqliteLimit.h *************************************/
  7184. /*
  7185. ** 2007 May 7
  7186. **
  7187. ** The author disclaims copyright to this source code. In place of
  7188. ** a legal notice, here is a blessing:
  7189. **
  7190. ** May you do good and not evil.
  7191. ** May you find forgiveness for yourself and forgive others.
  7192. ** May you share freely, never taking more than you give.
  7193. **
  7194. *************************************************************************
  7195. **
  7196. ** This file defines various limits of what SQLite can process.
  7197. */
  7198. /*
  7199. ** The maximum length of a TEXT or BLOB in bytes. This also
  7200. ** limits the size of a row in a table or index.
  7201. **
  7202. ** The hard limit is the ability of a 32-bit signed integer
  7203. ** to count the size: 2^31-1 or 2147483647.
  7204. */
  7205. #ifndef SQLITE_MAX_LENGTH
  7206. # define SQLITE_MAX_LENGTH 1000000000
  7207. #endif
  7208. /*
  7209. ** This is the maximum number of
  7210. **
  7211. ** * Columns in a table
  7212. ** * Columns in an index
  7213. ** * Columns in a view
  7214. ** * Terms in the SET clause of an UPDATE statement
  7215. ** * Terms in the result set of a SELECT statement
  7216. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  7217. ** * Terms in the VALUES clause of an INSERT statement
  7218. **
  7219. ** The hard upper limit here is 32676. Most database people will
  7220. ** tell you that in a well-normalized database, you usually should
  7221. ** not have more than a dozen or so columns in any table. And if
  7222. ** that is the case, there is no point in having more than a few
  7223. ** dozen values in any of the other situations described above.
  7224. */
  7225. #ifndef SQLITE_MAX_COLUMN
  7226. # define SQLITE_MAX_COLUMN 2000
  7227. #endif
  7228. /*
  7229. ** The maximum length of a single SQL statement in bytes.
  7230. **
  7231. ** It used to be the case that setting this value to zero would
  7232. ** turn the limit off. That is no longer true. It is not possible
  7233. ** to turn this limit off.
  7234. */
  7235. #ifndef SQLITE_MAX_SQL_LENGTH
  7236. # define SQLITE_MAX_SQL_LENGTH 1000000000
  7237. #endif
  7238. /*
  7239. ** The maximum depth of an expression tree. This is limited to
  7240. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  7241. ** want to place more severe limits on the complexity of an
  7242. ** expression.
  7243. **
  7244. ** A value of 0 used to mean that the limit was not enforced.
  7245. ** But that is no longer true. The limit is now strictly enforced
  7246. ** at all times.
  7247. */
  7248. #ifndef SQLITE_MAX_EXPR_DEPTH
  7249. # define SQLITE_MAX_EXPR_DEPTH 1000
  7250. #endif
  7251. /*
  7252. ** The maximum number of terms in a compound SELECT statement.
  7253. ** The code generator for compound SELECT statements does one
  7254. ** level of recursion for each term. A stack overflow can result
  7255. ** if the number of terms is too large. In practice, most SQL
  7256. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  7257. ** any limit on the number of terms in a compount SELECT.
  7258. */
  7259. #ifndef SQLITE_MAX_COMPOUND_SELECT
  7260. # define SQLITE_MAX_COMPOUND_SELECT 500
  7261. #endif
  7262. /*
  7263. ** The maximum number of opcodes in a VDBE program.
  7264. ** Not currently enforced.
  7265. */
  7266. #ifndef SQLITE_MAX_VDBE_OP
  7267. # define SQLITE_MAX_VDBE_OP 25000
  7268. #endif
  7269. /*
  7270. ** The maximum number of arguments to an SQL function.
  7271. */
  7272. #ifndef SQLITE_MAX_FUNCTION_ARG
  7273. # define SQLITE_MAX_FUNCTION_ARG 127
  7274. #endif
  7275. /*
  7276. ** The maximum number of in-memory pages to use for the main database
  7277. ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
  7278. */
  7279. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  7280. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  7281. #endif
  7282. #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
  7283. # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
  7284. #endif
  7285. /*
  7286. ** The default number of frames to accumulate in the log file before
  7287. ** checkpointing the database in WAL mode.
  7288. */
  7289. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  7290. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  7291. #endif
  7292. /*
  7293. ** The maximum number of attached databases. This must be between 0
  7294. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  7295. ** is used internally to track attached databases.
  7296. */
  7297. #ifndef SQLITE_MAX_ATTACHED
  7298. # define SQLITE_MAX_ATTACHED 10
  7299. #endif
  7300. /*
  7301. ** The maximum value of a ?nnn wildcard that the parser will accept.
  7302. */
  7303. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  7304. # define SQLITE_MAX_VARIABLE_NUMBER 999
  7305. #endif
  7306. /* Maximum page size. The upper bound on this value is 65536. This a limit
  7307. ** imposed by the use of 16-bit offsets within each page.
  7308. **
  7309. ** Earlier versions of SQLite allowed the user to change this value at
  7310. ** compile time. This is no longer permitted, on the grounds that it creates
  7311. ** a library that is technically incompatible with an SQLite library
  7312. ** compiled with a different limit. If a process operating on a database
  7313. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  7314. ** compiled with the default page-size limit will not be able to rollback
  7315. ** the aborted transaction. This could lead to database corruption.
  7316. */
  7317. #ifdef SQLITE_MAX_PAGE_SIZE
  7318. # undef SQLITE_MAX_PAGE_SIZE
  7319. #endif
  7320. #define SQLITE_MAX_PAGE_SIZE 65536
  7321. /*
  7322. ** The default size of a database page.
  7323. */
  7324. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  7325. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  7326. #endif
  7327. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7328. # undef SQLITE_DEFAULT_PAGE_SIZE
  7329. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7330. #endif
  7331. /*
  7332. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  7333. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  7334. ** device characteristics (sector-size and atomic write() support),
  7335. ** SQLite may choose a larger value. This constant is the maximum value
  7336. ** SQLite will choose on its own.
  7337. */
  7338. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7339. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  7340. #endif
  7341. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7342. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7343. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7344. #endif
  7345. /*
  7346. ** Maximum number of pages in one database file.
  7347. **
  7348. ** This is really just the default value for the max_page_count pragma.
  7349. ** This value can be lowered (or raised) at run-time using that the
  7350. ** max_page_count macro.
  7351. */
  7352. #ifndef SQLITE_MAX_PAGE_COUNT
  7353. # define SQLITE_MAX_PAGE_COUNT 1073741823
  7354. #endif
  7355. /*
  7356. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  7357. ** operator.
  7358. */
  7359. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  7360. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  7361. #endif
  7362. /*
  7363. ** Maximum depth of recursion for triggers.
  7364. **
  7365. ** A value of 1 means that a trigger program will not be able to itself
  7366. ** fire any triggers. A value of 0 means that no trigger programs at all
  7367. ** may be executed.
  7368. */
  7369. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  7370. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  7371. #endif
  7372. /************** End of sqliteLimit.h *****************************************/
  7373. /************** Continuing where we left off in sqliteInt.h ******************/
  7374. /* Disable nuisance warnings on Borland compilers */
  7375. #if defined(__BORLANDC__)
  7376. #pragma warn -rch /* unreachable code */
  7377. #pragma warn -ccc /* Condition is always true or false */
  7378. #pragma warn -aus /* Assigned value is never used */
  7379. #pragma warn -csu /* Comparing signed and unsigned */
  7380. #pragma warn -spa /* Suspicious pointer arithmetic */
  7381. #endif
  7382. /* Needed for various definitions... */
  7383. #ifndef _GNU_SOURCE
  7384. # define _GNU_SOURCE
  7385. #endif
  7386. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  7387. # define _BSD_SOURCE
  7388. #endif
  7389. /*
  7390. ** Include standard header files as necessary
  7391. */
  7392. #ifdef HAVE_STDINT_H
  7393. #include <stdint.h>
  7394. #endif
  7395. #ifdef HAVE_INTTYPES_H
  7396. #include <inttypes.h>
  7397. #endif
  7398. /*
  7399. ** The following macros are used to cast pointers to integers and
  7400. ** integers to pointers. The way you do this varies from one compiler
  7401. ** to the next, so we have developed the following set of #if statements
  7402. ** to generate appropriate macros for a wide range of compilers.
  7403. **
  7404. ** The correct "ANSI" way to do this is to use the intptr_t type.
  7405. ** Unfortunately, that typedef is not available on all compilers, or
  7406. ** if it is available, it requires an #include of specific headers
  7407. ** that vary from one machine to the next.
  7408. **
  7409. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  7410. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  7411. ** So we have to define the macros in different ways depending on the
  7412. ** compiler.
  7413. */
  7414. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  7415. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  7416. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  7417. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  7418. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  7419. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  7420. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  7421. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  7422. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  7423. #else /* Generates a warning - but it always works */
  7424. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  7425. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  7426. #endif
  7427. /*
  7428. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  7429. ** 0 means mutexes are permanently disable and the library is never
  7430. ** threadsafe. 1 means the library is serialized which is the highest
  7431. ** level of threadsafety. 2 means the library is multithreaded - multiple
  7432. ** threads can use SQLite as long as no two threads try to use the same
  7433. ** database connection at the same time.
  7434. **
  7435. ** Older versions of SQLite used an optional THREADSAFE macro.
  7436. ** We support that for legacy.
  7437. */
  7438. #if !defined(SQLITE_THREADSAFE)
  7439. # if defined(THREADSAFE)
  7440. # define SQLITE_THREADSAFE THREADSAFE
  7441. # else
  7442. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  7443. # endif
  7444. #endif
  7445. /*
  7446. ** Powersafe overwrite is on by default. But can be turned off using
  7447. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  7448. */
  7449. #ifndef SQLITE_POWERSAFE_OVERWRITE
  7450. # define SQLITE_POWERSAFE_OVERWRITE 1
  7451. #endif
  7452. /*
  7453. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  7454. ** It determines whether or not the features related to
  7455. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  7456. ** be overridden at runtime using the sqlite3_config() API.
  7457. */
  7458. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  7459. # define SQLITE_DEFAULT_MEMSTATUS 1
  7460. #endif
  7461. /*
  7462. ** Exactly one of the following macros must be defined in order to
  7463. ** specify which memory allocation subsystem to use.
  7464. **
  7465. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  7466. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  7467. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  7468. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  7469. **
  7470. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  7471. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  7472. ** will cause HeapValidate to be called. If heap validation should fail, an
  7473. ** assertion will be triggered.
  7474. **
  7475. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  7476. ** the default.
  7477. */
  7478. #if defined(SQLITE_SYSTEM_MALLOC) \
  7479. + defined(SQLITE_WIN32_MALLOC) \
  7480. + defined(SQLITE_ZERO_MALLOC) \
  7481. + defined(SQLITE_MEMDEBUG)>1
  7482. # error "Two or more of the following compile-time configuration options\
  7483. are defined but at most one is allowed:\
  7484. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  7485. SQLITE_ZERO_MALLOC"
  7486. #endif
  7487. #if defined(SQLITE_SYSTEM_MALLOC) \
  7488. + defined(SQLITE_WIN32_MALLOC) \
  7489. + defined(SQLITE_ZERO_MALLOC) \
  7490. + defined(SQLITE_MEMDEBUG)==0
  7491. # define SQLITE_SYSTEM_MALLOC 1
  7492. #endif
  7493. /*
  7494. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  7495. ** sizes of memory allocations below this value where possible.
  7496. */
  7497. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  7498. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  7499. #endif
  7500. /*
  7501. ** We need to define _XOPEN_SOURCE as follows in order to enable
  7502. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  7503. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  7504. ** it.
  7505. */
  7506. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  7507. # define _XOPEN_SOURCE 600
  7508. #endif
  7509. /*
  7510. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  7511. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  7512. ** make it true by defining or undefining NDEBUG.
  7513. **
  7514. ** Setting NDEBUG makes the code smaller and faster by disabling the
  7515. ** assert() statements in the code. So we want the default action
  7516. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  7517. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  7518. ** feature.
  7519. */
  7520. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  7521. # define NDEBUG 1
  7522. #endif
  7523. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  7524. # undef NDEBUG
  7525. #endif
  7526. /*
  7527. ** The testcase() macro is used to aid in coverage testing. When
  7528. ** doing coverage testing, the condition inside the argument to
  7529. ** testcase() must be evaluated both true and false in order to
  7530. ** get full branch coverage. The testcase() macro is inserted
  7531. ** to help ensure adequate test coverage in places where simple
  7532. ** condition/decision coverage is inadequate. For example, testcase()
  7533. ** can be used to make sure boundary values are tested. For
  7534. ** bitmask tests, testcase() can be used to make sure each bit
  7535. ** is significant and used at least once. On switch statements
  7536. ** where multiple cases go to the same block of code, testcase()
  7537. ** can insure that all cases are evaluated.
  7538. **
  7539. */
  7540. #ifdef SQLITE_COVERAGE_TEST
  7541. SQLITE_PRIVATE void sqlite3Coverage(int);
  7542. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  7543. #else
  7544. # define testcase(X)
  7545. #endif
  7546. /*
  7547. ** The TESTONLY macro is used to enclose variable declarations or
  7548. ** other bits of code that are needed to support the arguments
  7549. ** within testcase() and assert() macros.
  7550. */
  7551. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  7552. # define TESTONLY(X) X
  7553. #else
  7554. # define TESTONLY(X)
  7555. #endif
  7556. /*
  7557. ** Sometimes we need a small amount of code such as a variable initialization
  7558. ** to setup for a later assert() statement. We do not want this code to
  7559. ** appear when assert() is disabled. The following macro is therefore
  7560. ** used to contain that setup code. The "VVA" acronym stands for
  7561. ** "Verification, Validation, and Accreditation". In other words, the
  7562. ** code within VVA_ONLY() will only run during verification processes.
  7563. */
  7564. #ifndef NDEBUG
  7565. # define VVA_ONLY(X) X
  7566. #else
  7567. # define VVA_ONLY(X)
  7568. #endif
  7569. /*
  7570. ** The ALWAYS and NEVER macros surround boolean expressions which
  7571. ** are intended to always be true or false, respectively. Such
  7572. ** expressions could be omitted from the code completely. But they
  7573. ** are included in a few cases in order to enhance the resilience
  7574. ** of SQLite to unexpected behavior - to make the code "self-healing"
  7575. ** or "ductile" rather than being "brittle" and crashing at the first
  7576. ** hint of unplanned behavior.
  7577. **
  7578. ** In other words, ALWAYS and NEVER are added for defensive code.
  7579. **
  7580. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  7581. ** be true and false so that the unreachable code they specify will
  7582. ** not be counted as untested code.
  7583. */
  7584. #if defined(SQLITE_COVERAGE_TEST)
  7585. # define ALWAYS(X) (1)
  7586. # define NEVER(X) (0)
  7587. #elif !defined(NDEBUG)
  7588. # define ALWAYS(X) ((X)?1:(assert(0),0))
  7589. # define NEVER(X) ((X)?(assert(0),1):0)
  7590. #else
  7591. # define ALWAYS(X) (X)
  7592. # define NEVER(X) (X)
  7593. #endif
  7594. /*
  7595. ** Return true (non-zero) if the input is a integer that is too large
  7596. ** to fit in 32-bits. This macro is used inside of various testcase()
  7597. ** macros to verify that we have tested SQLite for large-file support.
  7598. */
  7599. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  7600. /*
  7601. ** The macro unlikely() is a hint that surrounds a boolean
  7602. ** expression that is usually false. Macro likely() surrounds
  7603. ** a boolean expression that is usually true. These hints could,
  7604. ** in theory, be used by the compiler to generate better code, but
  7605. ** currently they are just comments for human readers.
  7606. */
  7607. #define likely(X) (X)
  7608. #define unlikely(X) (X)
  7609. /************** Include hash.h in the middle of sqliteInt.h ******************/
  7610. /************** Begin file hash.h ********************************************/
  7611. /*
  7612. ** 2001 September 22
  7613. **
  7614. ** The author disclaims copyright to this source code. In place of
  7615. ** a legal notice, here is a blessing:
  7616. **
  7617. ** May you do good and not evil.
  7618. ** May you find forgiveness for yourself and forgive others.
  7619. ** May you share freely, never taking more than you give.
  7620. **
  7621. *************************************************************************
  7622. ** This is the header file for the generic hash-table implementation
  7623. ** used in SQLite.
  7624. */
  7625. #ifndef _SQLITE_HASH_H_
  7626. #define _SQLITE_HASH_H_
  7627. /* Forward declarations of structures. */
  7628. typedef struct Hash Hash;
  7629. typedef struct HashElem HashElem;
  7630. /* A complete hash table is an instance of the following structure.
  7631. ** The internals of this structure are intended to be opaque -- client
  7632. ** code should not attempt to access or modify the fields of this structure
  7633. ** directly. Change this structure only by using the routines below.
  7634. ** However, some of the "procedures" and "functions" for modifying and
  7635. ** accessing this structure are really macros, so we can't really make
  7636. ** this structure opaque.
  7637. **
  7638. ** All elements of the hash table are on a single doubly-linked list.
  7639. ** Hash.first points to the head of this list.
  7640. **
  7641. ** There are Hash.htsize buckets. Each bucket points to a spot in
  7642. ** the global doubly-linked list. The contents of the bucket are the
  7643. ** element pointed to plus the next _ht.count-1 elements in the list.
  7644. **
  7645. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  7646. ** by a linear search of the global list. For small tables, the
  7647. ** Hash.ht table is never allocated because if there are few elements
  7648. ** in the table, it is faster to do a linear search than to manage
  7649. ** the hash table.
  7650. */
  7651. struct Hash {
  7652. unsigned int htsize; /* Number of buckets in the hash table */
  7653. unsigned int count; /* Number of entries in this table */
  7654. HashElem *first; /* The first element of the array */
  7655. struct _ht { /* the hash table */
  7656. int count; /* Number of entries with this hash */
  7657. HashElem *chain; /* Pointer to first entry with this hash */
  7658. } *ht;
  7659. };
  7660. /* Each element in the hash table is an instance of the following
  7661. ** structure. All elements are stored on a single doubly-linked list.
  7662. **
  7663. ** Again, this structure is intended to be opaque, but it can't really
  7664. ** be opaque because it is used by macros.
  7665. */
  7666. struct HashElem {
  7667. HashElem *next, *prev; /* Next and previous elements in the table */
  7668. void *data; /* Data associated with this element */
  7669. const char *pKey; int nKey; /* Key associated with this element */
  7670. };
  7671. /*
  7672. ** Access routines. To delete, insert a NULL pointer.
  7673. */
  7674. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  7675. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
  7676. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
  7677. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  7678. /*
  7679. ** Macros for looping over all elements of a hash table. The idiom is
  7680. ** like this:
  7681. **
  7682. ** Hash h;
  7683. ** HashElem *p;
  7684. ** ...
  7685. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  7686. ** SomeStructure *pData = sqliteHashData(p);
  7687. ** // do something with pData
  7688. ** }
  7689. */
  7690. #define sqliteHashFirst(H) ((H)->first)
  7691. #define sqliteHashNext(E) ((E)->next)
  7692. #define sqliteHashData(E) ((E)->data)
  7693. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  7694. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  7695. /*
  7696. ** Number of entries in a hash table
  7697. */
  7698. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  7699. #endif /* _SQLITE_HASH_H_ */
  7700. /************** End of hash.h ************************************************/
  7701. /************** Continuing where we left off in sqliteInt.h ******************/
  7702. /************** Include parse.h in the middle of sqliteInt.h *****************/
  7703. /************** Begin file parse.h *******************************************/
  7704. #define TK_SEMI 1
  7705. #define TK_EXPLAIN 2
  7706. #define TK_QUERY 3
  7707. #define TK_PLAN 4
  7708. #define TK_BEGIN 5
  7709. #define TK_TRANSACTION 6
  7710. #define TK_DEFERRED 7
  7711. #define TK_IMMEDIATE 8
  7712. #define TK_EXCLUSIVE 9
  7713. #define TK_COMMIT 10
  7714. #define TK_END 11
  7715. #define TK_ROLLBACK 12
  7716. #define TK_SAVEPOINT 13
  7717. #define TK_RELEASE 14
  7718. #define TK_TO 15
  7719. #define TK_TABLE 16
  7720. #define TK_CREATE 17
  7721. #define TK_IF 18
  7722. #define TK_NOT 19
  7723. #define TK_EXISTS 20
  7724. #define TK_TEMP 21
  7725. #define TK_LP 22
  7726. #define TK_RP 23
  7727. #define TK_AS 24
  7728. #define TK_COMMA 25
  7729. #define TK_ID 26
  7730. #define TK_INDEXED 27
  7731. #define TK_ABORT 28
  7732. #define TK_ACTION 29
  7733. #define TK_AFTER 30
  7734. #define TK_ANALYZE 31
  7735. #define TK_ASC 32
  7736. #define TK_ATTACH 33
  7737. #define TK_BEFORE 34
  7738. #define TK_BY 35
  7739. #define TK_CASCADE 36
  7740. #define TK_CAST 37
  7741. #define TK_COLUMNKW 38
  7742. #define TK_CONFLICT 39
  7743. #define TK_DATABASE 40
  7744. #define TK_DESC 41
  7745. #define TK_DETACH 42
  7746. #define TK_EACH 43
  7747. #define TK_FAIL 44
  7748. #define TK_FOR 45
  7749. #define TK_IGNORE 46
  7750. #define TK_INITIALLY 47
  7751. #define TK_INSTEAD 48
  7752. #define TK_LIKE_KW 49
  7753. #define TK_MATCH 50
  7754. #define TK_NO 51
  7755. #define TK_KEY 52
  7756. #define TK_OF 53
  7757. #define TK_OFFSET 54
  7758. #define TK_PRAGMA 55
  7759. #define TK_RAISE 56
  7760. #define TK_REPLACE 57
  7761. #define TK_RESTRICT 58
  7762. #define TK_ROW 59
  7763. #define TK_TRIGGER 60
  7764. #define TK_VACUUM 61
  7765. #define TK_VIEW 62
  7766. #define TK_VIRTUAL 63
  7767. #define TK_REINDEX 64
  7768. #define TK_RENAME 65
  7769. #define TK_CTIME_KW 66
  7770. #define TK_ANY 67
  7771. #define TK_OR 68
  7772. #define TK_AND 69
  7773. #define TK_IS 70
  7774. #define TK_BETWEEN 71
  7775. #define TK_IN 72
  7776. #define TK_ISNULL 73
  7777. #define TK_NOTNULL 74
  7778. #define TK_NE 75
  7779. #define TK_EQ 76
  7780. #define TK_GT 77
  7781. #define TK_LE 78
  7782. #define TK_LT 79
  7783. #define TK_GE 80
  7784. #define TK_ESCAPE 81
  7785. #define TK_BITAND 82
  7786. #define TK_BITOR 83
  7787. #define TK_LSHIFT 84
  7788. #define TK_RSHIFT 85
  7789. #define TK_PLUS 86
  7790. #define TK_MINUS 87
  7791. #define TK_STAR 88
  7792. #define TK_SLASH 89
  7793. #define TK_REM 90
  7794. #define TK_CONCAT 91
  7795. #define TK_COLLATE 92
  7796. #define TK_BITNOT 93
  7797. #define TK_STRING 94
  7798. #define TK_JOIN_KW 95
  7799. #define TK_CONSTRAINT 96
  7800. #define TK_DEFAULT 97
  7801. #define TK_NULL 98
  7802. #define TK_PRIMARY 99
  7803. #define TK_UNIQUE 100
  7804. #define TK_CHECK 101
  7805. #define TK_REFERENCES 102
  7806. #define TK_AUTOINCR 103
  7807. #define TK_ON 104
  7808. #define TK_INSERT 105
  7809. #define TK_DELETE 106
  7810. #define TK_UPDATE 107
  7811. #define TK_SET 108
  7812. #define TK_DEFERRABLE 109
  7813. #define TK_FOREIGN 110
  7814. #define TK_DROP 111
  7815. #define TK_UNION 112
  7816. #define TK_ALL 113
  7817. #define TK_EXCEPT 114
  7818. #define TK_INTERSECT 115
  7819. #define TK_SELECT 116
  7820. #define TK_DISTINCT 117
  7821. #define TK_DOT 118
  7822. #define TK_FROM 119
  7823. #define TK_JOIN 120
  7824. #define TK_USING 121
  7825. #define TK_ORDER 122
  7826. #define TK_GROUP 123
  7827. #define TK_HAVING 124
  7828. #define TK_LIMIT 125
  7829. #define TK_WHERE 126
  7830. #define TK_INTO 127
  7831. #define TK_VALUES 128
  7832. #define TK_INTEGER 129
  7833. #define TK_FLOAT 130
  7834. #define TK_BLOB 131
  7835. #define TK_REGISTER 132
  7836. #define TK_VARIABLE 133
  7837. #define TK_CASE 134
  7838. #define TK_WHEN 135
  7839. #define TK_THEN 136
  7840. #define TK_ELSE 137
  7841. #define TK_INDEX 138
  7842. #define TK_ALTER 139
  7843. #define TK_ADD 140
  7844. #define TK_TO_TEXT 141
  7845. #define TK_TO_BLOB 142
  7846. #define TK_TO_NUMERIC 143
  7847. #define TK_TO_INT 144
  7848. #define TK_TO_REAL 145
  7849. #define TK_ISNOT 146
  7850. #define TK_END_OF_FILE 147
  7851. #define TK_ILLEGAL 148
  7852. #define TK_SPACE 149
  7853. #define TK_UNCLOSED_STRING 150
  7854. #define TK_FUNCTION 151
  7855. #define TK_COLUMN 152
  7856. #define TK_AGG_FUNCTION 153
  7857. #define TK_AGG_COLUMN 154
  7858. #define TK_CONST_FUNC 155
  7859. #define TK_UMINUS 156
  7860. #define TK_UPLUS 157
  7861. /************** End of parse.h ***********************************************/
  7862. /************** Continuing where we left off in sqliteInt.h ******************/
  7863. #include <stdio.h>
  7864. #include <stdlib.h>
  7865. #include <string.h>
  7866. #include <assert.h>
  7867. #include <stddef.h>
  7868. /*
  7869. ** If compiling for a processor that lacks floating point support,
  7870. ** substitute integer for floating-point
  7871. */
  7872. #ifdef SQLITE_OMIT_FLOATING_POINT
  7873. # define double sqlite_int64
  7874. # define float sqlite_int64
  7875. # define LONGDOUBLE_TYPE sqlite_int64
  7876. # ifndef SQLITE_BIG_DBL
  7877. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  7878. # endif
  7879. # define SQLITE_OMIT_DATETIME_FUNCS 1
  7880. # define SQLITE_OMIT_TRACE 1
  7881. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  7882. # undef SQLITE_HAVE_ISNAN
  7883. #endif
  7884. #ifndef SQLITE_BIG_DBL
  7885. # define SQLITE_BIG_DBL (1e99)
  7886. #endif
  7887. /*
  7888. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  7889. ** afterward. Having this macro allows us to cause the C compiler
  7890. ** to omit code used by TEMP tables without messy #ifndef statements.
  7891. */
  7892. #ifdef SQLITE_OMIT_TEMPDB
  7893. #define OMIT_TEMPDB 1
  7894. #else
  7895. #define OMIT_TEMPDB 0
  7896. #endif
  7897. /*
  7898. ** The "file format" number is an integer that is incremented whenever
  7899. ** the VDBE-level file format changes. The following macros define the
  7900. ** the default file format for new databases and the maximum file format
  7901. ** that the library can read.
  7902. */
  7903. #define SQLITE_MAX_FILE_FORMAT 4
  7904. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  7905. # define SQLITE_DEFAULT_FILE_FORMAT 4
  7906. #endif
  7907. /*
  7908. ** Determine whether triggers are recursive by default. This can be
  7909. ** changed at run-time using a pragma.
  7910. */
  7911. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  7912. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  7913. #endif
  7914. /*
  7915. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  7916. ** on the command-line
  7917. */
  7918. #ifndef SQLITE_TEMP_STORE
  7919. # define SQLITE_TEMP_STORE 1
  7920. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  7921. #endif
  7922. /*
  7923. ** GCC does not define the offsetof() macro so we'll have to do it
  7924. ** ourselves.
  7925. */
  7926. #ifndef offsetof
  7927. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  7928. #endif
  7929. /*
  7930. ** Macros to compute minimum and maximum of two numbers.
  7931. */
  7932. #define MIN(A,B) ((A)<(B)?(A):(B))
  7933. #define MAX(A,B) ((A)>(B)?(A):(B))
  7934. /*
  7935. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  7936. ** not, there are still machines out there that use EBCDIC.)
  7937. */
  7938. #if 'A' == '\301'
  7939. # define SQLITE_EBCDIC 1
  7940. #else
  7941. # define SQLITE_ASCII 1
  7942. #endif
  7943. /*
  7944. ** Integers of known sizes. These typedefs might change for architectures
  7945. ** where the sizes very. Preprocessor macros are available so that the
  7946. ** types can be conveniently redefined at compile-type. Like this:
  7947. **
  7948. ** cc '-DUINTPTR_TYPE=long long int' ...
  7949. */
  7950. #ifndef UINT32_TYPE
  7951. # ifdef HAVE_UINT32_T
  7952. # define UINT32_TYPE uint32_t
  7953. # else
  7954. # define UINT32_TYPE unsigned int
  7955. # endif
  7956. #endif
  7957. #ifndef UINT16_TYPE
  7958. # ifdef HAVE_UINT16_T
  7959. # define UINT16_TYPE uint16_t
  7960. # else
  7961. # define UINT16_TYPE unsigned short int
  7962. # endif
  7963. #endif
  7964. #ifndef INT16_TYPE
  7965. # ifdef HAVE_INT16_T
  7966. # define INT16_TYPE int16_t
  7967. # else
  7968. # define INT16_TYPE short int
  7969. # endif
  7970. #endif
  7971. #ifndef UINT8_TYPE
  7972. # ifdef HAVE_UINT8_T
  7973. # define UINT8_TYPE uint8_t
  7974. # else
  7975. # define UINT8_TYPE unsigned char
  7976. # endif
  7977. #endif
  7978. #ifndef INT8_TYPE
  7979. # ifdef HAVE_INT8_T
  7980. # define INT8_TYPE int8_t
  7981. # else
  7982. # define INT8_TYPE signed char
  7983. # endif
  7984. #endif
  7985. #ifndef LONGDOUBLE_TYPE
  7986. # define LONGDOUBLE_TYPE long double
  7987. #endif
  7988. typedef sqlite_int64 i64; /* 8-byte signed integer */
  7989. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  7990. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  7991. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  7992. typedef INT16_TYPE i16; /* 2-byte signed integer */
  7993. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  7994. typedef INT8_TYPE i8; /* 1-byte signed integer */
  7995. /*
  7996. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  7997. ** that can be stored in a u32 without loss of data. The value
  7998. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  7999. ** have to specify the value in the less intuitive manner shown:
  8000. */
  8001. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  8002. /*
  8003. ** The datatype used to store estimates of the number of rows in a
  8004. ** table or index. This is an unsigned integer type. For 99.9% of
  8005. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  8006. ** can be used at compile-time if desired.
  8007. */
  8008. #ifdef SQLITE_64BIT_STATS
  8009. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  8010. #else
  8011. typedef u32 tRowcnt; /* 32-bit is the default */
  8012. #endif
  8013. /*
  8014. ** Estimated quantities used for query planning are stored as 16-bit
  8015. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  8016. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  8017. ** But the allowed values are "grainy". Not every value is representable.
  8018. ** For example, quantities 16 and 17 are both represented by a LogEst
  8019. ** of 40. However, since LogEst quantatites are suppose to be estimates,
  8020. ** not exact values, this imprecision is not a problem.
  8021. **
  8022. ** "LogEst" is short for "Logarithimic Estimate".
  8023. **
  8024. ** Examples:
  8025. ** 1 -> 0 20 -> 43 10000 -> 132
  8026. ** 2 -> 10 25 -> 46 25000 -> 146
  8027. ** 3 -> 16 100 -> 66 1000000 -> 199
  8028. ** 4 -> 20 1000 -> 99 1048576 -> 200
  8029. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  8030. **
  8031. ** The LogEst can be negative to indicate fractional values.
  8032. ** Examples:
  8033. **
  8034. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  8035. */
  8036. typedef INT16_TYPE LogEst;
  8037. /*
  8038. ** Macros to determine whether the machine is big or little endian,
  8039. ** evaluated at runtime.
  8040. */
  8041. #ifdef SQLITE_AMALGAMATION
  8042. SQLITE_PRIVATE const int sqlite3one = 1;
  8043. #else
  8044. SQLITE_PRIVATE const int sqlite3one;
  8045. #endif
  8046. #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  8047. || defined(__x86_64) || defined(__x86_64__)
  8048. # define SQLITE_BIGENDIAN 0
  8049. # define SQLITE_LITTLEENDIAN 1
  8050. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  8051. #else
  8052. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  8053. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  8054. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  8055. #endif
  8056. /*
  8057. ** Constants for the largest and smallest possible 64-bit signed integers.
  8058. ** These macros are designed to work correctly on both 32-bit and 64-bit
  8059. ** compilers.
  8060. */
  8061. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  8062. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  8063. /*
  8064. ** Round up a number to the next larger multiple of 8. This is used
  8065. ** to force 8-byte alignment on 64-bit architectures.
  8066. */
  8067. #define ROUND8(x) (((x)+7)&~7)
  8068. /*
  8069. ** Round down to the nearest multiple of 8
  8070. */
  8071. #define ROUNDDOWN8(x) ((x)&~7)
  8072. /*
  8073. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  8074. ** macro is used only within assert() to verify that the code gets
  8075. ** all alignment restrictions correct.
  8076. **
  8077. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  8078. ** underlying malloc() implemention might return us 4-byte aligned
  8079. ** pointers. In that case, only verify 4-byte alignment.
  8080. */
  8081. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  8082. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  8083. #else
  8084. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  8085. #endif
  8086. /*
  8087. ** Disable MMAP on platforms where it is known to not work
  8088. */
  8089. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  8090. # undef SQLITE_MAX_MMAP_SIZE
  8091. # define SQLITE_MAX_MMAP_SIZE 0
  8092. #endif
  8093. /*
  8094. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  8095. */
  8096. #ifdef __APPLE__
  8097. # include <TargetConditionals.h>
  8098. # if TARGET_OS_IPHONE
  8099. # undef SQLITE_MAX_MMAP_SIZE
  8100. # define SQLITE_MAX_MMAP_SIZE 0
  8101. # endif
  8102. #endif
  8103. #ifndef SQLITE_MAX_MMAP_SIZE
  8104. # if defined(__linux__) \
  8105. || defined(_WIN32) \
  8106. || (defined(__APPLE__) && defined(__MACH__)) \
  8107. || defined(__sun)
  8108. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  8109. # else
  8110. # define SQLITE_MAX_MMAP_SIZE 0
  8111. # endif
  8112. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  8113. #endif
  8114. /*
  8115. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  8116. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  8117. ** not exceed the maximum mmap size.
  8118. */
  8119. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  8120. # define SQLITE_DEFAULT_MMAP_SIZE 0
  8121. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  8122. #endif
  8123. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  8124. # undef SQLITE_DEFAULT_MMAP_SIZE
  8125. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  8126. #endif
  8127. /*
  8128. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  8129. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  8130. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  8131. */
  8132. #ifdef SQLITE_ENABLE_STAT4
  8133. # undef SQLITE_ENABLE_STAT3
  8134. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8135. #elif SQLITE_ENABLE_STAT3
  8136. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8137. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  8138. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  8139. #endif
  8140. /*
  8141. ** An instance of the following structure is used to store the busy-handler
  8142. ** callback for a given sqlite handle.
  8143. **
  8144. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  8145. ** callback for the database handle. Each pager opened via the sqlite
  8146. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  8147. ** callback is currently invoked only from within pager.c.
  8148. */
  8149. typedef struct BusyHandler BusyHandler;
  8150. struct BusyHandler {
  8151. int (*xFunc)(void *,int); /* The busy callback */
  8152. void *pArg; /* First arg to busy callback */
  8153. int nBusy; /* Incremented with each busy call */
  8154. };
  8155. /*
  8156. ** Name of the master database table. The master database table
  8157. ** is a special table that holds the names and attributes of all
  8158. ** user tables and indices.
  8159. */
  8160. #define MASTER_NAME "sqlite_master"
  8161. #define TEMP_MASTER_NAME "sqlite_temp_master"
  8162. /*
  8163. ** The root-page of the master database table.
  8164. */
  8165. #define MASTER_ROOT 1
  8166. /*
  8167. ** The name of the schema table.
  8168. */
  8169. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  8170. /*
  8171. ** A convenience macro that returns the number of elements in
  8172. ** an array.
  8173. */
  8174. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  8175. /*
  8176. ** Determine if the argument is a power of two
  8177. */
  8178. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  8179. /*
  8180. ** The following value as a destructor means to use sqlite3DbFree().
  8181. ** The sqlite3DbFree() routine requires two parameters instead of the
  8182. ** one parameter that destructors normally want. So we have to introduce
  8183. ** this magic value that the code knows to handle differently. Any
  8184. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  8185. ** and SQLITE_TRANSIENT.
  8186. */
  8187. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  8188. /*
  8189. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  8190. ** not support Writable Static Data (WSD) such as global and static variables.
  8191. ** All variables must either be on the stack or dynamically allocated from
  8192. ** the heap. When WSD is unsupported, the variable declarations scattered
  8193. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  8194. ** macro is used for this purpose. And instead of referencing the variable
  8195. ** directly, we use its constant as a key to lookup the run-time allocated
  8196. ** buffer that holds real variable. The constant is also the initializer
  8197. ** for the run-time allocated buffer.
  8198. **
  8199. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  8200. ** macros become no-ops and have zero performance impact.
  8201. */
  8202. #ifdef SQLITE_OMIT_WSD
  8203. #define SQLITE_WSD const
  8204. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  8205. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  8206. SQLITE_API int sqlite3_wsd_init(int N, int J);
  8207. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  8208. #else
  8209. #define SQLITE_WSD
  8210. #define GLOBAL(t,v) v
  8211. #define sqlite3GlobalConfig sqlite3Config
  8212. #endif
  8213. /*
  8214. ** The following macros are used to suppress compiler warnings and to
  8215. ** make it clear to human readers when a function parameter is deliberately
  8216. ** left unused within the body of a function. This usually happens when
  8217. ** a function is called via a function pointer. For example the
  8218. ** implementation of an SQL aggregate step callback may not use the
  8219. ** parameter indicating the number of arguments passed to the aggregate,
  8220. ** if it knows that this is enforced elsewhere.
  8221. **
  8222. ** When a function parameter is not used at all within the body of a function,
  8223. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  8224. ** However, these macros may also be used to suppress warnings related to
  8225. ** parameters that may or may not be used depending on compilation options.
  8226. ** For example those parameters only used in assert() statements. In these
  8227. ** cases the parameters are named as per the usual conventions.
  8228. */
  8229. #define UNUSED_PARAMETER(x) (void)(x)
  8230. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  8231. /*
  8232. ** Forward references to structures
  8233. */
  8234. typedef struct AggInfo AggInfo;
  8235. typedef struct AuthContext AuthContext;
  8236. typedef struct AutoincInfo AutoincInfo;
  8237. typedef struct Bitvec Bitvec;
  8238. typedef struct CollSeq CollSeq;
  8239. typedef struct Column Column;
  8240. typedef struct Db Db;
  8241. typedef struct Schema Schema;
  8242. typedef struct Expr Expr;
  8243. typedef struct ExprList ExprList;
  8244. typedef struct ExprSpan ExprSpan;
  8245. typedef struct FKey FKey;
  8246. typedef struct FuncDestructor FuncDestructor;
  8247. typedef struct FuncDef FuncDef;
  8248. typedef struct FuncDefHash FuncDefHash;
  8249. typedef struct IdList IdList;
  8250. typedef struct Index Index;
  8251. typedef struct IndexSample IndexSample;
  8252. typedef struct KeyClass KeyClass;
  8253. typedef struct KeyInfo KeyInfo;
  8254. typedef struct Lookaside Lookaside;
  8255. typedef struct LookasideSlot LookasideSlot;
  8256. typedef struct Module Module;
  8257. typedef struct NameContext NameContext;
  8258. typedef struct Parse Parse;
  8259. typedef struct RowSet RowSet;
  8260. typedef struct Savepoint Savepoint;
  8261. typedef struct Select Select;
  8262. typedef struct SelectDest SelectDest;
  8263. typedef struct SrcList SrcList;
  8264. typedef struct StrAccum StrAccum;
  8265. typedef struct Table Table;
  8266. typedef struct TableLock TableLock;
  8267. typedef struct Token Token;
  8268. typedef struct Trigger Trigger;
  8269. typedef struct TriggerPrg TriggerPrg;
  8270. typedef struct TriggerStep TriggerStep;
  8271. typedef struct UnpackedRecord UnpackedRecord;
  8272. typedef struct VTable VTable;
  8273. typedef struct VtabCtx VtabCtx;
  8274. typedef struct Walker Walker;
  8275. typedef struct WhereInfo WhereInfo;
  8276. /*
  8277. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  8278. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  8279. ** pointer types (i.e. FuncDef) defined above.
  8280. */
  8281. /************** Include btree.h in the middle of sqliteInt.h *****************/
  8282. /************** Begin file btree.h *******************************************/
  8283. /*
  8284. ** 2001 September 15
  8285. **
  8286. ** The author disclaims copyright to this source code. In place of
  8287. ** a legal notice, here is a blessing:
  8288. **
  8289. ** May you do good and not evil.
  8290. ** May you find forgiveness for yourself and forgive others.
  8291. ** May you share freely, never taking more than you give.
  8292. **
  8293. *************************************************************************
  8294. ** This header file defines the interface that the sqlite B-Tree file
  8295. ** subsystem. See comments in the source code for a detailed description
  8296. ** of what each interface routine does.
  8297. */
  8298. #ifndef _BTREE_H_
  8299. #define _BTREE_H_
  8300. /* TODO: This definition is just included so other modules compile. It
  8301. ** needs to be revisited.
  8302. */
  8303. #define SQLITE_N_BTREE_META 10
  8304. /*
  8305. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  8306. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  8307. */
  8308. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  8309. #define SQLITE_DEFAULT_AUTOVACUUM 0
  8310. #endif
  8311. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  8312. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  8313. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  8314. /*
  8315. ** Forward declarations of structure
  8316. */
  8317. typedef struct Btree Btree;
  8318. typedef struct BtCursor BtCursor;
  8319. typedef struct BtShared BtShared;
  8320. SQLITE_PRIVATE int sqlite3BtreeOpen(
  8321. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  8322. const char *zFilename, /* Name of database file to open */
  8323. sqlite3 *db, /* Associated database connection */
  8324. Btree **ppBtree, /* Return open Btree* here */
  8325. int flags, /* Flags */
  8326. int vfsFlags /* Flags passed through to VFS open */
  8327. );
  8328. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  8329. ** following values.
  8330. **
  8331. ** NOTE: These values must match the corresponding PAGER_ values in
  8332. ** pager.h.
  8333. */
  8334. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  8335. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  8336. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  8337. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  8338. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  8339. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  8340. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  8341. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  8342. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  8343. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  8344. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  8345. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  8346. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  8347. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  8348. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  8349. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  8350. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  8351. #endif
  8352. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  8353. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  8354. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  8355. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  8356. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  8357. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  8358. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
  8359. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  8360. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  8361. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  8362. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  8363. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  8364. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  8365. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  8366. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  8367. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  8368. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  8369. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  8370. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  8371. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  8372. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  8373. ** of the flags shown below.
  8374. **
  8375. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  8376. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  8377. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  8378. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  8379. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  8380. ** indices.)
  8381. */
  8382. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  8383. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  8384. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  8385. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  8386. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  8387. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  8388. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  8389. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  8390. /*
  8391. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  8392. ** should be one of the following values. The integer values are assigned
  8393. ** to constants so that the offset of the corresponding field in an
  8394. ** SQLite database header may be found using the following formula:
  8395. **
  8396. ** offset = 36 + (idx * 4)
  8397. **
  8398. ** For example, the free-page-count field is located at byte offset 36 of
  8399. ** the database file header. The incr-vacuum-flag field is located at
  8400. ** byte offset 64 (== 36+4*7).
  8401. */
  8402. #define BTREE_FREE_PAGE_COUNT 0
  8403. #define BTREE_SCHEMA_VERSION 1
  8404. #define BTREE_FILE_FORMAT 2
  8405. #define BTREE_DEFAULT_CACHE_SIZE 3
  8406. #define BTREE_LARGEST_ROOT_PAGE 4
  8407. #define BTREE_TEXT_ENCODING 5
  8408. #define BTREE_USER_VERSION 6
  8409. #define BTREE_INCR_VACUUM 7
  8410. #define BTREE_APPLICATION_ID 8
  8411. /*
  8412. ** Values that may be OR'd together to form the second argument of an
  8413. ** sqlite3BtreeCursorHints() call.
  8414. */
  8415. #define BTREE_BULKLOAD 0x00000001
  8416. SQLITE_PRIVATE int sqlite3BtreeCursor(
  8417. Btree*, /* BTree containing table to open */
  8418. int iTable, /* Index of root page */
  8419. int wrFlag, /* 1 for writing. 0 for read-only */
  8420. struct KeyInfo*, /* First argument to compare function */
  8421. BtCursor *pCursor /* Space to write cursor structure */
  8422. );
  8423. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  8424. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  8425. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  8426. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  8427. BtCursor*,
  8428. UnpackedRecord *pUnKey,
  8429. i64 intKey,
  8430. int bias,
  8431. int *pRes
  8432. );
  8433. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
  8434. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  8435. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  8436. const void *pData, int nData,
  8437. int nZero, int bias, int seekResult);
  8438. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  8439. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  8440. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  8441. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  8442. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  8443. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  8444. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  8445. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
  8446. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
  8447. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  8448. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  8449. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
  8450. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
  8451. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  8452. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  8453. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  8454. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
  8455. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  8456. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  8457. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  8458. #ifndef NDEBUG
  8459. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  8460. #endif
  8461. #ifndef SQLITE_OMIT_BTREECOUNT
  8462. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  8463. #endif
  8464. #ifdef SQLITE_TEST
  8465. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  8466. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  8467. #endif
  8468. #ifndef SQLITE_OMIT_WAL
  8469. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  8470. #endif
  8471. /*
  8472. ** If we are not using shared cache, then there is no need to
  8473. ** use mutexes to access the BtShared structures. So make the
  8474. ** Enter and Leave procedures no-ops.
  8475. */
  8476. #ifndef SQLITE_OMIT_SHARED_CACHE
  8477. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  8478. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  8479. #else
  8480. # define sqlite3BtreeEnter(X)
  8481. # define sqlite3BtreeEnterAll(X)
  8482. #endif
  8483. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  8484. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  8485. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  8486. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  8487. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  8488. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  8489. #ifndef NDEBUG
  8490. /* These routines are used inside assert() statements only. */
  8491. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  8492. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  8493. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  8494. #endif
  8495. #else
  8496. # define sqlite3BtreeSharable(X) 0
  8497. # define sqlite3BtreeLeave(X)
  8498. # define sqlite3BtreeEnterCursor(X)
  8499. # define sqlite3BtreeLeaveCursor(X)
  8500. # define sqlite3BtreeLeaveAll(X)
  8501. # define sqlite3BtreeHoldsMutex(X) 1
  8502. # define sqlite3BtreeHoldsAllMutexes(X) 1
  8503. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  8504. #endif
  8505. #endif /* _BTREE_H_ */
  8506. /************** End of btree.h ***********************************************/
  8507. /************** Continuing where we left off in sqliteInt.h ******************/
  8508. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  8509. /************** Begin file vdbe.h ********************************************/
  8510. /*
  8511. ** 2001 September 15
  8512. **
  8513. ** The author disclaims copyright to this source code. In place of
  8514. ** a legal notice, here is a blessing:
  8515. **
  8516. ** May you do good and not evil.
  8517. ** May you find forgiveness for yourself and forgive others.
  8518. ** May you share freely, never taking more than you give.
  8519. **
  8520. *************************************************************************
  8521. ** Header file for the Virtual DataBase Engine (VDBE)
  8522. **
  8523. ** This header defines the interface to the virtual database engine
  8524. ** or VDBE. The VDBE implements an abstract machine that runs a
  8525. ** simple program to access and modify the underlying database.
  8526. */
  8527. #ifndef _SQLITE_VDBE_H_
  8528. #define _SQLITE_VDBE_H_
  8529. /* #include <stdio.h> */
  8530. /*
  8531. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  8532. ** in the source file sqliteVdbe.c are allowed to see the insides
  8533. ** of this structure.
  8534. */
  8535. typedef struct Vdbe Vdbe;
  8536. /*
  8537. ** The names of the following types declared in vdbeInt.h are required
  8538. ** for the VdbeOp definition.
  8539. */
  8540. typedef struct Mem Mem;
  8541. typedef struct SubProgram SubProgram;
  8542. /*
  8543. ** A single instruction of the virtual machine has an opcode
  8544. ** and as many as three operands. The instruction is recorded
  8545. ** as an instance of the following structure:
  8546. */
  8547. struct VdbeOp {
  8548. u8 opcode; /* What operation to perform */
  8549. signed char p4type; /* One of the P4_xxx constants for p4 */
  8550. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  8551. u8 p5; /* Fifth parameter is an unsigned character */
  8552. int p1; /* First operand */
  8553. int p2; /* Second parameter (often the jump destination) */
  8554. int p3; /* The third parameter */
  8555. union { /* fourth parameter */
  8556. int i; /* Integer value if p4type==P4_INT32 */
  8557. void *p; /* Generic pointer */
  8558. char *z; /* Pointer to data for string (char array) types */
  8559. i64 *pI64; /* Used when p4type is P4_INT64 */
  8560. double *pReal; /* Used when p4type is P4_REAL */
  8561. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  8562. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  8563. Mem *pMem; /* Used when p4type is P4_MEM */
  8564. VTable *pVtab; /* Used when p4type is P4_VTAB */
  8565. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  8566. int *ai; /* Used when p4type is P4_INTARRAY */
  8567. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  8568. int (*xAdvance)(BtCursor *, int *);
  8569. } p4;
  8570. #ifdef SQLITE_DEBUG
  8571. char *zComment; /* Comment to improve readability */
  8572. #endif
  8573. #ifdef VDBE_PROFILE
  8574. int cnt; /* Number of times this instruction was executed */
  8575. u64 cycles; /* Total time spent executing this instruction */
  8576. #endif
  8577. };
  8578. typedef struct VdbeOp VdbeOp;
  8579. /*
  8580. ** A sub-routine used to implement a trigger program.
  8581. */
  8582. struct SubProgram {
  8583. VdbeOp *aOp; /* Array of opcodes for sub-program */
  8584. int nOp; /* Elements in aOp[] */
  8585. int nMem; /* Number of memory cells required */
  8586. int nCsr; /* Number of cursors required */
  8587. int nOnce; /* Number of OP_Once instructions */
  8588. void *token; /* id that may be used to recursive triggers */
  8589. SubProgram *pNext; /* Next sub-program already visited */
  8590. };
  8591. /*
  8592. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  8593. ** it takes up less space.
  8594. */
  8595. struct VdbeOpList {
  8596. u8 opcode; /* What operation to perform */
  8597. signed char p1; /* First operand */
  8598. signed char p2; /* Second parameter (often the jump destination) */
  8599. signed char p3; /* Third parameter */
  8600. };
  8601. typedef struct VdbeOpList VdbeOpList;
  8602. /*
  8603. ** Allowed values of VdbeOp.p4type
  8604. */
  8605. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  8606. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  8607. #define P4_STATIC (-2) /* Pointer to a static string */
  8608. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  8609. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  8610. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  8611. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  8612. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  8613. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  8614. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  8615. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  8616. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  8617. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  8618. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  8619. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  8620. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  8621. /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
  8622. ** is made. That copy is freed when the Vdbe is finalized. But if the
  8623. ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
  8624. ** gets freed when the Vdbe is finalized so it still should be obtained
  8625. ** from a single sqliteMalloc(). But no copy is made and the calling
  8626. ** function should *not* try to free the KeyInfo.
  8627. */
  8628. #define P4_KEYINFO_HANDOFF (-16)
  8629. #define P4_KEYINFO_STATIC (-17)
  8630. /*
  8631. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  8632. ** number of columns of data returned by the statement.
  8633. */
  8634. #define COLNAME_NAME 0
  8635. #define COLNAME_DECLTYPE 1
  8636. #define COLNAME_DATABASE 2
  8637. #define COLNAME_TABLE 3
  8638. #define COLNAME_COLUMN 4
  8639. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  8640. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  8641. #else
  8642. # ifdef SQLITE_OMIT_DECLTYPE
  8643. # define COLNAME_N 1 /* Store only the name */
  8644. # else
  8645. # define COLNAME_N 2 /* Store the name and decltype */
  8646. # endif
  8647. #endif
  8648. /*
  8649. ** The following macro converts a relative address in the p2 field
  8650. ** of a VdbeOp structure into a negative number so that
  8651. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  8652. ** the macro again restores the address.
  8653. */
  8654. #define ADDR(X) (-1-(X))
  8655. /*
  8656. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  8657. ** header file that defines a number for each opcode used by the VDBE.
  8658. */
  8659. /************** Include opcodes.h in the middle of vdbe.h ********************/
  8660. /************** Begin file opcodes.h *****************************************/
  8661. /* Automatically generated. Do not edit */
  8662. /* See the mkopcodeh.awk script for details */
  8663. #define OP_Function 1
  8664. #define OP_Savepoint 2
  8665. #define OP_AutoCommit 3
  8666. #define OP_Transaction 4
  8667. #define OP_SorterNext 5
  8668. #define OP_Prev 6
  8669. #define OP_Next 7
  8670. #define OP_AggStep 8
  8671. #define OP_Checkpoint 9
  8672. #define OP_JournalMode 10
  8673. #define OP_Vacuum 11
  8674. #define OP_VFilter 12
  8675. #define OP_VUpdate 13
  8676. #define OP_Goto 14
  8677. #define OP_Gosub 15
  8678. #define OP_Return 16
  8679. #define OP_Yield 17
  8680. #define OP_HaltIfNull 18
  8681. #define OP_Not 19 /* same as TK_NOT */
  8682. #define OP_Halt 20
  8683. #define OP_Integer 21
  8684. #define OP_Int64 22
  8685. #define OP_String 23
  8686. #define OP_Null 24
  8687. #define OP_Blob 25
  8688. #define OP_Variable 26
  8689. #define OP_Move 27
  8690. #define OP_Copy 28
  8691. #define OP_SCopy 29
  8692. #define OP_ResultRow 30
  8693. #define OP_CollSeq 31
  8694. #define OP_AddImm 32
  8695. #define OP_MustBeInt 33
  8696. #define OP_RealAffinity 34
  8697. #define OP_Permutation 35
  8698. #define OP_Compare 36
  8699. #define OP_Jump 37
  8700. #define OP_Once 38
  8701. #define OP_If 39
  8702. #define OP_IfNot 40
  8703. #define OP_Column 41
  8704. #define OP_Affinity 42
  8705. #define OP_MakeRecord 43
  8706. #define OP_Count 44
  8707. #define OP_ReadCookie 45
  8708. #define OP_SetCookie 46
  8709. #define OP_VerifyCookie 47
  8710. #define OP_OpenRead 48
  8711. #define OP_OpenWrite 49
  8712. #define OP_OpenAutoindex 50
  8713. #define OP_OpenEphemeral 51
  8714. #define OP_SorterOpen 52
  8715. #define OP_OpenPseudo 53
  8716. #define OP_Close 54
  8717. #define OP_SeekLt 55
  8718. #define OP_SeekLe 56
  8719. #define OP_SeekGe 57
  8720. #define OP_SeekGt 58
  8721. #define OP_Seek 59
  8722. #define OP_NotFound 60
  8723. #define OP_Found 61
  8724. #define OP_IsUnique 62
  8725. #define OP_NotExists 63
  8726. #define OP_Sequence 64
  8727. #define OP_NewRowid 65
  8728. #define OP_Insert 66
  8729. #define OP_InsertInt 67
  8730. #define OP_Or 68 /* same as TK_OR */
  8731. #define OP_And 69 /* same as TK_AND */
  8732. #define OP_Delete 70
  8733. #define OP_ResetCount 71
  8734. #define OP_SorterCompare 72
  8735. #define OP_IsNull 73 /* same as TK_ISNULL */
  8736. #define OP_NotNull 74 /* same as TK_NOTNULL */
  8737. #define OP_Ne 75 /* same as TK_NE */
  8738. #define OP_Eq 76 /* same as TK_EQ */
  8739. #define OP_Gt 77 /* same as TK_GT */
  8740. #define OP_Le 78 /* same as TK_LE */
  8741. #define OP_Lt 79 /* same as TK_LT */
  8742. #define OP_Ge 80 /* same as TK_GE */
  8743. #define OP_SorterData 81
  8744. #define OP_BitAnd 82 /* same as TK_BITAND */
  8745. #define OP_BitOr 83 /* same as TK_BITOR */
  8746. #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
  8747. #define OP_ShiftRight 85 /* same as TK_RSHIFT */
  8748. #define OP_Add 86 /* same as TK_PLUS */
  8749. #define OP_Subtract 87 /* same as TK_MINUS */
  8750. #define OP_Multiply 88 /* same as TK_STAR */
  8751. #define OP_Divide 89 /* same as TK_SLASH */
  8752. #define OP_Remainder 90 /* same as TK_REM */
  8753. #define OP_Concat 91 /* same as TK_CONCAT */
  8754. #define OP_RowKey 92
  8755. #define OP_BitNot 93 /* same as TK_BITNOT */
  8756. #define OP_String8 94 /* same as TK_STRING */
  8757. #define OP_RowData 95
  8758. #define OP_Rowid 96
  8759. #define OP_NullRow 97
  8760. #define OP_Last 98
  8761. #define OP_SorterSort 99
  8762. #define OP_Sort 100
  8763. #define OP_Rewind 101
  8764. #define OP_SorterInsert 102
  8765. #define OP_IdxInsert 103
  8766. #define OP_IdxDelete 104
  8767. #define OP_IdxRowid 105
  8768. #define OP_IdxLT 106
  8769. #define OP_IdxGE 107
  8770. #define OP_Destroy 108
  8771. #define OP_Clear 109
  8772. #define OP_CreateIndex 110
  8773. #define OP_CreateTable 111
  8774. #define OP_ParseSchema 112
  8775. #define OP_LoadAnalysis 113
  8776. #define OP_DropTable 114
  8777. #define OP_DropIndex 115
  8778. #define OP_DropTrigger 116
  8779. #define OP_IntegrityCk 117
  8780. #define OP_RowSetAdd 118
  8781. #define OP_RowSetRead 119
  8782. #define OP_RowSetTest 120
  8783. #define OP_Program 121
  8784. #define OP_Param 122
  8785. #define OP_FkCounter 123
  8786. #define OP_FkIfZero 124
  8787. #define OP_MemMax 125
  8788. #define OP_IfPos 126
  8789. #define OP_IfNeg 127
  8790. #define OP_IfZero 128
  8791. #define OP_AggFinal 129
  8792. #define OP_Real 130 /* same as TK_FLOAT */
  8793. #define OP_IncrVacuum 131
  8794. #define OP_Expire 132
  8795. #define OP_TableLock 133
  8796. #define OP_VBegin 134
  8797. #define OP_VCreate 135
  8798. #define OP_VDestroy 136
  8799. #define OP_VOpen 137
  8800. #define OP_VColumn 138
  8801. #define OP_VNext 139
  8802. #define OP_VRename 140
  8803. #define OP_ToText 141 /* same as TK_TO_TEXT */
  8804. #define OP_ToBlob 142 /* same as TK_TO_BLOB */
  8805. #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
  8806. #define OP_ToInt 144 /* same as TK_TO_INT */
  8807. #define OP_ToReal 145 /* same as TK_TO_REAL */
  8808. #define OP_Pagecount 146
  8809. #define OP_MaxPgcnt 147
  8810. #define OP_Trace 148
  8811. #define OP_Noop 149
  8812. #define OP_Explain 150
  8813. /* Properties such as "out2" or "jump" that are specified in
  8814. ** comments following the "case" for each opcode in the vdbe.c
  8815. ** are encoded into bitvectors as follows:
  8816. */
  8817. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  8818. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  8819. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  8820. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  8821. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  8822. #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
  8823. #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
  8824. #define OPFLG_INITIALIZER {\
  8825. /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
  8826. /* 8 */ 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x01, 0x01,\
  8827. /* 16 */ 0x04, 0x04, 0x10, 0x24, 0x00, 0x02, 0x02, 0x02,\
  8828. /* 24 */ 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x00, 0x00,\
  8829. /* 32 */ 0x04, 0x05, 0x04, 0x00, 0x00, 0x01, 0x01, 0x05,\
  8830. /* 40 */ 0x05, 0x00, 0x00, 0x00, 0x02, 0x02, 0x10, 0x00,\
  8831. /* 48 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,\
  8832. /* 56 */ 0x11, 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11,\
  8833. /* 64 */ 0x02, 0x02, 0x00, 0x00, 0x4c, 0x4c, 0x00, 0x00,\
  8834. /* 72 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
  8835. /* 80 */ 0x15, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
  8836. /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x00, 0x24, 0x02, 0x00,\
  8837. /* 96 */ 0x02, 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08,\
  8838. /* 104 */ 0x00, 0x02, 0x01, 0x01, 0x02, 0x00, 0x02, 0x02,\
  8839. /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x45,\
  8840. /* 120 */ 0x15, 0x01, 0x02, 0x00, 0x01, 0x08, 0x05, 0x05,\
  8841. /* 128 */ 0x05, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00,\
  8842. /* 136 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x04, 0x04,\
  8843. /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
  8844. /************** End of opcodes.h *********************************************/
  8845. /************** Continuing where we left off in vdbe.h ***********************/
  8846. /*
  8847. ** Prototypes for the VDBE interface. See comments on the implementation
  8848. ** for a description of what each of these routines does.
  8849. */
  8850. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
  8851. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  8852. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  8853. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  8854. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  8855. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  8856. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  8857. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
  8858. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  8859. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  8860. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  8861. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  8862. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  8863. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  8864. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  8865. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  8866. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  8867. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  8868. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  8869. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  8870. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  8871. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  8872. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  8873. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  8874. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  8875. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  8876. #ifdef SQLITE_DEBUG
  8877. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  8878. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
  8879. #endif
  8880. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  8881. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  8882. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  8883. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  8884. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  8885. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  8886. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  8887. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  8888. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  8889. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  8890. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  8891. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  8892. #ifndef SQLITE_OMIT_TRACE
  8893. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  8894. #endif
  8895. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  8896. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  8897. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  8898. #ifndef SQLITE_OMIT_TRIGGER
  8899. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  8900. #endif
  8901. #ifndef NDEBUG
  8902. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  8903. # define VdbeComment(X) sqlite3VdbeComment X
  8904. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  8905. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  8906. #else
  8907. # define VdbeComment(X)
  8908. # define VdbeNoopComment(X)
  8909. #endif
  8910. #endif
  8911. /************** End of vdbe.h ************************************************/
  8912. /************** Continuing where we left off in sqliteInt.h ******************/
  8913. /************** Include pager.h in the middle of sqliteInt.h *****************/
  8914. /************** Begin file pager.h *******************************************/
  8915. /*
  8916. ** 2001 September 15
  8917. **
  8918. ** The author disclaims copyright to this source code. In place of
  8919. ** a legal notice, here is a blessing:
  8920. **
  8921. ** May you do good and not evil.
  8922. ** May you find forgiveness for yourself and forgive others.
  8923. ** May you share freely, never taking more than you give.
  8924. **
  8925. *************************************************************************
  8926. ** This header file defines the interface that the sqlite page cache
  8927. ** subsystem. The page cache subsystem reads and writes a file a page
  8928. ** at a time and provides a journal for rollback.
  8929. */
  8930. #ifndef _PAGER_H_
  8931. #define _PAGER_H_
  8932. /*
  8933. ** Default maximum size for persistent journal files. A negative
  8934. ** value means no limit. This value may be overridden using the
  8935. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  8936. */
  8937. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  8938. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  8939. #endif
  8940. /*
  8941. ** The type used to represent a page number. The first page in a file
  8942. ** is called page 1. 0 is used to represent "not a page".
  8943. */
  8944. typedef u32 Pgno;
  8945. /*
  8946. ** Each open file is managed by a separate instance of the "Pager" structure.
  8947. */
  8948. typedef struct Pager Pager;
  8949. /*
  8950. ** Handle type for pages.
  8951. */
  8952. typedef struct PgHdr DbPage;
  8953. /*
  8954. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  8955. ** reserved for working around a windows/posix incompatibility). It is
  8956. ** used in the journal to signify that the remainder of the journal file
  8957. ** is devoted to storing a master journal name - there are no more pages to
  8958. ** roll back. See comments for function writeMasterJournal() in pager.c
  8959. ** for details.
  8960. */
  8961. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  8962. /*
  8963. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  8964. **
  8965. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  8966. */
  8967. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  8968. #define PAGER_MEMORY 0x0002 /* In-memory database */
  8969. /*
  8970. ** Valid values for the second argument to sqlite3PagerLockingMode().
  8971. */
  8972. #define PAGER_LOCKINGMODE_QUERY -1
  8973. #define PAGER_LOCKINGMODE_NORMAL 0
  8974. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  8975. /*
  8976. ** Numeric constants that encode the journalmode.
  8977. */
  8978. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  8979. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  8980. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  8981. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  8982. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  8983. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  8984. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  8985. /*
  8986. ** Flags that make up the mask passed to sqlite3PagerAcquire().
  8987. */
  8988. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  8989. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  8990. /*
  8991. ** Flags for sqlite3PagerSetFlags()
  8992. */
  8993. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  8994. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  8995. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  8996. #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
  8997. #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
  8998. #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
  8999. #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
  9000. #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
  9001. /*
  9002. ** The remainder of this file contains the declarations of the functions
  9003. ** that make up the Pager sub-system API. See source code comments for
  9004. ** a detailed description of each routine.
  9005. */
  9006. /* Open and close a Pager connection. */
  9007. SQLITE_PRIVATE int sqlite3PagerOpen(
  9008. sqlite3_vfs*,
  9009. Pager **ppPager,
  9010. const char*,
  9011. int,
  9012. int,
  9013. int,
  9014. void(*)(DbPage*)
  9015. );
  9016. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  9017. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  9018. /* Functions used to configure a Pager object. */
  9019. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  9020. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  9021. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  9022. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  9023. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  9024. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  9025. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  9026. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  9027. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  9028. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  9029. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  9030. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  9031. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  9032. /* Functions used to obtain and release page references. */
  9033. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  9034. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  9035. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  9036. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  9037. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  9038. /* Operations on page references. */
  9039. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  9040. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  9041. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  9042. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  9043. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  9044. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  9045. /* Functions used to manage pager transactions and savepoints. */
  9046. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  9047. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  9048. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  9049. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  9050. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
  9051. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  9052. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  9053. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  9054. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  9055. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  9056. #ifndef SQLITE_OMIT_WAL
  9057. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  9058. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  9059. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  9060. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  9061. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  9062. #endif
  9063. #ifdef SQLITE_ENABLE_ZIPVFS
  9064. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  9065. #endif
  9066. /* Functions used to query pager state and configuration. */
  9067. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  9068. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  9069. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  9070. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  9071. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  9072. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  9073. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  9074. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  9075. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  9076. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  9077. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  9078. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  9079. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  9080. /* Functions used to truncate the database file. */
  9081. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  9082. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  9083. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  9084. #endif
  9085. /* Functions to support testing and debugging. */
  9086. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  9087. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  9088. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  9089. #endif
  9090. #ifdef SQLITE_TEST
  9091. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  9092. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  9093. void disable_simulated_io_errors(void);
  9094. void enable_simulated_io_errors(void);
  9095. #else
  9096. # define disable_simulated_io_errors()
  9097. # define enable_simulated_io_errors()
  9098. #endif
  9099. #endif /* _PAGER_H_ */
  9100. /************** End of pager.h ***********************************************/
  9101. /************** Continuing where we left off in sqliteInt.h ******************/
  9102. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  9103. /************** Begin file pcache.h ******************************************/
  9104. /*
  9105. ** 2008 August 05
  9106. **
  9107. ** The author disclaims copyright to this source code. In place of
  9108. ** a legal notice, here is a blessing:
  9109. **
  9110. ** May you do good and not evil.
  9111. ** May you find forgiveness for yourself and forgive others.
  9112. ** May you share freely, never taking more than you give.
  9113. **
  9114. *************************************************************************
  9115. ** This header file defines the interface that the sqlite page cache
  9116. ** subsystem.
  9117. */
  9118. #ifndef _PCACHE_H_
  9119. typedef struct PgHdr PgHdr;
  9120. typedef struct PCache PCache;
  9121. /*
  9122. ** Every page in the cache is controlled by an instance of the following
  9123. ** structure.
  9124. */
  9125. struct PgHdr {
  9126. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  9127. void *pData; /* Page data */
  9128. void *pExtra; /* Extra content */
  9129. PgHdr *pDirty; /* Transient list of dirty pages */
  9130. Pager *pPager; /* The pager this page is part of */
  9131. Pgno pgno; /* Page number for this page */
  9132. #ifdef SQLITE_CHECK_PAGES
  9133. u32 pageHash; /* Hash of page content */
  9134. #endif
  9135. u16 flags; /* PGHDR flags defined below */
  9136. /**********************************************************************
  9137. ** Elements above are public. All that follows is private to pcache.c
  9138. ** and should not be accessed by other modules.
  9139. */
  9140. i16 nRef; /* Number of users of this page */
  9141. PCache *pCache; /* Cache that owns this page */
  9142. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  9143. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  9144. };
  9145. /* Bit values for PgHdr.flags */
  9146. #define PGHDR_DIRTY 0x002 /* Page has changed */
  9147. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  9148. ** writing this page to the database */
  9149. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  9150. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  9151. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  9152. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  9153. /* Initialize and shutdown the page cache subsystem */
  9154. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  9155. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  9156. /* Page cache buffer management:
  9157. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  9158. */
  9159. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  9160. /* Create a new pager cache.
  9161. ** Under memory stress, invoke xStress to try to make pages clean.
  9162. ** Only clean and unpinned pages can be reclaimed.
  9163. */
  9164. SQLITE_PRIVATE void sqlite3PcacheOpen(
  9165. int szPage, /* Size of every page */
  9166. int szExtra, /* Extra space associated with each page */
  9167. int bPurgeable, /* True if pages are on backing store */
  9168. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  9169. void *pStress, /* Argument to xStress */
  9170. PCache *pToInit /* Preallocated space for the PCache */
  9171. );
  9172. /* Modify the page-size after the cache has been created. */
  9173. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
  9174. /* Return the size in bytes of a PCache object. Used to preallocate
  9175. ** storage space.
  9176. */
  9177. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  9178. /* One release per successful fetch. Page is pinned until released.
  9179. ** Reference counted.
  9180. */
  9181. SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
  9182. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  9183. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  9184. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  9185. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  9186. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  9187. /* Change a page number. Used by incr-vacuum. */
  9188. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  9189. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  9190. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  9191. /* Get a list of all dirty pages in the cache, sorted by page number */
  9192. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  9193. /* Reset and close the cache object */
  9194. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  9195. /* Clear flags from pages of the page cache */
  9196. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  9197. /* Discard the contents of the cache */
  9198. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  9199. /* Return the total number of outstanding page references */
  9200. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  9201. /* Increment the reference count of an existing page */
  9202. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  9203. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  9204. /* Return the total number of pages stored in the cache */
  9205. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  9206. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  9207. /* Iterate through all dirty pages currently stored in the cache. This
  9208. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  9209. ** library is built.
  9210. */
  9211. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  9212. #endif
  9213. /* Set and get the suggested cache-size for the specified pager-cache.
  9214. **
  9215. ** If no global maximum is configured, then the system attempts to limit
  9216. ** the total number of pages cached by purgeable pager-caches to the sum
  9217. ** of the suggested cache-sizes.
  9218. */
  9219. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  9220. #ifdef SQLITE_TEST
  9221. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  9222. #endif
  9223. /* Free up as much memory as possible from the page cache */
  9224. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  9225. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  9226. /* Try to return memory used by the pcache module to the main memory heap */
  9227. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  9228. #endif
  9229. #ifdef SQLITE_TEST
  9230. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  9231. #endif
  9232. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  9233. #endif /* _PCACHE_H_ */
  9234. /************** End of pcache.h **********************************************/
  9235. /************** Continuing where we left off in sqliteInt.h ******************/
  9236. /************** Include os.h in the middle of sqliteInt.h ********************/
  9237. /************** Begin file os.h **********************************************/
  9238. /*
  9239. ** 2001 September 16
  9240. **
  9241. ** The author disclaims copyright to this source code. In place of
  9242. ** a legal notice, here is a blessing:
  9243. **
  9244. ** May you do good and not evil.
  9245. ** May you find forgiveness for yourself and forgive others.
  9246. ** May you share freely, never taking more than you give.
  9247. **
  9248. ******************************************************************************
  9249. **
  9250. ** This header file (together with is companion C source-code file
  9251. ** "os.c") attempt to abstract the underlying operating system so that
  9252. ** the SQLite library will work on both POSIX and windows systems.
  9253. **
  9254. ** This header file is #include-ed by sqliteInt.h and thus ends up
  9255. ** being included by every source file.
  9256. */
  9257. #ifndef _SQLITE_OS_H_
  9258. #define _SQLITE_OS_H_
  9259. /*
  9260. ** Figure out if we are dealing with Unix, Windows, or some other
  9261. ** operating system. After the following block of preprocess macros,
  9262. ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER
  9263. ** will defined to either 1 or 0. One of the four will be 1. The other
  9264. ** three will be 0.
  9265. */
  9266. #if defined(SQLITE_OS_OTHER)
  9267. # if SQLITE_OS_OTHER==1
  9268. # undef SQLITE_OS_UNIX
  9269. # define SQLITE_OS_UNIX 0
  9270. # undef SQLITE_OS_WIN
  9271. # define SQLITE_OS_WIN 0
  9272. # else
  9273. # undef SQLITE_OS_OTHER
  9274. # endif
  9275. #endif
  9276. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  9277. # define SQLITE_OS_OTHER 0
  9278. # ifndef SQLITE_OS_WIN
  9279. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  9280. # define SQLITE_OS_WIN 1
  9281. # define SQLITE_OS_UNIX 0
  9282. # else
  9283. # define SQLITE_OS_WIN 0
  9284. # define SQLITE_OS_UNIX 1
  9285. # endif
  9286. # else
  9287. # define SQLITE_OS_UNIX 0
  9288. # endif
  9289. #else
  9290. # ifndef SQLITE_OS_WIN
  9291. # define SQLITE_OS_WIN 0
  9292. # endif
  9293. #endif
  9294. #if SQLITE_OS_WIN
  9295. # include <windows.h>
  9296. #endif
  9297. /*
  9298. ** Determine if we are dealing with Windows NT.
  9299. **
  9300. ** We ought to be able to determine if we are compiling for win98 or winNT
  9301. ** using the _WIN32_WINNT macro as follows:
  9302. **
  9303. ** #if defined(_WIN32_WINNT)
  9304. ** # define SQLITE_OS_WINNT 1
  9305. ** #else
  9306. ** # define SQLITE_OS_WINNT 0
  9307. ** #endif
  9308. **
  9309. ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
  9310. ** so the above test does not work. We'll just assume that everything is
  9311. ** winNT unless the programmer explicitly says otherwise by setting
  9312. ** SQLITE_OS_WINNT to 0.
  9313. */
  9314. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  9315. # define SQLITE_OS_WINNT 1
  9316. #endif
  9317. /*
  9318. ** Determine if we are dealing with WindowsCE - which has a much
  9319. ** reduced API.
  9320. */
  9321. #if defined(_WIN32_WCE)
  9322. # define SQLITE_OS_WINCE 1
  9323. #else
  9324. # define SQLITE_OS_WINCE 0
  9325. #endif
  9326. /*
  9327. ** Determine if we are dealing with WinRT, which provides only a subset of
  9328. ** the full Win32 API.
  9329. */
  9330. #if !defined(SQLITE_OS_WINRT)
  9331. # define SQLITE_OS_WINRT 0
  9332. #endif
  9333. /* If the SET_FULLSYNC macro is not defined above, then make it
  9334. ** a no-op
  9335. */
  9336. #ifndef SET_FULLSYNC
  9337. # define SET_FULLSYNC(x,y)
  9338. #endif
  9339. /*
  9340. ** The default size of a disk sector
  9341. */
  9342. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  9343. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  9344. #endif
  9345. /*
  9346. ** Temporary files are named starting with this prefix followed by 16 random
  9347. ** alphanumeric characters, and no file extension. They are stored in the
  9348. ** OS's standard temporary file directory, and are deleted prior to exit.
  9349. ** If sqlite is being embedded in another program, you may wish to change the
  9350. ** prefix to reflect your program's name, so that if your program exits
  9351. ** prematurely, old temporary files can be easily identified. This can be done
  9352. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  9353. **
  9354. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  9355. ** Mcafee started using SQLite in their anti-virus product and it
  9356. ** started putting files with the "sqlite" name in the c:/temp folder.
  9357. ** This annoyed many windows users. Those users would then do a
  9358. ** Google search for "sqlite", find the telephone numbers of the
  9359. ** developers and call to wake them up at night and complain.
  9360. ** For this reason, the default name prefix is changed to be "sqlite"
  9361. ** spelled backwards. So the temp files are still identified, but
  9362. ** anybody smart enough to figure out the code is also likely smart
  9363. ** enough to know that calling the developer will not help get rid
  9364. ** of the file.
  9365. */
  9366. #ifndef SQLITE_TEMP_FILE_PREFIX
  9367. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  9368. #endif
  9369. /*
  9370. ** The following values may be passed as the second argument to
  9371. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  9372. **
  9373. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  9374. ** RESERVED: A single process may hold a RESERVED lock on a file at
  9375. ** any time. Other processes may hold and obtain new SHARED locks.
  9376. ** PENDING: A single process may hold a PENDING lock on a file at
  9377. ** any one time. Existing SHARED locks may persist, but no new
  9378. ** SHARED locks may be obtained by other processes.
  9379. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  9380. **
  9381. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  9382. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  9383. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  9384. ** sqlite3OsLock().
  9385. */
  9386. #define NO_LOCK 0
  9387. #define SHARED_LOCK 1
  9388. #define RESERVED_LOCK 2
  9389. #define PENDING_LOCK 3
  9390. #define EXCLUSIVE_LOCK 4
  9391. /*
  9392. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  9393. **
  9394. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  9395. ** those functions are not available. So we use only LockFile() and
  9396. ** UnlockFile().
  9397. **
  9398. ** LockFile() prevents not just writing but also reading by other processes.
  9399. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  9400. ** byte out of a specific range of bytes. The lock byte is obtained at
  9401. ** random so two separate readers can probably access the file at the
  9402. ** same time, unless they are unlucky and choose the same lock byte.
  9403. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  9404. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  9405. ** a single byte of the file that is designated as the reserved lock byte.
  9406. ** A PENDING_LOCK is obtained by locking a designated byte different from
  9407. ** the RESERVED_LOCK byte.
  9408. **
  9409. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  9410. ** which means we can use reader/writer locks. When reader/writer locks
  9411. ** are used, the lock is placed on the same range of bytes that is used
  9412. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  9413. ** will support two or more Win95 readers or two or more WinNT readers.
  9414. ** But a single Win95 reader will lock out all WinNT readers and a single
  9415. ** WinNT reader will lock out all other Win95 readers.
  9416. **
  9417. ** The following #defines specify the range of bytes used for locking.
  9418. ** SHARED_SIZE is the number of bytes available in the pool from which
  9419. ** a random byte is selected for a shared lock. The pool of bytes for
  9420. ** shared locks begins at SHARED_FIRST.
  9421. **
  9422. ** The same locking strategy and
  9423. ** byte ranges are used for Unix. This leaves open the possiblity of having
  9424. ** clients on win95, winNT, and unix all talking to the same shared file
  9425. ** and all locking correctly. To do so would require that samba (or whatever
  9426. ** tool is being used for file sharing) implements locks correctly between
  9427. ** windows and unix. I'm guessing that isn't likely to happen, but by
  9428. ** using the same locking range we are at least open to the possibility.
  9429. **
  9430. ** Locking in windows is manditory. For this reason, we cannot store
  9431. ** actual data in the bytes used for locking. The pager never allocates
  9432. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  9433. ** that all locks will fit on a single page even at the minimum page size.
  9434. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  9435. ** is set high so that we don't have to allocate an unused page except
  9436. ** for very large databases. But one should test the page skipping logic
  9437. ** by setting PENDING_BYTE low and running the entire regression suite.
  9438. **
  9439. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  9440. ** file format. Depending on how it is changed, you might not notice
  9441. ** the incompatibility right away, even running a full regression test.
  9442. ** The default location of PENDING_BYTE is the first byte past the
  9443. ** 1GB boundary.
  9444. **
  9445. */
  9446. #ifdef SQLITE_OMIT_WSD
  9447. # define PENDING_BYTE (0x40000000)
  9448. #else
  9449. # define PENDING_BYTE sqlite3PendingByte
  9450. #endif
  9451. #define RESERVED_BYTE (PENDING_BYTE+1)
  9452. #define SHARED_FIRST (PENDING_BYTE+2)
  9453. #define SHARED_SIZE 510
  9454. /*
  9455. ** Wrapper around OS specific sqlite3_os_init() function.
  9456. */
  9457. SQLITE_PRIVATE int sqlite3OsInit(void);
  9458. /*
  9459. ** Functions for accessing sqlite3_file methods
  9460. */
  9461. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  9462. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  9463. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  9464. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  9465. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  9466. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  9467. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  9468. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  9469. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  9470. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  9471. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  9472. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  9473. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  9474. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  9475. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  9476. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  9477. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  9478. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  9479. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  9480. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  9481. /*
  9482. ** Functions for accessing sqlite3_vfs methods
  9483. */
  9484. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  9485. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  9486. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  9487. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  9488. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  9489. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  9490. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  9491. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  9492. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  9493. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  9494. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  9495. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  9496. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  9497. /*
  9498. ** Convenience functions for opening and closing files using
  9499. ** sqlite3_malloc() to obtain space for the file-handle structure.
  9500. */
  9501. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  9502. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  9503. #endif /* _SQLITE_OS_H_ */
  9504. /************** End of os.h **************************************************/
  9505. /************** Continuing where we left off in sqliteInt.h ******************/
  9506. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  9507. /************** Begin file mutex.h *******************************************/
  9508. /*
  9509. ** 2007 August 28
  9510. **
  9511. ** The author disclaims copyright to this source code. In place of
  9512. ** a legal notice, here is a blessing:
  9513. **
  9514. ** May you do good and not evil.
  9515. ** May you find forgiveness for yourself and forgive others.
  9516. ** May you share freely, never taking more than you give.
  9517. **
  9518. *************************************************************************
  9519. **
  9520. ** This file contains the common header for all mutex implementations.
  9521. ** The sqliteInt.h header #includes this file so that it is available
  9522. ** to all source files. We break it out in an effort to keep the code
  9523. ** better organized.
  9524. **
  9525. ** NOTE: source files should *not* #include this header file directly.
  9526. ** Source files should #include the sqliteInt.h file and let that file
  9527. ** include this one indirectly.
  9528. */
  9529. /*
  9530. ** Figure out what version of the code to use. The choices are
  9531. **
  9532. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  9533. ** mutexes implemention cannot be overridden
  9534. ** at start-time.
  9535. **
  9536. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  9537. ** mutual exclusion is provided. But this
  9538. ** implementation can be overridden at
  9539. ** start-time.
  9540. **
  9541. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  9542. **
  9543. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  9544. */
  9545. #if !SQLITE_THREADSAFE
  9546. # define SQLITE_MUTEX_OMIT
  9547. #endif
  9548. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  9549. # if SQLITE_OS_UNIX
  9550. # define SQLITE_MUTEX_PTHREADS
  9551. # elif SQLITE_OS_WIN
  9552. # define SQLITE_MUTEX_W32
  9553. # else
  9554. # define SQLITE_MUTEX_NOOP
  9555. # endif
  9556. #endif
  9557. #ifdef SQLITE_MUTEX_OMIT
  9558. /*
  9559. ** If this is a no-op implementation, implement everything as macros.
  9560. */
  9561. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  9562. #define sqlite3_mutex_free(X)
  9563. #define sqlite3_mutex_enter(X)
  9564. #define sqlite3_mutex_try(X) SQLITE_OK
  9565. #define sqlite3_mutex_leave(X)
  9566. #define sqlite3_mutex_held(X) ((void)(X),1)
  9567. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  9568. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  9569. #define sqlite3MutexInit() SQLITE_OK
  9570. #define sqlite3MutexEnd()
  9571. #define MUTEX_LOGIC(X)
  9572. #else
  9573. #define MUTEX_LOGIC(X) X
  9574. #endif /* defined(SQLITE_MUTEX_OMIT) */
  9575. /************** End of mutex.h ***********************************************/
  9576. /************** Continuing where we left off in sqliteInt.h ******************/
  9577. /*
  9578. ** Each database file to be accessed by the system is an instance
  9579. ** of the following structure. There are normally two of these structures
  9580. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  9581. ** aDb[1] is the database file used to hold temporary tables. Additional
  9582. ** databases may be attached.
  9583. */
  9584. struct Db {
  9585. char *zName; /* Name of this database */
  9586. Btree *pBt; /* The B*Tree structure for this database file */
  9587. u8 safety_level; /* How aggressive at syncing data to disk */
  9588. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  9589. };
  9590. /*
  9591. ** An instance of the following structure stores a database schema.
  9592. **
  9593. ** Most Schema objects are associated with a Btree. The exception is
  9594. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  9595. ** In shared cache mode, a single Schema object can be shared by multiple
  9596. ** Btrees that refer to the same underlying BtShared object.
  9597. **
  9598. ** Schema objects are automatically deallocated when the last Btree that
  9599. ** references them is destroyed. The TEMP Schema is manually freed by
  9600. ** sqlite3_close().
  9601. *
  9602. ** A thread must be holding a mutex on the corresponding Btree in order
  9603. ** to access Schema content. This implies that the thread must also be
  9604. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  9605. ** For a TEMP Schema, only the connection mutex is required.
  9606. */
  9607. struct Schema {
  9608. int schema_cookie; /* Database schema version number for this file */
  9609. int iGeneration; /* Generation counter. Incremented with each change */
  9610. Hash tblHash; /* All tables indexed by name */
  9611. Hash idxHash; /* All (named) indices indexed by name */
  9612. Hash trigHash; /* All triggers indexed by name */
  9613. Hash fkeyHash; /* All foreign keys by referenced table name */
  9614. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  9615. u8 file_format; /* Schema format version for this file */
  9616. u8 enc; /* Text encoding used by this database */
  9617. u16 flags; /* Flags associated with this schema */
  9618. int cache_size; /* Number of pages to use in the cache */
  9619. };
  9620. /*
  9621. ** These macros can be used to test, set, or clear bits in the
  9622. ** Db.pSchema->flags field.
  9623. */
  9624. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
  9625. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
  9626. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
  9627. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
  9628. /*
  9629. ** Allowed values for the DB.pSchema->flags field.
  9630. **
  9631. ** The DB_SchemaLoaded flag is set after the database schema has been
  9632. ** read into internal hash tables.
  9633. **
  9634. ** DB_UnresetViews means that one or more views have column names that
  9635. ** have been filled out. If the schema changes, these column names might
  9636. ** changes and so the view will need to be reset.
  9637. */
  9638. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  9639. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  9640. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  9641. /*
  9642. ** The number of different kinds of things that can be limited
  9643. ** using the sqlite3_limit() interface.
  9644. */
  9645. #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
  9646. /*
  9647. ** Lookaside malloc is a set of fixed-size buffers that can be used
  9648. ** to satisfy small transient memory allocation requests for objects
  9649. ** associated with a particular database connection. The use of
  9650. ** lookaside malloc provides a significant performance enhancement
  9651. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  9652. ** SQL statements.
  9653. **
  9654. ** The Lookaside structure holds configuration information about the
  9655. ** lookaside malloc subsystem. Each available memory allocation in
  9656. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  9657. ** objects.
  9658. **
  9659. ** Lookaside allocations are only allowed for objects that are associated
  9660. ** with a particular database connection. Hence, schema information cannot
  9661. ** be stored in lookaside because in shared cache mode the schema information
  9662. ** is shared by multiple database connections. Therefore, while parsing
  9663. ** schema information, the Lookaside.bEnabled flag is cleared so that
  9664. ** lookaside allocations are not used to construct the schema objects.
  9665. */
  9666. struct Lookaside {
  9667. u16 sz; /* Size of each buffer in bytes */
  9668. u8 bEnabled; /* False to disable new lookaside allocations */
  9669. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  9670. int nOut; /* Number of buffers currently checked out */
  9671. int mxOut; /* Highwater mark for nOut */
  9672. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  9673. LookasideSlot *pFree; /* List of available buffers */
  9674. void *pStart; /* First byte of available memory space */
  9675. void *pEnd; /* First byte past end of available space */
  9676. };
  9677. struct LookasideSlot {
  9678. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  9679. };
  9680. /*
  9681. ** A hash table for function definitions.
  9682. **
  9683. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  9684. ** Collisions are on the FuncDef.pHash chain.
  9685. */
  9686. struct FuncDefHash {
  9687. FuncDef *a[23]; /* Hash table for functions */
  9688. };
  9689. /*
  9690. ** Each database connection is an instance of the following structure.
  9691. */
  9692. struct sqlite3 {
  9693. sqlite3_vfs *pVfs; /* OS Interface */
  9694. struct Vdbe *pVdbe; /* List of active virtual machines */
  9695. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  9696. sqlite3_mutex *mutex; /* Connection mutex */
  9697. Db *aDb; /* All backends */
  9698. int nDb; /* Number of backends currently in use */
  9699. int flags; /* Miscellaneous flags. See below */
  9700. i64 lastRowid; /* ROWID of most recent insert (see above) */
  9701. i64 szMmap; /* Default mmap_size setting */
  9702. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  9703. int errCode; /* Most recent error code (SQLITE_*) */
  9704. int errMask; /* & result codes with this before returning */
  9705. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  9706. u8 autoCommit; /* The auto-commit flag. */
  9707. u8 temp_store; /* 1: file 2: memory 0: default */
  9708. u8 mallocFailed; /* True if we have seen a malloc failure */
  9709. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  9710. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  9711. u8 suppressErr; /* Do not issue error messages if true */
  9712. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  9713. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  9714. int nextPagesize; /* Pagesize after VACUUM if >0 */
  9715. u32 magic; /* Magic number for detect library misuse */
  9716. int nChange; /* Value returned by sqlite3_changes() */
  9717. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  9718. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  9719. struct sqlite3InitInfo { /* Information used during initialization */
  9720. int newTnum; /* Rootpage of table being initialized */
  9721. u8 iDb; /* Which db file is being initialized */
  9722. u8 busy; /* TRUE if currently initializing */
  9723. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  9724. } init;
  9725. int nVdbeActive; /* Number of VDBEs currently running */
  9726. int nVdbeRead; /* Number of active VDBEs that read or write */
  9727. int nVdbeWrite; /* Number of active VDBEs that read and write */
  9728. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  9729. int nExtension; /* Number of loaded extensions */
  9730. void **aExtension; /* Array of shared library handles */
  9731. void (*xTrace)(void*,const char*); /* Trace function */
  9732. void *pTraceArg; /* Argument to the trace function */
  9733. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  9734. void *pProfileArg; /* Argument to profile function */
  9735. void *pCommitArg; /* Argument to xCommitCallback() */
  9736. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  9737. void *pRollbackArg; /* Argument to xRollbackCallback() */
  9738. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  9739. void *pUpdateArg;
  9740. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  9741. #ifndef SQLITE_OMIT_WAL
  9742. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  9743. void *pWalArg;
  9744. #endif
  9745. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  9746. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  9747. void *pCollNeededArg;
  9748. sqlite3_value *pErr; /* Most recent error message */
  9749. union {
  9750. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  9751. double notUsed1; /* Spacer */
  9752. } u1;
  9753. Lookaside lookaside; /* Lookaside malloc configuration */
  9754. #ifndef SQLITE_OMIT_AUTHORIZATION
  9755. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  9756. /* Access authorization function */
  9757. void *pAuthArg; /* 1st argument to the access auth function */
  9758. #endif
  9759. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  9760. int (*xProgress)(void *); /* The progress callback */
  9761. void *pProgressArg; /* Argument to the progress callback */
  9762. unsigned nProgressOps; /* Number of opcodes for progress callback */
  9763. #endif
  9764. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9765. int nVTrans; /* Allocated size of aVTrans */
  9766. Hash aModule; /* populated by sqlite3_create_module() */
  9767. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  9768. VTable **aVTrans; /* Virtual tables with open transactions */
  9769. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  9770. #endif
  9771. FuncDefHash aFunc; /* Hash table of connection functions */
  9772. Hash aCollSeq; /* All collating sequences */
  9773. BusyHandler busyHandler; /* Busy callback */
  9774. Db aDbStatic[2]; /* Static space for the 2 default backends */
  9775. Savepoint *pSavepoint; /* List of active savepoints */
  9776. int busyTimeout; /* Busy handler timeout, in msec */
  9777. int nSavepoint; /* Number of non-transaction savepoints */
  9778. int nStatement; /* Number of nested statement-transactions */
  9779. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  9780. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  9781. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  9782. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  9783. /* The following variables are all protected by the STATIC_MASTER
  9784. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  9785. **
  9786. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  9787. ** unlock so that it can proceed.
  9788. **
  9789. ** When X.pBlockingConnection==Y, that means that something that X tried
  9790. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  9791. ** held by Y.
  9792. */
  9793. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  9794. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  9795. void *pUnlockArg; /* Argument to xUnlockNotify */
  9796. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  9797. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  9798. #endif
  9799. };
  9800. /*
  9801. ** A macro to discover the encoding of a database.
  9802. */
  9803. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  9804. /*
  9805. ** Possible values for the sqlite3.flags.
  9806. */
  9807. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  9808. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  9809. #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
  9810. #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
  9811. #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
  9812. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  9813. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  9814. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  9815. /* DELETE, or UPDATE and return */
  9816. /* the count using a callback. */
  9817. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  9818. /* result set is empty */
  9819. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  9820. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  9821. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  9822. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  9823. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  9824. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  9825. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  9826. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  9827. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  9828. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  9829. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  9830. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  9831. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  9832. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  9833. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  9834. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  9835. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  9836. /*
  9837. ** Bits of the sqlite3.dbOptFlags field that are used by the
  9838. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  9839. ** selectively disable various optimizations.
  9840. */
  9841. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  9842. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  9843. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  9844. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  9845. #define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */
  9846. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  9847. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  9848. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  9849. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  9850. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  9851. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  9852. #define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */
  9853. #define SQLITE_AdjustOutEst 0x1000 /* Adjust output estimates using WHERE */
  9854. #define SQLITE_AllOpts 0xffff /* All optimizations */
  9855. /*
  9856. ** Macros for testing whether or not optimizations are enabled or disabled.
  9857. */
  9858. #ifndef SQLITE_OMIT_BUILTIN_TEST
  9859. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  9860. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  9861. #else
  9862. #define OptimizationDisabled(db, mask) 0
  9863. #define OptimizationEnabled(db, mask) 1
  9864. #endif
  9865. /*
  9866. ** Possible values for the sqlite.magic field.
  9867. ** The numbers are obtained at random and have no special meaning, other
  9868. ** than being distinct from one another.
  9869. */
  9870. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  9871. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  9872. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  9873. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  9874. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  9875. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  9876. /*
  9877. ** Each SQL function is defined by an instance of the following
  9878. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  9879. ** hash table. When multiple functions have the same name, the hash table
  9880. ** points to a linked list of these structures.
  9881. */
  9882. struct FuncDef {
  9883. i16 nArg; /* Number of arguments. -1 means unlimited */
  9884. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  9885. void *pUserData; /* User data parameter */
  9886. FuncDef *pNext; /* Next function with same name */
  9887. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  9888. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  9889. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  9890. char *zName; /* SQL name of the function. */
  9891. FuncDef *pHash; /* Next with a different name but the same hash */
  9892. FuncDestructor *pDestructor; /* Reference counted destructor function */
  9893. };
  9894. /*
  9895. ** This structure encapsulates a user-function destructor callback (as
  9896. ** configured using create_function_v2()) and a reference counter. When
  9897. ** create_function_v2() is called to create a function with a destructor,
  9898. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  9899. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  9900. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  9901. ** member of each of the new FuncDef objects is set to point to the allocated
  9902. ** FuncDestructor.
  9903. **
  9904. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  9905. ** count on this object is decremented. When it reaches 0, the destructor
  9906. ** is invoked and the FuncDestructor structure freed.
  9907. */
  9908. struct FuncDestructor {
  9909. int nRef;
  9910. void (*xDestroy)(void *);
  9911. void *pUserData;
  9912. };
  9913. /*
  9914. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  9915. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  9916. ** are assert() statements in the code to verify this.
  9917. */
  9918. #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  9919. #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
  9920. #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
  9921. #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
  9922. #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
  9923. #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
  9924. #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
  9925. #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
  9926. #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
  9927. #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
  9928. /*
  9929. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  9930. ** used to create the initializers for the FuncDef structures.
  9931. **
  9932. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  9933. ** Used to create a scalar function definition of a function zName
  9934. ** implemented by C function xFunc that accepts nArg arguments. The
  9935. ** value passed as iArg is cast to a (void*) and made available
  9936. ** as the user-data (sqlite3_user_data()) for the function. If
  9937. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  9938. **
  9939. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  9940. ** Used to create an aggregate function definition implemented by
  9941. ** the C functions xStep and xFinal. The first four parameters
  9942. ** are interpreted in the same way as the first 4 parameters to
  9943. ** FUNCTION().
  9944. **
  9945. ** LIKEFUNC(zName, nArg, pArg, flags)
  9946. ** Used to create a scalar function definition of a function zName
  9947. ** that accepts nArg arguments and is implemented by a call to C
  9948. ** function likeFunc. Argument pArg is cast to a (void *) and made
  9949. ** available as the function user-data (sqlite3_user_data()). The
  9950. ** FuncDef.flags variable is set to the value passed as the flags
  9951. ** parameter.
  9952. */
  9953. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  9954. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  9955. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  9956. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  9957. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  9958. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  9959. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  9960. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  9961. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  9962. #define LIKEFUNC(zName, nArg, arg, flags) \
  9963. {nArg, SQLITE_UTF8|flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  9964. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  9965. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  9966. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  9967. /*
  9968. ** All current savepoints are stored in a linked list starting at
  9969. ** sqlite3.pSavepoint. The first element in the list is the most recently
  9970. ** opened savepoint. Savepoints are added to the list by the vdbe
  9971. ** OP_Savepoint instruction.
  9972. */
  9973. struct Savepoint {
  9974. char *zName; /* Savepoint name (nul-terminated) */
  9975. i64 nDeferredCons; /* Number of deferred fk violations */
  9976. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  9977. Savepoint *pNext; /* Parent savepoint (if any) */
  9978. };
  9979. /*
  9980. ** The following are used as the second parameter to sqlite3Savepoint(),
  9981. ** and as the P1 argument to the OP_Savepoint instruction.
  9982. */
  9983. #define SAVEPOINT_BEGIN 0
  9984. #define SAVEPOINT_RELEASE 1
  9985. #define SAVEPOINT_ROLLBACK 2
  9986. /*
  9987. ** Each SQLite module (virtual table definition) is defined by an
  9988. ** instance of the following structure, stored in the sqlite3.aModule
  9989. ** hash table.
  9990. */
  9991. struct Module {
  9992. const sqlite3_module *pModule; /* Callback pointers */
  9993. const char *zName; /* Name passed to create_module() */
  9994. void *pAux; /* pAux passed to create_module() */
  9995. void (*xDestroy)(void *); /* Module destructor function */
  9996. };
  9997. /*
  9998. ** information about each column of an SQL table is held in an instance
  9999. ** of this structure.
  10000. */
  10001. struct Column {
  10002. char *zName; /* Name of this column */
  10003. Expr *pDflt; /* Default value of this column */
  10004. char *zDflt; /* Original text of the default value */
  10005. char *zType; /* Data type for this column */
  10006. char *zColl; /* Collating sequence. If NULL, use the default */
  10007. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  10008. char affinity; /* One of the SQLITE_AFF_... values */
  10009. u8 szEst; /* Estimated size of this column. INT==1 */
  10010. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  10011. };
  10012. /* Allowed values for Column.colFlags:
  10013. */
  10014. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  10015. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  10016. /*
  10017. ** A "Collating Sequence" is defined by an instance of the following
  10018. ** structure. Conceptually, a collating sequence consists of a name and
  10019. ** a comparison routine that defines the order of that sequence.
  10020. **
  10021. ** If CollSeq.xCmp is NULL, it means that the
  10022. ** collating sequence is undefined. Indices built on an undefined
  10023. ** collating sequence may not be read or written.
  10024. */
  10025. struct CollSeq {
  10026. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  10027. u8 enc; /* Text encoding handled by xCmp() */
  10028. void *pUser; /* First argument to xCmp() */
  10029. int (*xCmp)(void*,int, const void*, int, const void*);
  10030. void (*xDel)(void*); /* Destructor for pUser */
  10031. };
  10032. /*
  10033. ** A sort order can be either ASC or DESC.
  10034. */
  10035. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  10036. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  10037. /*
  10038. ** Column affinity types.
  10039. **
  10040. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  10041. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  10042. ** the speed a little by numbering the values consecutively.
  10043. **
  10044. ** But rather than start with 0 or 1, we begin with 'a'. That way,
  10045. ** when multiple affinity types are concatenated into a string and
  10046. ** used as the P4 operand, they will be more readable.
  10047. **
  10048. ** Note also that the numeric types are grouped together so that testing
  10049. ** for a numeric type is a single comparison.
  10050. */
  10051. #define SQLITE_AFF_TEXT 'a'
  10052. #define SQLITE_AFF_NONE 'b'
  10053. #define SQLITE_AFF_NUMERIC 'c'
  10054. #define SQLITE_AFF_INTEGER 'd'
  10055. #define SQLITE_AFF_REAL 'e'
  10056. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  10057. /*
  10058. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  10059. ** affinity value.
  10060. */
  10061. #define SQLITE_AFF_MASK 0x67
  10062. /*
  10063. ** Additional bit values that can be ORed with an affinity without
  10064. ** changing the affinity.
  10065. */
  10066. #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
  10067. #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
  10068. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  10069. /*
  10070. ** An object of this type is created for each virtual table present in
  10071. ** the database schema.
  10072. **
  10073. ** If the database schema is shared, then there is one instance of this
  10074. ** structure for each database connection (sqlite3*) that uses the shared
  10075. ** schema. This is because each database connection requires its own unique
  10076. ** instance of the sqlite3_vtab* handle used to access the virtual table
  10077. ** implementation. sqlite3_vtab* handles can not be shared between
  10078. ** database connections, even when the rest of the in-memory database
  10079. ** schema is shared, as the implementation often stores the database
  10080. ** connection handle passed to it via the xConnect() or xCreate() method
  10081. ** during initialization internally. This database connection handle may
  10082. ** then be used by the virtual table implementation to access real tables
  10083. ** within the database. So that they appear as part of the callers
  10084. ** transaction, these accesses need to be made via the same database
  10085. ** connection as that used to execute SQL operations on the virtual table.
  10086. **
  10087. ** All VTable objects that correspond to a single table in a shared
  10088. ** database schema are initially stored in a linked-list pointed to by
  10089. ** the Table.pVTable member variable of the corresponding Table object.
  10090. ** When an sqlite3_prepare() operation is required to access the virtual
  10091. ** table, it searches the list for the VTable that corresponds to the
  10092. ** database connection doing the preparing so as to use the correct
  10093. ** sqlite3_vtab* handle in the compiled query.
  10094. **
  10095. ** When an in-memory Table object is deleted (for example when the
  10096. ** schema is being reloaded for some reason), the VTable objects are not
  10097. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  10098. ** immediately. Instead, they are moved from the Table.pVTable list to
  10099. ** another linked list headed by the sqlite3.pDisconnect member of the
  10100. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  10101. ** next time a statement is prepared using said sqlite3*. This is done
  10102. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  10103. ** Refer to comments above function sqlite3VtabUnlockList() for an
  10104. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  10105. ** list without holding the corresponding sqlite3.mutex mutex.
  10106. **
  10107. ** The memory for objects of this type is always allocated by
  10108. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  10109. ** the first argument.
  10110. */
  10111. struct VTable {
  10112. sqlite3 *db; /* Database connection associated with this table */
  10113. Module *pMod; /* Pointer to module implementation */
  10114. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  10115. int nRef; /* Number of pointers to this structure */
  10116. u8 bConstraint; /* True if constraints are supported */
  10117. int iSavepoint; /* Depth of the SAVEPOINT stack */
  10118. VTable *pNext; /* Next in linked list (see above) */
  10119. };
  10120. /*
  10121. ** Each SQL table is represented in memory by an instance of the
  10122. ** following structure.
  10123. **
  10124. ** Table.zName is the name of the table. The case of the original
  10125. ** CREATE TABLE statement is stored, but case is not significant for
  10126. ** comparisons.
  10127. **
  10128. ** Table.nCol is the number of columns in this table. Table.aCol is a
  10129. ** pointer to an array of Column structures, one for each column.
  10130. **
  10131. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  10132. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  10133. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  10134. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  10135. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  10136. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  10137. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  10138. **
  10139. ** Table.tnum is the page number for the root BTree page of the table in the
  10140. ** database file. If Table.iDb is the index of the database table backend
  10141. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  10142. ** holds temporary tables and indices. If TF_Ephemeral is set
  10143. ** then the table is stored in a file that is automatically deleted
  10144. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  10145. ** refers VDBE cursor number that holds the table open, not to the root
  10146. ** page number. Transient tables are used to hold the results of a
  10147. ** sub-query that appears instead of a real table name in the FROM clause
  10148. ** of a SELECT statement.
  10149. */
  10150. struct Table {
  10151. char *zName; /* Name of the table or view */
  10152. Column *aCol; /* Information about each column */
  10153. Index *pIndex; /* List of SQL indexes on this table. */
  10154. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  10155. FKey *pFKey; /* Linked list of all foreign keys in this table */
  10156. char *zColAff; /* String defining the affinity of each column */
  10157. #ifndef SQLITE_OMIT_CHECK
  10158. ExprList *pCheck; /* All CHECK constraints */
  10159. #endif
  10160. tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
  10161. int tnum; /* Root BTree node for this table (see note above) */
  10162. i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  10163. i16 nCol; /* Number of columns in this table */
  10164. u16 nRef; /* Number of pointers to this Table */
  10165. LogEst szTabRow; /* Estimated size of each table row in bytes */
  10166. u8 tabFlags; /* Mask of TF_* values */
  10167. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  10168. #ifndef SQLITE_OMIT_ALTERTABLE
  10169. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  10170. #endif
  10171. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10172. int nModuleArg; /* Number of arguments to the module */
  10173. char **azModuleArg; /* Text of all module args. [0] is module name */
  10174. VTable *pVTable; /* List of VTable objects. */
  10175. #endif
  10176. Trigger *pTrigger; /* List of triggers stored in pSchema */
  10177. Schema *pSchema; /* Schema that contains this table */
  10178. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  10179. };
  10180. /*
  10181. ** Allowed values for Tabe.tabFlags.
  10182. */
  10183. #define TF_Readonly 0x01 /* Read-only system table */
  10184. #define TF_Ephemeral 0x02 /* An ephemeral table */
  10185. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  10186. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  10187. #define TF_Virtual 0x10 /* Is a virtual table */
  10188. /*
  10189. ** Test to see whether or not a table is a virtual table. This is
  10190. ** done as a macro so that it will be optimized out when virtual
  10191. ** table support is omitted from the build.
  10192. */
  10193. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10194. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  10195. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  10196. #else
  10197. # define IsVirtual(X) 0
  10198. # define IsHiddenColumn(X) 0
  10199. #endif
  10200. /*
  10201. ** Each foreign key constraint is an instance of the following structure.
  10202. **
  10203. ** A foreign key is associated with two tables. The "from" table is
  10204. ** the table that contains the REFERENCES clause that creates the foreign
  10205. ** key. The "to" table is the table that is named in the REFERENCES clause.
  10206. ** Consider this example:
  10207. **
  10208. ** CREATE TABLE ex1(
  10209. ** a INTEGER PRIMARY KEY,
  10210. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  10211. ** );
  10212. **
  10213. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  10214. **
  10215. ** Each REFERENCES clause generates an instance of the following structure
  10216. ** which is attached to the from-table. The to-table need not exist when
  10217. ** the from-table is created. The existence of the to-table is not checked.
  10218. */
  10219. struct FKey {
  10220. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  10221. FKey *pNextFrom; /* Next foreign key in pFrom */
  10222. char *zTo; /* Name of table that the key points to (aka: Parent) */
  10223. FKey *pNextTo; /* Next foreign key on table named zTo */
  10224. FKey *pPrevTo; /* Previous foreign key on table named zTo */
  10225. int nCol; /* Number of columns in this key */
  10226. /* EV: R-30323-21917 */
  10227. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  10228. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  10229. Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
  10230. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  10231. int iFrom; /* Index of column in pFrom */
  10232. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  10233. } aCol[1]; /* One entry for each of nCol column s */
  10234. };
  10235. /*
  10236. ** SQLite supports many different ways to resolve a constraint
  10237. ** error. ROLLBACK processing means that a constraint violation
  10238. ** causes the operation in process to fail and for the current transaction
  10239. ** to be rolled back. ABORT processing means the operation in process
  10240. ** fails and any prior changes from that one operation are backed out,
  10241. ** but the transaction is not rolled back. FAIL processing means that
  10242. ** the operation in progress stops and returns an error code. But prior
  10243. ** changes due to the same operation are not backed out and no rollback
  10244. ** occurs. IGNORE means that the particular row that caused the constraint
  10245. ** error is not inserted or updated. Processing continues and no error
  10246. ** is returned. REPLACE means that preexisting database rows that caused
  10247. ** a UNIQUE constraint violation are removed so that the new insert or
  10248. ** update can proceed. Processing continues and no error is reported.
  10249. **
  10250. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  10251. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  10252. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  10253. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  10254. ** referenced table row is propagated into the row that holds the
  10255. ** foreign key.
  10256. **
  10257. ** The following symbolic values are used to record which type
  10258. ** of action to take.
  10259. */
  10260. #define OE_None 0 /* There is no constraint to check */
  10261. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  10262. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  10263. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  10264. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  10265. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  10266. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  10267. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  10268. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  10269. #define OE_Cascade 9 /* Cascade the changes */
  10270. #define OE_Default 10 /* Do whatever the default action is */
  10271. /*
  10272. ** An instance of the following structure is passed as the first
  10273. ** argument to sqlite3VdbeKeyCompare and is used to control the
  10274. ** comparison of the two index keys.
  10275. **
  10276. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  10277. ** are nField slots for the columns of an index then one extra slot
  10278. ** for the rowid at the end.
  10279. */
  10280. struct KeyInfo {
  10281. sqlite3 *db; /* The database connection */
  10282. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  10283. u16 nField; /* Maximum index for aColl[] and aSortOrder[] */
  10284. u8 *aSortOrder; /* Sort order for each column. */
  10285. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  10286. };
  10287. /*
  10288. ** An instance of the following structure holds information about a
  10289. ** single index record that has already been parsed out into individual
  10290. ** values.
  10291. **
  10292. ** A record is an object that contains one or more fields of data.
  10293. ** Records are used to store the content of a table row and to store
  10294. ** the key of an index. A blob encoding of a record is created by
  10295. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  10296. ** OP_Column opcode.
  10297. **
  10298. ** This structure holds a record that has already been disassembled
  10299. ** into its constituent fields.
  10300. */
  10301. struct UnpackedRecord {
  10302. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  10303. u16 nField; /* Number of entries in apMem[] */
  10304. u8 flags; /* Boolean settings. UNPACKED_... below */
  10305. i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
  10306. Mem *aMem; /* Values */
  10307. };
  10308. /*
  10309. ** Allowed values of UnpackedRecord.flags
  10310. */
  10311. #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */
  10312. #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */
  10313. #define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */
  10314. /*
  10315. ** Each SQL index is represented in memory by an
  10316. ** instance of the following structure.
  10317. **
  10318. ** The columns of the table that are to be indexed are described
  10319. ** by the aiColumn[] field of this structure. For example, suppose
  10320. ** we have the following table and index:
  10321. **
  10322. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  10323. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  10324. **
  10325. ** In the Table structure describing Ex1, nCol==3 because there are
  10326. ** three columns in the table. In the Index structure describing
  10327. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  10328. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  10329. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  10330. ** The second column to be indexed (c1) has an index of 0 in
  10331. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  10332. **
  10333. ** The Index.onError field determines whether or not the indexed columns
  10334. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  10335. ** it means this is not a unique index. Otherwise it is a unique index
  10336. ** and the value of Index.onError indicate the which conflict resolution
  10337. ** algorithm to employ whenever an attempt is made to insert a non-unique
  10338. ** element.
  10339. */
  10340. struct Index {
  10341. char *zName; /* Name of this index */
  10342. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  10343. tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */
  10344. Table *pTable; /* The SQL table being indexed */
  10345. char *zColAff; /* String defining the affinity of each column */
  10346. Index *pNext; /* The next index associated with the same table */
  10347. Schema *pSchema; /* Schema containing this index */
  10348. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  10349. char **azColl; /* Array of collation sequence names for index */
  10350. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  10351. int tnum; /* DB Page containing root of this index */
  10352. LogEst szIdxRow; /* Estimated average row size in bytes */
  10353. u16 nColumn; /* Number of columns in table used by this index */
  10354. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  10355. unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  10356. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  10357. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  10358. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  10359. int nSample; /* Number of elements in aSample[] */
  10360. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  10361. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  10362. IndexSample *aSample; /* Samples of the left-most key */
  10363. #endif
  10364. };
  10365. /*
  10366. ** Each sample stored in the sqlite_stat3 table is represented in memory
  10367. ** using a structure of this type. See documentation at the top of the
  10368. ** analyze.c source file for additional information.
  10369. */
  10370. struct IndexSample {
  10371. void *p; /* Pointer to sampled record */
  10372. int n; /* Size of record in bytes */
  10373. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  10374. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  10375. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  10376. };
  10377. /*
  10378. ** Each token coming out of the lexer is an instance of
  10379. ** this structure. Tokens are also used as part of an expression.
  10380. **
  10381. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  10382. ** may contain random values. Do not make any assumptions about Token.dyn
  10383. ** and Token.n when Token.z==0.
  10384. */
  10385. struct Token {
  10386. const char *z; /* Text of the token. Not NULL-terminated! */
  10387. unsigned int n; /* Number of characters in this token */
  10388. };
  10389. /*
  10390. ** An instance of this structure contains information needed to generate
  10391. ** code for a SELECT that contains aggregate functions.
  10392. **
  10393. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  10394. ** pointer to this structure. The Expr.iColumn field is the index in
  10395. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  10396. ** code for that node.
  10397. **
  10398. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  10399. ** original Select structure that describes the SELECT statement. These
  10400. ** fields do not need to be freed when deallocating the AggInfo structure.
  10401. */
  10402. struct AggInfo {
  10403. u8 directMode; /* Direct rendering mode means take data directly
  10404. ** from source tables rather than from accumulators */
  10405. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  10406. ** than the source table */
  10407. int sortingIdx; /* Cursor number of the sorting index */
  10408. int sortingIdxPTab; /* Cursor number of pseudo-table */
  10409. int nSortingColumn; /* Number of columns in the sorting index */
  10410. ExprList *pGroupBy; /* The group by clause */
  10411. struct AggInfo_col { /* For each column used in source tables */
  10412. Table *pTab; /* Source table */
  10413. int iTable; /* Cursor number of the source table */
  10414. int iColumn; /* Column number within the source table */
  10415. int iSorterColumn; /* Column number in the sorting index */
  10416. int iMem; /* Memory location that acts as accumulator */
  10417. Expr *pExpr; /* The original expression */
  10418. } *aCol;
  10419. int nColumn; /* Number of used entries in aCol[] */
  10420. int nAccumulator; /* Number of columns that show through to the output.
  10421. ** Additional columns are used only as parameters to
  10422. ** aggregate functions */
  10423. struct AggInfo_func { /* For each aggregate function */
  10424. Expr *pExpr; /* Expression encoding the function */
  10425. FuncDef *pFunc; /* The aggregate function implementation */
  10426. int iMem; /* Memory location that acts as accumulator */
  10427. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  10428. } *aFunc;
  10429. int nFunc; /* Number of entries in aFunc[] */
  10430. };
  10431. /*
  10432. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  10433. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  10434. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  10435. ** it uses less memory in the Expr object, which is a big memory user
  10436. ** in systems with lots of prepared statements. And few applications
  10437. ** need more than about 10 or 20 variables. But some extreme users want
  10438. ** to have prepared statements with over 32767 variables, and for them
  10439. ** the option is available (at compile-time).
  10440. */
  10441. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  10442. typedef i16 ynVar;
  10443. #else
  10444. typedef int ynVar;
  10445. #endif
  10446. /*
  10447. ** Each node of an expression in the parse tree is an instance
  10448. ** of this structure.
  10449. **
  10450. ** Expr.op is the opcode. The integer parser token codes are reused
  10451. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  10452. ** code representing the ">=" operator. This same integer code is reused
  10453. ** to represent the greater-than-or-equal-to operator in the expression
  10454. ** tree.
  10455. **
  10456. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  10457. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  10458. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  10459. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  10460. ** then Expr.token contains the name of the function.
  10461. **
  10462. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  10463. ** binary operator. Either or both may be NULL.
  10464. **
  10465. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  10466. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  10467. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  10468. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  10469. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  10470. ** valid.
  10471. **
  10472. ** An expression of the form ID or ID.ID refers to a column in a table.
  10473. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  10474. ** the integer cursor number of a VDBE cursor pointing to that table and
  10475. ** Expr.iColumn is the column number for the specific column. If the
  10476. ** expression is used as a result in an aggregate SELECT, then the
  10477. ** value is also stored in the Expr.iAgg column in the aggregate so that
  10478. ** it can be accessed after all aggregates are computed.
  10479. **
  10480. ** If the expression is an unbound variable marker (a question mark
  10481. ** character '?' in the original SQL) then the Expr.iTable holds the index
  10482. ** number for that variable.
  10483. **
  10484. ** If the expression is a subquery then Expr.iColumn holds an integer
  10485. ** register number containing the result of the subquery. If the
  10486. ** subquery gives a constant result, then iTable is -1. If the subquery
  10487. ** gives a different answer at different times during statement processing
  10488. ** then iTable is the address of a subroutine that computes the subquery.
  10489. **
  10490. ** If the Expr is of type OP_Column, and the table it is selecting from
  10491. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  10492. ** corresponding table definition.
  10493. **
  10494. ** ALLOCATION NOTES:
  10495. **
  10496. ** Expr objects can use a lot of memory space in database schema. To
  10497. ** help reduce memory requirements, sometimes an Expr object will be
  10498. ** truncated. And to reduce the number of memory allocations, sometimes
  10499. ** two or more Expr objects will be stored in a single memory allocation,
  10500. ** together with Expr.zToken strings.
  10501. **
  10502. ** If the EP_Reduced and EP_TokenOnly flags are set when
  10503. ** an Expr object is truncated. When EP_Reduced is set, then all
  10504. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  10505. ** are contained within the same memory allocation. Note, however, that
  10506. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  10507. ** allocated, regardless of whether or not EP_Reduced is set.
  10508. */
  10509. struct Expr {
  10510. u8 op; /* Operation performed by this node */
  10511. char affinity; /* The affinity of the column or 0 if not a column */
  10512. u32 flags; /* Various flags. EP_* See below */
  10513. union {
  10514. char *zToken; /* Token value. Zero terminated and dequoted */
  10515. int iValue; /* Non-negative integer value if EP_IntValue */
  10516. } u;
  10517. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  10518. ** space is allocated for the fields below this point. An attempt to
  10519. ** access them will result in a segfault or malfunction.
  10520. *********************************************************************/
  10521. Expr *pLeft; /* Left subnode */
  10522. Expr *pRight; /* Right subnode */
  10523. union {
  10524. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  10525. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  10526. } x;
  10527. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  10528. ** space is allocated for the fields below this point. An attempt to
  10529. ** access them will result in a segfault or malfunction.
  10530. *********************************************************************/
  10531. #if SQLITE_MAX_EXPR_DEPTH>0
  10532. int nHeight; /* Height of the tree headed by this node */
  10533. #endif
  10534. int iTable; /* TK_COLUMN: cursor number of table holding column
  10535. ** TK_REGISTER: register number
  10536. ** TK_TRIGGER: 1 -> new, 0 -> old
  10537. ** EP_Unlikely: 1000 times likelihood */
  10538. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  10539. ** TK_VARIABLE: variable number (always >= 1). */
  10540. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  10541. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  10542. u8 op2; /* TK_REGISTER: original value of Expr.op
  10543. ** TK_COLUMN: the value of p5 for OP_Column
  10544. ** TK_AGG_FUNCTION: nesting depth */
  10545. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  10546. Table *pTab; /* Table for TK_COLUMN expressions. */
  10547. };
  10548. /*
  10549. ** The following are the meanings of bits in the Expr.flags field.
  10550. */
  10551. #define EP_FromJoin 0x000001 /* Originated in ON or USING clause of a join */
  10552. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  10553. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  10554. #define EP_Error 0x000008 /* Expression contains one or more errors */
  10555. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  10556. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  10557. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  10558. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  10559. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE opeartor */
  10560. #define EP_FixedDest 0x000200 /* Result needed in a specific register */
  10561. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  10562. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  10563. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  10564. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  10565. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  10566. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  10567. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  10568. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  10569. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  10570. /*
  10571. ** These macros can be used to test, set, or clear bits in the
  10572. ** Expr.flags field.
  10573. */
  10574. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  10575. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  10576. #define ExprSetProperty(E,P) (E)->flags|=(P)
  10577. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  10578. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  10579. ** and Accreditation only. It works like ExprSetProperty() during VVA
  10580. ** processes but is a no-op for delivery.
  10581. */
  10582. #ifdef SQLITE_DEBUG
  10583. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  10584. #else
  10585. # define ExprSetVVAProperty(E,P)
  10586. #endif
  10587. /*
  10588. ** Macros to determine the number of bytes required by a normal Expr
  10589. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  10590. ** and an Expr struct with the EP_TokenOnly flag set.
  10591. */
  10592. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  10593. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  10594. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  10595. /*
  10596. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  10597. ** above sqlite3ExprDup() for details.
  10598. */
  10599. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  10600. /*
  10601. ** A list of expressions. Each expression may optionally have a
  10602. ** name. An expr/name combination can be used in several ways, such
  10603. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  10604. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  10605. ** also be used as the argument to a function, in which case the a.zName
  10606. ** field is not used.
  10607. **
  10608. ** By default the Expr.zSpan field holds a human-readable description of
  10609. ** the expression that is used in the generation of error messages and
  10610. ** column labels. In this case, Expr.zSpan is typically the text of a
  10611. ** column expression as it exists in a SELECT statement. However, if
  10612. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  10613. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  10614. ** form is used for name resolution with nested FROM clauses.
  10615. */
  10616. struct ExprList {
  10617. int nExpr; /* Number of expressions on the list */
  10618. int iECursor; /* VDBE Cursor associated with this ExprList */
  10619. struct ExprList_item { /* For each expression in the list */
  10620. Expr *pExpr; /* The list of expressions */
  10621. char *zName; /* Token associated with this expression */
  10622. char *zSpan; /* Original text of the expression */
  10623. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  10624. unsigned done :1; /* A flag to indicate when processing is finished */
  10625. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  10626. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  10627. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  10628. } *a; /* Alloc a power of two greater or equal to nExpr */
  10629. };
  10630. /*
  10631. ** An instance of this structure is used by the parser to record both
  10632. ** the parse tree for an expression and the span of input text for an
  10633. ** expression.
  10634. */
  10635. struct ExprSpan {
  10636. Expr *pExpr; /* The expression parse tree */
  10637. const char *zStart; /* First character of input text */
  10638. const char *zEnd; /* One character past the end of input text */
  10639. };
  10640. /*
  10641. ** An instance of this structure can hold a simple list of identifiers,
  10642. ** such as the list "a,b,c" in the following statements:
  10643. **
  10644. ** INSERT INTO t(a,b,c) VALUES ...;
  10645. ** CREATE INDEX idx ON t(a,b,c);
  10646. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  10647. **
  10648. ** The IdList.a.idx field is used when the IdList represents the list of
  10649. ** column names after a table name in an INSERT statement. In the statement
  10650. **
  10651. ** INSERT INTO t(a,b,c) ...
  10652. **
  10653. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  10654. */
  10655. struct IdList {
  10656. struct IdList_item {
  10657. char *zName; /* Name of the identifier */
  10658. int idx; /* Index in some Table.aCol[] of a column named zName */
  10659. } *a;
  10660. int nId; /* Number of identifiers on the list */
  10661. };
  10662. /*
  10663. ** The bitmask datatype defined below is used for various optimizations.
  10664. **
  10665. ** Changing this from a 64-bit to a 32-bit type limits the number of
  10666. ** tables in a join to 32 instead of 64. But it also reduces the size
  10667. ** of the library by 738 bytes on ix86.
  10668. */
  10669. typedef u64 Bitmask;
  10670. /*
  10671. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  10672. */
  10673. #define BMS ((int)(sizeof(Bitmask)*8))
  10674. /*
  10675. ** A bit in a Bitmask
  10676. */
  10677. #define MASKBIT(n) (((Bitmask)1)<<(n))
  10678. /*
  10679. ** The following structure describes the FROM clause of a SELECT statement.
  10680. ** Each table or subquery in the FROM clause is a separate element of
  10681. ** the SrcList.a[] array.
  10682. **
  10683. ** With the addition of multiple database support, the following structure
  10684. ** can also be used to describe a particular table such as the table that
  10685. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  10686. ** such a table must be a simple name: ID. But in SQLite, the table can
  10687. ** now be identified by a database name, a dot, then the table name: ID.ID.
  10688. **
  10689. ** The jointype starts out showing the join type between the current table
  10690. ** and the next table on the list. The parser builds the list this way.
  10691. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  10692. ** jointype expresses the join between the table and the previous table.
  10693. **
  10694. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  10695. ** contains more than 63 columns and the 64-th or later column is used.
  10696. */
  10697. struct SrcList {
  10698. u8 nSrc; /* Number of tables or subqueries in the FROM clause */
  10699. u8 nAlloc; /* Number of entries allocated in a[] below */
  10700. struct SrcList_item {
  10701. Schema *pSchema; /* Schema to which this item is fixed */
  10702. char *zDatabase; /* Name of database holding this table */
  10703. char *zName; /* Name of the table */
  10704. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  10705. Table *pTab; /* An SQL table corresponding to zName */
  10706. Select *pSelect; /* A SELECT statement used in place of a table name */
  10707. int addrFillSub; /* Address of subroutine to manifest a subquery */
  10708. int regReturn; /* Register holding return address of addrFillSub */
  10709. u8 jointype; /* Type of join between this able and the previous */
  10710. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  10711. unsigned isCorrelated :1; /* True if sub-query is correlated */
  10712. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  10713. #ifndef SQLITE_OMIT_EXPLAIN
  10714. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  10715. #endif
  10716. int iCursor; /* The VDBE cursor number used to access this table */
  10717. Expr *pOn; /* The ON clause of a join */
  10718. IdList *pUsing; /* The USING clause of a join */
  10719. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  10720. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  10721. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  10722. } a[1]; /* One entry for each identifier on the list */
  10723. };
  10724. /*
  10725. ** Permitted values of the SrcList.a.jointype field
  10726. */
  10727. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  10728. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  10729. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  10730. #define JT_LEFT 0x0008 /* Left outer join */
  10731. #define JT_RIGHT 0x0010 /* Right outer join */
  10732. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  10733. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  10734. /*
  10735. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  10736. ** and the WhereInfo.wctrlFlags member.
  10737. */
  10738. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  10739. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  10740. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  10741. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  10742. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  10743. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  10744. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  10745. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  10746. #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
  10747. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  10748. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  10749. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  10750. /* Allowed return values from sqlite3WhereIsDistinct()
  10751. */
  10752. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  10753. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  10754. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  10755. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  10756. /*
  10757. ** A NameContext defines a context in which to resolve table and column
  10758. ** names. The context consists of a list of tables (the pSrcList) field and
  10759. ** a list of named expression (pEList). The named expression list may
  10760. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  10761. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  10762. ** pEList corresponds to the result set of a SELECT and is NULL for
  10763. ** other statements.
  10764. **
  10765. ** NameContexts can be nested. When resolving names, the inner-most
  10766. ** context is searched first. If no match is found, the next outer
  10767. ** context is checked. If there is still no match, the next context
  10768. ** is checked. This process continues until either a match is found
  10769. ** or all contexts are check. When a match is found, the nRef member of
  10770. ** the context containing the match is incremented.
  10771. **
  10772. ** Each subquery gets a new NameContext. The pNext field points to the
  10773. ** NameContext in the parent query. Thus the process of scanning the
  10774. ** NameContext list corresponds to searching through successively outer
  10775. ** subqueries looking for a match.
  10776. */
  10777. struct NameContext {
  10778. Parse *pParse; /* The parser */
  10779. SrcList *pSrcList; /* One or more tables used to resolve names */
  10780. ExprList *pEList; /* Optional list of result-set columns */
  10781. AggInfo *pAggInfo; /* Information about aggregates at this level */
  10782. NameContext *pNext; /* Next outer name context. NULL for outermost */
  10783. int nRef; /* Number of names resolved by this context */
  10784. int nErr; /* Number of errors encountered while resolving names */
  10785. u8 ncFlags; /* Zero or more NC_* flags defined below */
  10786. };
  10787. /*
  10788. ** Allowed values for the NameContext, ncFlags field.
  10789. */
  10790. #define NC_AllowAgg 0x01 /* Aggregate functions are allowed here */
  10791. #define NC_HasAgg 0x02 /* One or more aggregate functions seen */
  10792. #define NC_IsCheck 0x04 /* True if resolving names in a CHECK constraint */
  10793. #define NC_InAggFunc 0x08 /* True if analyzing arguments to an agg func */
  10794. #define NC_PartIdx 0x10 /* True if resolving a partial index WHERE */
  10795. /*
  10796. ** An instance of the following structure contains all information
  10797. ** needed to generate code for a single SELECT statement.
  10798. **
  10799. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  10800. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  10801. ** limit and nOffset to the value of the offset (or 0 if there is not
  10802. ** offset). But later on, nLimit and nOffset become the memory locations
  10803. ** in the VDBE that record the limit and offset counters.
  10804. **
  10805. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  10806. ** These addresses must be stored so that we can go back and fill in
  10807. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  10808. ** the number of columns in P2 can be computed at the same time
  10809. ** as the OP_OpenEphm instruction is coded because not
  10810. ** enough information about the compound query is known at that point.
  10811. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  10812. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  10813. ** sequences for the ORDER BY clause.
  10814. */
  10815. struct Select {
  10816. ExprList *pEList; /* The fields of the result */
  10817. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  10818. u16 selFlags; /* Various SF_* values */
  10819. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  10820. int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
  10821. u64 nSelectRow; /* Estimated number of result rows */
  10822. SrcList *pSrc; /* The FROM clause */
  10823. Expr *pWhere; /* The WHERE clause */
  10824. ExprList *pGroupBy; /* The GROUP BY clause */
  10825. Expr *pHaving; /* The HAVING clause */
  10826. ExprList *pOrderBy; /* The ORDER BY clause */
  10827. Select *pPrior; /* Prior select in a compound select statement */
  10828. Select *pNext; /* Next select to the left in a compound */
  10829. Select *pRightmost; /* Right-most select in a compound select statement */
  10830. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  10831. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  10832. };
  10833. /*
  10834. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  10835. ** "Select Flag".
  10836. */
  10837. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  10838. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  10839. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  10840. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  10841. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  10842. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  10843. #define SF_UseSorter 0x0040 /* Sort using a sorter */
  10844. #define SF_Values 0x0080 /* Synthesized from VALUES clause */
  10845. #define SF_Materialize 0x0100 /* Force materialization of views */
  10846. #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
  10847. #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
  10848. /*
  10849. ** The results of a select can be distributed in several ways. The
  10850. ** "SRT" prefix means "SELECT Result Type".
  10851. */
  10852. #define SRT_Union 1 /* Store result as keys in an index */
  10853. #define SRT_Except 2 /* Remove result from a UNION index */
  10854. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  10855. #define SRT_Discard 4 /* Do not save the results anywhere */
  10856. /* The ORDER BY clause is ignored for all of the above */
  10857. #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
  10858. #define SRT_Output 5 /* Output each row of result */
  10859. #define SRT_Mem 6 /* Store result in a memory cell */
  10860. #define SRT_Set 7 /* Store results as keys in an index */
  10861. #define SRT_Table 8 /* Store result as data with an automatic rowid */
  10862. #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
  10863. #define SRT_Coroutine 10 /* Generate a single row of result */
  10864. /*
  10865. ** An instance of this object describes where to put of the results of
  10866. ** a SELECT statement.
  10867. */
  10868. struct SelectDest {
  10869. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  10870. char affSdst; /* Affinity used when eDest==SRT_Set */
  10871. int iSDParm; /* A parameter used by the eDest disposal method */
  10872. int iSdst; /* Base register where results are written */
  10873. int nSdst; /* Number of registers allocated */
  10874. };
  10875. /*
  10876. ** During code generation of statements that do inserts into AUTOINCREMENT
  10877. ** tables, the following information is attached to the Table.u.autoInc.p
  10878. ** pointer of each autoincrement table to record some side information that
  10879. ** the code generator needs. We have to keep per-table autoincrement
  10880. ** information in case inserts are down within triggers. Triggers do not
  10881. ** normally coordinate their activities, but we do need to coordinate the
  10882. ** loading and saving of autoincrement information.
  10883. */
  10884. struct AutoincInfo {
  10885. AutoincInfo *pNext; /* Next info block in a list of them all */
  10886. Table *pTab; /* Table this info block refers to */
  10887. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  10888. int regCtr; /* Memory register holding the rowid counter */
  10889. };
  10890. /*
  10891. ** Size of the column cache
  10892. */
  10893. #ifndef SQLITE_N_COLCACHE
  10894. # define SQLITE_N_COLCACHE 10
  10895. #endif
  10896. /*
  10897. ** At least one instance of the following structure is created for each
  10898. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  10899. ** statement. All such objects are stored in the linked list headed at
  10900. ** Parse.pTriggerPrg and deleted once statement compilation has been
  10901. ** completed.
  10902. **
  10903. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  10904. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  10905. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  10906. ** The Parse.pTriggerPrg list never contains two entries with the same
  10907. ** values for both pTrigger and orconf.
  10908. **
  10909. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  10910. ** accessed (or set to 0 for triggers fired as a result of INSERT
  10911. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  10912. ** a mask of new.* columns used by the program.
  10913. */
  10914. struct TriggerPrg {
  10915. Trigger *pTrigger; /* Trigger this program was coded from */
  10916. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  10917. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  10918. int orconf; /* Default ON CONFLICT policy */
  10919. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  10920. };
  10921. /*
  10922. ** The yDbMask datatype for the bitmask of all attached databases.
  10923. */
  10924. #if SQLITE_MAX_ATTACHED>30
  10925. typedef sqlite3_uint64 yDbMask;
  10926. #else
  10927. typedef unsigned int yDbMask;
  10928. #endif
  10929. /*
  10930. ** An SQL parser context. A copy of this structure is passed through
  10931. ** the parser and down into all the parser action routine in order to
  10932. ** carry around information that is global to the entire parse.
  10933. **
  10934. ** The structure is divided into two parts. When the parser and code
  10935. ** generate call themselves recursively, the first part of the structure
  10936. ** is constant but the second part is reset at the beginning and end of
  10937. ** each recursion.
  10938. **
  10939. ** The nTableLock and aTableLock variables are only used if the shared-cache
  10940. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  10941. ** used to store the set of table-locks required by the statement being
  10942. ** compiled. Function sqlite3TableLock() is used to add entries to the
  10943. ** list.
  10944. */
  10945. struct Parse {
  10946. sqlite3 *db; /* The main database structure */
  10947. char *zErrMsg; /* An error message */
  10948. Vdbe *pVdbe; /* An engine for executing database bytecode */
  10949. int rc; /* Return code from execution */
  10950. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  10951. u8 checkSchema; /* Causes schema cookie check after an error */
  10952. u8 nested; /* Number of nested calls to the parser/code generator */
  10953. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  10954. u8 nTempInUse; /* Number of aTempReg[] currently checked out */
  10955. u8 nColCache; /* Number of entries in aColCache[] */
  10956. u8 iColCache; /* Next entry in aColCache[] to replace */
  10957. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  10958. u8 mayAbort; /* True if statement may throw an ABORT exception */
  10959. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  10960. int aTempReg[8]; /* Holding area for temporary registers */
  10961. int nRangeReg; /* Size of the temporary register block */
  10962. int iRangeReg; /* First register in temporary register block */
  10963. int nErr; /* Number of errors seen */
  10964. int nTab; /* Number of previously allocated VDBE cursors */
  10965. int nMem; /* Number of memory cells used so far */
  10966. int nSet; /* Number of sets used so far */
  10967. int nOnce; /* Number of OP_Once instructions so far */
  10968. int ckBase; /* Base register of data during check constraints */
  10969. int iPartIdxTab; /* Table corresponding to a partial index */
  10970. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  10971. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  10972. struct yColCache {
  10973. int iTable; /* Table cursor number */
  10974. int iColumn; /* Table column number */
  10975. u8 tempReg; /* iReg is a temp register that needs to be freed */
  10976. int iLevel; /* Nesting level */
  10977. int iReg; /* Reg with value of this column. 0 means none. */
  10978. int lru; /* Least recently used entry has the smallest value */
  10979. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  10980. yDbMask writeMask; /* Start a write transaction on these databases */
  10981. yDbMask cookieMask; /* Bitmask of schema verified databases */
  10982. int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
  10983. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  10984. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  10985. int regRoot; /* Register holding root page number for new objects */
  10986. int nMaxArg; /* Max args passed to user function by sub-program */
  10987. Token constraintName;/* Name of the constraint currently being parsed */
  10988. #ifndef SQLITE_OMIT_SHARED_CACHE
  10989. int nTableLock; /* Number of locks in aTableLock */
  10990. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  10991. #endif
  10992. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  10993. /* Information used while coding trigger programs. */
  10994. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  10995. Table *pTriggerTab; /* Table triggers are being coded for */
  10996. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  10997. u32 oldmask; /* Mask of old.* columns referenced */
  10998. u32 newmask; /* Mask of new.* columns referenced */
  10999. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  11000. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  11001. u8 disableTriggers; /* True to disable triggers */
  11002. /* Above is constant between recursions. Below is reset before and after
  11003. ** each recursion */
  11004. int nVar; /* Number of '?' variables seen in the SQL so far */
  11005. int nzVar; /* Number of available slots in azVar[] */
  11006. u8 explain; /* True if the EXPLAIN flag is found on the query */
  11007. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11008. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  11009. int nVtabLock; /* Number of virtual tables to lock */
  11010. #endif
  11011. int nAlias; /* Number of aliased result set columns */
  11012. int nHeight; /* Expression tree height of current sub-select */
  11013. #ifndef SQLITE_OMIT_EXPLAIN
  11014. int iSelectId; /* ID of current select for EXPLAIN output */
  11015. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  11016. #endif
  11017. char **azVar; /* Pointers to names of parameters */
  11018. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  11019. int *aAlias; /* Register used to hold aliased result */
  11020. const char *zTail; /* All SQL text past the last semicolon parsed */
  11021. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  11022. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  11023. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  11024. Token sNameToken; /* Token with unqualified schema object name */
  11025. Token sLastToken; /* The last token parsed */
  11026. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11027. Token sArg; /* Complete text of a module argument */
  11028. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  11029. #endif
  11030. Table *pZombieTab; /* List of Table objects to delete after code gen */
  11031. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  11032. };
  11033. /*
  11034. ** Return true if currently inside an sqlite3_declare_vtab() call.
  11035. */
  11036. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11037. #define IN_DECLARE_VTAB 0
  11038. #else
  11039. #define IN_DECLARE_VTAB (pParse->declareVtab)
  11040. #endif
  11041. /*
  11042. ** An instance of the following structure can be declared on a stack and used
  11043. ** to save the Parse.zAuthContext value so that it can be restored later.
  11044. */
  11045. struct AuthContext {
  11046. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  11047. Parse *pParse; /* The Parse structure */
  11048. };
  11049. /*
  11050. ** Bitfield flags for P5 value in various opcodes.
  11051. */
  11052. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  11053. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  11054. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  11055. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  11056. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  11057. #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
  11058. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  11059. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  11060. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  11061. #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
  11062. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  11063. /*
  11064. * Each trigger present in the database schema is stored as an instance of
  11065. * struct Trigger.
  11066. *
  11067. * Pointers to instances of struct Trigger are stored in two ways.
  11068. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  11069. * database). This allows Trigger structures to be retrieved by name.
  11070. * 2. All triggers associated with a single table form a linked list, using the
  11071. * pNext member of struct Trigger. A pointer to the first element of the
  11072. * linked list is stored as the "pTrigger" member of the associated
  11073. * struct Table.
  11074. *
  11075. * The "step_list" member points to the first element of a linked list
  11076. * containing the SQL statements specified as the trigger program.
  11077. */
  11078. struct Trigger {
  11079. char *zName; /* The name of the trigger */
  11080. char *table; /* The table or view to which the trigger applies */
  11081. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  11082. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  11083. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  11084. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  11085. the <column-list> is stored here */
  11086. Schema *pSchema; /* Schema containing the trigger */
  11087. Schema *pTabSchema; /* Schema containing the table */
  11088. TriggerStep *step_list; /* Link list of trigger program steps */
  11089. Trigger *pNext; /* Next trigger associated with the table */
  11090. };
  11091. /*
  11092. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  11093. ** determine which.
  11094. **
  11095. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  11096. ** In that cases, the constants below can be ORed together.
  11097. */
  11098. #define TRIGGER_BEFORE 1
  11099. #define TRIGGER_AFTER 2
  11100. /*
  11101. * An instance of struct TriggerStep is used to store a single SQL statement
  11102. * that is a part of a trigger-program.
  11103. *
  11104. * Instances of struct TriggerStep are stored in a singly linked list (linked
  11105. * using the "pNext" member) referenced by the "step_list" member of the
  11106. * associated struct Trigger instance. The first element of the linked list is
  11107. * the first step of the trigger-program.
  11108. *
  11109. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  11110. * "SELECT" statement. The meanings of the other members is determined by the
  11111. * value of "op" as follows:
  11112. *
  11113. * (op == TK_INSERT)
  11114. * orconf -> stores the ON CONFLICT algorithm
  11115. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  11116. * this stores a pointer to the SELECT statement. Otherwise NULL.
  11117. * target -> A token holding the quoted name of the table to insert into.
  11118. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  11119. * this stores values to be inserted. Otherwise NULL.
  11120. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  11121. * statement, then this stores the column-names to be
  11122. * inserted into.
  11123. *
  11124. * (op == TK_DELETE)
  11125. * target -> A token holding the quoted name of the table to delete from.
  11126. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  11127. * Otherwise NULL.
  11128. *
  11129. * (op == TK_UPDATE)
  11130. * target -> A token holding the quoted name of the table to update rows of.
  11131. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  11132. * Otherwise NULL.
  11133. * pExprList -> A list of the columns to update and the expressions to update
  11134. * them to. See sqlite3Update() documentation of "pChanges"
  11135. * argument.
  11136. *
  11137. */
  11138. struct TriggerStep {
  11139. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  11140. u8 orconf; /* OE_Rollback etc. */
  11141. Trigger *pTrig; /* The trigger that this step is a part of */
  11142. Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  11143. Token target; /* Target table for DELETE, UPDATE, INSERT */
  11144. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  11145. ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
  11146. IdList *pIdList; /* Column names for INSERT */
  11147. TriggerStep *pNext; /* Next in the link-list */
  11148. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  11149. };
  11150. /*
  11151. ** The following structure contains information used by the sqliteFix...
  11152. ** routines as they walk the parse tree to make database references
  11153. ** explicit.
  11154. */
  11155. typedef struct DbFixer DbFixer;
  11156. struct DbFixer {
  11157. Parse *pParse; /* The parsing context. Error messages written here */
  11158. Schema *pSchema; /* Fix items to this schema */
  11159. int bVarOnly; /* Check for variable references only */
  11160. const char *zDb; /* Make sure all objects are contained in this database */
  11161. const char *zType; /* Type of the container - used for error messages */
  11162. const Token *pName; /* Name of the container - used for error messages */
  11163. };
  11164. /*
  11165. ** An objected used to accumulate the text of a string where we
  11166. ** do not necessarily know how big the string will be in the end.
  11167. */
  11168. struct StrAccum {
  11169. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  11170. char *zBase; /* A base allocation. Not from malloc. */
  11171. char *zText; /* The string collected so far */
  11172. int nChar; /* Length of the string so far */
  11173. int nAlloc; /* Amount of space allocated in zText */
  11174. int mxAlloc; /* Maximum allowed string length */
  11175. u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
  11176. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  11177. };
  11178. #define STRACCUM_NOMEM 1
  11179. #define STRACCUM_TOOBIG 2
  11180. /*
  11181. ** A pointer to this structure is used to communicate information
  11182. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  11183. */
  11184. typedef struct {
  11185. sqlite3 *db; /* The database being initialized */
  11186. char **pzErrMsg; /* Error message stored here */
  11187. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  11188. int rc; /* Result code stored here */
  11189. } InitData;
  11190. /*
  11191. ** Structure containing global configuration data for the SQLite library.
  11192. **
  11193. ** This structure also contains some state information.
  11194. */
  11195. struct Sqlite3Config {
  11196. int bMemstat; /* True to enable memory status */
  11197. int bCoreMutex; /* True to enable core mutexing */
  11198. int bFullMutex; /* True to enable full mutexing */
  11199. int bOpenUri; /* True to interpret filenames as URIs */
  11200. int bUseCis; /* Use covering indices for full-scans */
  11201. int mxStrlen; /* Maximum string length */
  11202. int szLookaside; /* Default lookaside buffer size */
  11203. int nLookaside; /* Default lookaside buffer count */
  11204. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  11205. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  11206. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  11207. void *pHeap; /* Heap storage space */
  11208. int nHeap; /* Size of pHeap[] */
  11209. int mnReq, mxReq; /* Min and max heap requests sizes */
  11210. sqlite3_int64 szMmap; /* mmap() space per open file */
  11211. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  11212. void *pScratch; /* Scratch memory */
  11213. int szScratch; /* Size of each scratch buffer */
  11214. int nScratch; /* Number of scratch buffers */
  11215. void *pPage; /* Page cache memory */
  11216. int szPage; /* Size of each page in pPage[] */
  11217. int nPage; /* Number of pages in pPage[] */
  11218. int mxParserStack; /* maximum depth of the parser stack */
  11219. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  11220. /* The above might be initialized to non-zero. The following need to always
  11221. ** initially be zero, however. */
  11222. int isInit; /* True after initialization has finished */
  11223. int inProgress; /* True while initialization in progress */
  11224. int isMutexInit; /* True after mutexes are initialized */
  11225. int isMallocInit; /* True after malloc is initialized */
  11226. int isPCacheInit; /* True after malloc is initialized */
  11227. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  11228. int nRefInitMutex; /* Number of users of pInitMutex */
  11229. void (*xLog)(void*,int,const char*); /* Function for logging */
  11230. void *pLogArg; /* First argument to xLog() */
  11231. int bLocaltimeFault; /* True to fail localtime() calls */
  11232. #ifdef SQLITE_ENABLE_SQLLOG
  11233. void(*xSqllog)(void*,sqlite3*,const char*, int);
  11234. void *pSqllogArg;
  11235. #endif
  11236. };
  11237. /*
  11238. ** Context pointer passed down through the tree-walk.
  11239. */
  11240. struct Walker {
  11241. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  11242. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  11243. Parse *pParse; /* Parser context. */
  11244. int walkerDepth; /* Number of subqueries */
  11245. u8 bSelectDepthFirst; /* Do subqueries first */
  11246. union { /* Extra data for callback */
  11247. NameContext *pNC; /* Naming context */
  11248. int i; /* Integer value */
  11249. SrcList *pSrcList; /* FROM clause */
  11250. struct SrcCount *pSrcCount; /* Counting column references */
  11251. } u;
  11252. };
  11253. /* Forward declarations */
  11254. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  11255. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  11256. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  11257. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  11258. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  11259. /*
  11260. ** Return code from the parse-tree walking primitives and their
  11261. ** callbacks.
  11262. */
  11263. #define WRC_Continue 0 /* Continue down into children */
  11264. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  11265. #define WRC_Abort 2 /* Abandon the tree walk */
  11266. /*
  11267. ** Assuming zIn points to the first byte of a UTF-8 character,
  11268. ** advance zIn to point to the first byte of the next UTF-8 character.
  11269. */
  11270. #define SQLITE_SKIP_UTF8(zIn) { \
  11271. if( (*(zIn++))>=0xc0 ){ \
  11272. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  11273. } \
  11274. }
  11275. /*
  11276. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  11277. ** the same name but without the _BKPT suffix. These macros invoke
  11278. ** routines that report the line-number on which the error originated
  11279. ** using sqlite3_log(). The routines also provide a convenient place
  11280. ** to set a debugger breakpoint.
  11281. */
  11282. SQLITE_PRIVATE int sqlite3CorruptError(int);
  11283. SQLITE_PRIVATE int sqlite3MisuseError(int);
  11284. SQLITE_PRIVATE int sqlite3CantopenError(int);
  11285. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  11286. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  11287. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  11288. /*
  11289. ** FTS4 is really an extension for FTS3. It is enabled using the
  11290. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  11291. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  11292. */
  11293. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  11294. # define SQLITE_ENABLE_FTS3
  11295. #endif
  11296. /*
  11297. ** The ctype.h header is needed for non-ASCII systems. It is also
  11298. ** needed by FTS3 when FTS3 is included in the amalgamation.
  11299. */
  11300. #if !defined(SQLITE_ASCII) || \
  11301. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  11302. # include <ctype.h>
  11303. #endif
  11304. /*
  11305. ** The following macros mimic the standard library functions toupper(),
  11306. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  11307. ** sqlite versions only work for ASCII characters, regardless of locale.
  11308. */
  11309. #ifdef SQLITE_ASCII
  11310. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  11311. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  11312. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  11313. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  11314. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  11315. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  11316. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  11317. #else
  11318. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  11319. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  11320. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  11321. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  11322. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  11323. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  11324. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  11325. #endif
  11326. /*
  11327. ** Internal function prototypes
  11328. */
  11329. #define sqlite3StrICmp sqlite3_stricmp
  11330. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  11331. #define sqlite3StrNICmp sqlite3_strnicmp
  11332. SQLITE_PRIVATE int sqlite3MallocInit(void);
  11333. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  11334. SQLITE_PRIVATE void *sqlite3Malloc(int);
  11335. SQLITE_PRIVATE void *sqlite3MallocZero(int);
  11336. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
  11337. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
  11338. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  11339. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  11340. SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
  11341. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  11342. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
  11343. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  11344. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  11345. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  11346. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  11347. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  11348. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  11349. SQLITE_PRIVATE void sqlite3PageFree(void*);
  11350. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  11351. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  11352. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  11353. /*
  11354. ** On systems with ample stack space and that support alloca(), make
  11355. ** use of alloca() to obtain space for large automatic objects. By default,
  11356. ** obtain space from malloc().
  11357. **
  11358. ** The alloca() routine never returns NULL. This will cause code paths
  11359. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  11360. */
  11361. #ifdef SQLITE_USE_ALLOCA
  11362. # define sqlite3StackAllocRaw(D,N) alloca(N)
  11363. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  11364. # define sqlite3StackFree(D,P)
  11365. #else
  11366. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  11367. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  11368. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  11369. #endif
  11370. #ifdef SQLITE_ENABLE_MEMSYS3
  11371. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  11372. #endif
  11373. #ifdef SQLITE_ENABLE_MEMSYS5
  11374. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  11375. #endif
  11376. #ifndef SQLITE_MUTEX_OMIT
  11377. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  11378. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  11379. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  11380. SQLITE_PRIVATE int sqlite3MutexInit(void);
  11381. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  11382. #endif
  11383. SQLITE_PRIVATE int sqlite3StatusValue(int);
  11384. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  11385. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  11386. #ifndef SQLITE_OMIT_FLOATING_POINT
  11387. SQLITE_PRIVATE int sqlite3IsNaN(double);
  11388. #else
  11389. # define sqlite3IsNaN(X) 0
  11390. #endif
  11391. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
  11392. #ifndef SQLITE_OMIT_TRACE
  11393. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  11394. #endif
  11395. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  11396. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  11397. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  11398. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  11399. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  11400. #endif
  11401. #if defined(SQLITE_TEST)
  11402. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  11403. #endif
  11404. /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
  11405. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  11406. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe*);
  11407. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
  11408. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe*);
  11409. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe*);
  11410. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe*);
  11411. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe*);
  11412. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe*, Select*);
  11413. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe*, Expr*);
  11414. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe*, ExprList*);
  11415. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe*);
  11416. #else
  11417. # define sqlite3ExplainBegin(X)
  11418. # define sqlite3ExplainSelect(A,B)
  11419. # define sqlite3ExplainExpr(A,B)
  11420. # define sqlite3ExplainExprList(A,B)
  11421. # define sqlite3ExplainFinish(X)
  11422. # define sqlite3VdbeExplanation(X) 0
  11423. #endif
  11424. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  11425. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  11426. SQLITE_PRIVATE int sqlite3Dequote(char*);
  11427. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  11428. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  11429. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  11430. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  11431. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  11432. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  11433. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  11434. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  11435. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  11436. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  11437. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  11438. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  11439. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  11440. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  11441. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  11442. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  11443. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  11444. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  11445. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  11446. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  11447. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  11448. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  11449. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  11450. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  11451. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  11452. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  11453. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  11454. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  11455. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  11456. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  11457. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  11458. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  11459. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  11460. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  11461. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  11462. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  11463. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  11464. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  11465. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  11466. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  11467. sqlite3_vfs**,char**,char **);
  11468. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  11469. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  11470. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  11471. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  11472. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  11473. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  11474. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  11475. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  11476. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  11477. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  11478. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  11479. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  11480. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
  11481. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  11482. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  11483. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  11484. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  11485. #else
  11486. # define sqlite3ViewGetColumnNames(A,B) 0
  11487. #endif
  11488. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  11489. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  11490. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  11491. #ifndef SQLITE_OMIT_AUTOINCREMENT
  11492. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  11493. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  11494. #else
  11495. # define sqlite3AutoincrementBegin(X)
  11496. # define sqlite3AutoincrementEnd(X)
  11497. #endif
  11498. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
  11499. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  11500. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  11501. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  11502. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  11503. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  11504. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  11505. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  11506. Token*, Select*, Expr*, IdList*);
  11507. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  11508. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  11509. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  11510. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  11511. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  11512. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  11513. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  11514. Expr*, int, int);
  11515. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  11516. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  11517. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  11518. Expr*,ExprList*,u16,Expr*,Expr*);
  11519. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  11520. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  11521. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  11522. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  11523. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  11524. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  11525. #endif
  11526. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  11527. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  11528. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  11529. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  11530. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
  11531. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  11532. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  11533. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  11534. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  11535. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*);
  11536. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  11537. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  11538. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  11539. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  11540. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  11541. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
  11542. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  11543. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  11544. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  11545. SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
  11546. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  11547. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  11548. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  11549. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
  11550. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  11551. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  11552. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  11553. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  11554. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  11555. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  11556. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  11557. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  11558. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  11559. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  11560. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  11561. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  11562. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  11563. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  11564. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  11565. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  11566. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  11567. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  11568. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  11569. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  11570. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  11571. SQLITE_PRIVATE void sqlite3PrngResetState(void);
  11572. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  11573. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  11574. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  11575. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  11576. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  11577. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  11578. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  11579. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  11580. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  11581. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  11582. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  11583. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
  11584. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  11585. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  11586. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  11587. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  11588. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  11589. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
  11590. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  11591. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*);
  11592. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  11593. int*,int,int,int,int,int*);
  11594. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  11595. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  11596. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  11597. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  11598. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  11599. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, int);
  11600. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  11601. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  11602. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  11603. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  11604. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  11605. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  11606. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  11607. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  11608. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  11609. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  11610. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  11611. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  11612. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  11613. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  11614. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  11615. #endif
  11616. #ifndef SQLITE_OMIT_TRIGGER
  11617. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  11618. Expr*,int, int);
  11619. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  11620. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  11621. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  11622. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  11623. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  11624. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  11625. int, int, int);
  11626. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  11627. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  11628. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  11629. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  11630. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  11631. ExprList*,Select*,u8);
  11632. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  11633. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  11634. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  11635. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  11636. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  11637. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  11638. #else
  11639. # define sqlite3TriggersExist(B,C,D,E,F) 0
  11640. # define sqlite3DeleteTrigger(A,B)
  11641. # define sqlite3DropTriggerPtr(A,B)
  11642. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  11643. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  11644. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  11645. # define sqlite3TriggerList(X, Y) 0
  11646. # define sqlite3ParseToplevel(p) p
  11647. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  11648. #endif
  11649. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  11650. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  11651. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  11652. #ifndef SQLITE_OMIT_AUTHORIZATION
  11653. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  11654. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  11655. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  11656. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  11657. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  11658. #else
  11659. # define sqlite3AuthRead(a,b,c,d)
  11660. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  11661. # define sqlite3AuthContextPush(a,b,c)
  11662. # define sqlite3AuthContextPop(a) ((void)(a))
  11663. #endif
  11664. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  11665. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  11666. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  11667. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  11668. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  11669. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  11670. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  11671. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  11672. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  11673. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  11674. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  11675. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  11676. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  11677. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  11678. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  11679. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  11680. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11681. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  11682. #endif
  11683. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  11684. /*
  11685. ** Routines to read and write variable-length integers. These used to
  11686. ** be defined locally, but now we use the varint routines in the util.c
  11687. ** file. Code should use the MACRO forms below, as the Varint32 versions
  11688. ** are coded to assume the single byte case is already handled (which
  11689. ** the MACRO form does).
  11690. */
  11691. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  11692. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
  11693. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  11694. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  11695. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  11696. /*
  11697. ** The header of a record consists of a sequence variable-length integers.
  11698. ** These integers are almost always small and are encoded as a single byte.
  11699. ** The following macros take advantage this fact to provide a fast encode
  11700. ** and decode of the integers in a record header. It is faster for the common
  11701. ** case where the integer is a single byte. It is a little slower when the
  11702. ** integer is two or more bytes. But overall it is faster.
  11703. **
  11704. ** The following expressions are equivalent:
  11705. **
  11706. ** x = sqlite3GetVarint32( A, &B );
  11707. ** x = sqlite3PutVarint32( A, B );
  11708. **
  11709. ** x = getVarint32( A, B );
  11710. ** x = putVarint32( A, B );
  11711. **
  11712. */
  11713. #define getVarint32(A,B) \
  11714. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  11715. #define putVarint32(A,B) \
  11716. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  11717. sqlite3PutVarint32((A),(B)))
  11718. #define getVarint sqlite3GetVarint
  11719. #define putVarint sqlite3PutVarint
  11720. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  11721. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
  11722. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  11723. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  11724. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  11725. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  11726. SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
  11727. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  11728. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  11729. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  11730. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  11731. defined(SQLITE_DEBUG_OS_TRACE)
  11732. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  11733. #endif
  11734. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  11735. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  11736. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  11737. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  11738. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  11739. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
  11740. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  11741. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  11742. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  11743. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  11744. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  11745. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  11746. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  11747. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  11748. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  11749. #ifdef SQLITE_ENABLE_8_3_NAMES
  11750. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  11751. #else
  11752. # define sqlite3FileSuffix3(X,Y)
  11753. #endif
  11754. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
  11755. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  11756. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  11757. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  11758. void(*)(void*));
  11759. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  11760. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  11761. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  11762. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  11763. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  11764. #ifndef SQLITE_AMALGAMATION
  11765. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  11766. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  11767. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  11768. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  11769. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  11770. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  11771. #ifndef SQLITE_OMIT_WSD
  11772. SQLITE_PRIVATE int sqlite3PendingByte;
  11773. #endif
  11774. #endif
  11775. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  11776. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  11777. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  11778. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  11779. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  11780. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  11781. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  11782. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  11783. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  11784. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  11785. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  11786. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  11787. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  11788. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  11789. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  11790. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  11791. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  11792. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  11793. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  11794. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  11795. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  11796. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  11797. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  11798. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  11799. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  11800. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  11801. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  11802. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  11803. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  11804. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  11805. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  11806. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  11807. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int);
  11808. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  11809. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  11810. void (*)(sqlite3_context*,int,sqlite3_value **),
  11811. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  11812. FuncDestructor *pDestructor
  11813. );
  11814. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  11815. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  11816. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  11817. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  11818. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
  11819. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  11820. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  11821. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  11822. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  11823. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  11824. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  11825. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  11826. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  11827. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  11828. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  11829. #endif
  11830. /*
  11831. ** The interface to the LEMON-generated parser
  11832. */
  11833. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
  11834. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  11835. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  11836. #ifdef YYTRACKMAXSTACKDEPTH
  11837. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  11838. #endif
  11839. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  11840. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  11841. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  11842. #else
  11843. # define sqlite3CloseExtensions(X)
  11844. #endif
  11845. #ifndef SQLITE_OMIT_SHARED_CACHE
  11846. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  11847. #else
  11848. #define sqlite3TableLock(v,w,x,y,z)
  11849. #endif
  11850. #ifdef SQLITE_TEST
  11851. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  11852. #endif
  11853. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11854. # define sqlite3VtabClear(Y)
  11855. # define sqlite3VtabSync(X,Y) SQLITE_OK
  11856. # define sqlite3VtabRollback(X)
  11857. # define sqlite3VtabCommit(X)
  11858. # define sqlite3VtabInSync(db) 0
  11859. # define sqlite3VtabLock(X)
  11860. # define sqlite3VtabUnlock(X)
  11861. # define sqlite3VtabUnlockList(X)
  11862. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  11863. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  11864. #else
  11865. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  11866. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  11867. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  11868. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  11869. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  11870. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  11871. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  11872. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  11873. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  11874. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  11875. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  11876. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  11877. #endif
  11878. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  11879. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  11880. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  11881. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  11882. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  11883. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  11884. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  11885. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  11886. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  11887. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  11888. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  11889. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  11890. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  11891. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  11892. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  11893. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  11894. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  11895. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  11896. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  11897. #ifndef SQLITE_OMIT_WAL
  11898. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  11899. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  11900. #endif
  11901. /* Declarations for functions in fkey.c. All of these are replaced by
  11902. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  11903. ** key functionality is available. If OMIT_TRIGGER is defined but
  11904. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  11905. ** this case foreign keys are parsed, but no other functionality is
  11906. ** provided (enforcement of FK constraints requires the triggers sub-system).
  11907. */
  11908. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  11909. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  11910. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  11911. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  11912. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  11913. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  11914. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  11915. #else
  11916. #define sqlite3FkActions(a,b,c,d,e,f)
  11917. #define sqlite3FkCheck(a,b,c,d,e,f)
  11918. #define sqlite3FkDropTable(a,b,c)
  11919. #define sqlite3FkOldmask(a,b) 0
  11920. #define sqlite3FkRequired(a,b,c,d) 0
  11921. #endif
  11922. #ifndef SQLITE_OMIT_FOREIGN_KEY
  11923. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  11924. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  11925. #else
  11926. #define sqlite3FkDelete(a,b)
  11927. #define sqlite3FkLocateIndex(a,b,c,d,e)
  11928. #endif
  11929. /*
  11930. ** Available fault injectors. Should be numbered beginning with 0.
  11931. */
  11932. #define SQLITE_FAULTINJECTOR_MALLOC 0
  11933. #define SQLITE_FAULTINJECTOR_COUNT 1
  11934. /*
  11935. ** The interface to the code in fault.c used for identifying "benign"
  11936. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  11937. ** is not defined.
  11938. */
  11939. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11940. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  11941. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  11942. #else
  11943. #define sqlite3BeginBenignMalloc()
  11944. #define sqlite3EndBenignMalloc()
  11945. #endif
  11946. #define IN_INDEX_ROWID 1
  11947. #define IN_INDEX_EPH 2
  11948. #define IN_INDEX_INDEX_ASC 3
  11949. #define IN_INDEX_INDEX_DESC 4
  11950. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
  11951. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  11952. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  11953. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  11954. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  11955. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  11956. #else
  11957. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  11958. #define sqlite3JournalExists(p) 1
  11959. #endif
  11960. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  11961. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  11962. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  11963. #if SQLITE_MAX_EXPR_DEPTH>0
  11964. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  11965. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  11966. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  11967. #else
  11968. #define sqlite3ExprSetHeight(x,y)
  11969. #define sqlite3SelectExprHeight(x) 0
  11970. #define sqlite3ExprCheckHeight(x,y)
  11971. #endif
  11972. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  11973. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  11974. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  11975. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  11976. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  11977. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  11978. #else
  11979. #define sqlite3ConnectionBlocked(x,y)
  11980. #define sqlite3ConnectionUnlocked(x)
  11981. #define sqlite3ConnectionClosed(x)
  11982. #endif
  11983. #ifdef SQLITE_DEBUG
  11984. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  11985. #endif
  11986. /*
  11987. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  11988. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  11989. ** print I/O tracing messages.
  11990. */
  11991. #ifdef SQLITE_ENABLE_IOTRACE
  11992. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  11993. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  11994. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  11995. #else
  11996. # define IOTRACE(A)
  11997. # define sqlite3VdbeIOTraceSql(X)
  11998. #endif
  11999. /*
  12000. ** These routines are available for the mem2.c debugging memory allocator
  12001. ** only. They are used to verify that different "types" of memory
  12002. ** allocations are properly tracked by the system.
  12003. **
  12004. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  12005. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  12006. ** a single bit set.
  12007. **
  12008. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  12009. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12010. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  12011. **
  12012. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  12013. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12014. **
  12015. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  12016. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  12017. ** it might have been allocated by lookaside, except the allocation was
  12018. ** too large or lookaside was already full. It is important to verify
  12019. ** that allocations that might have been satisfied by lookaside are not
  12020. ** passed back to non-lookaside free() routines. Asserts such as the
  12021. ** example above are placed on the non-lookaside free() routines to verify
  12022. ** this constraint.
  12023. **
  12024. ** All of this is no-op for a production build. It only comes into
  12025. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  12026. */
  12027. #ifdef SQLITE_MEMDEBUG
  12028. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  12029. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  12030. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  12031. #else
  12032. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  12033. # define sqlite3MemdebugHasType(X,Y) 1
  12034. # define sqlite3MemdebugNoType(X,Y) 1
  12035. #endif
  12036. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  12037. #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
  12038. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  12039. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  12040. #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
  12041. #endif /* _SQLITEINT_H_ */
  12042. /************** End of sqliteInt.h *******************************************/
  12043. /************** Begin file global.c ******************************************/
  12044. /*
  12045. ** 2008 June 13
  12046. **
  12047. ** The author disclaims copyright to this source code. In place of
  12048. ** a legal notice, here is a blessing:
  12049. **
  12050. ** May you do good and not evil.
  12051. ** May you find forgiveness for yourself and forgive others.
  12052. ** May you share freely, never taking more than you give.
  12053. **
  12054. *************************************************************************
  12055. **
  12056. ** This file contains definitions of global variables and contants.
  12057. */
  12058. /* An array to map all upper-case characters into their corresponding
  12059. ** lower-case character.
  12060. **
  12061. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  12062. ** handle case conversions for the UTF character set since the tables
  12063. ** involved are nearly as big or bigger than SQLite itself.
  12064. */
  12065. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  12066. #ifdef SQLITE_ASCII
  12067. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  12068. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  12069. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  12070. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  12071. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  12072. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  12073. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  12074. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  12075. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  12076. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  12077. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  12078. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  12079. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  12080. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  12081. 252,253,254,255
  12082. #endif
  12083. #ifdef SQLITE_EBCDIC
  12084. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  12085. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  12086. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  12087. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  12088. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  12089. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  12090. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  12091. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  12092. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  12093. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  12094. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  12095. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  12096. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  12097. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  12098. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  12099. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  12100. #endif
  12101. };
  12102. /*
  12103. ** The following 256 byte lookup table is used to support SQLites built-in
  12104. ** equivalents to the following standard library functions:
  12105. **
  12106. ** isspace() 0x01
  12107. ** isalpha() 0x02
  12108. ** isdigit() 0x04
  12109. ** isalnum() 0x06
  12110. ** isxdigit() 0x08
  12111. ** toupper() 0x20
  12112. ** SQLite identifier character 0x40
  12113. **
  12114. ** Bit 0x20 is set if the mapped character requires translation to upper
  12115. ** case. i.e. if the character is a lower-case ASCII character.
  12116. ** If x is a lower-case ASCII character, then its upper-case equivalent
  12117. ** is (x - 0x20). Therefore toupper() can be implemented as:
  12118. **
  12119. ** (x & ~(map[x]&0x20))
  12120. **
  12121. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  12122. ** array. tolower() is used more often than toupper() by SQLite.
  12123. **
  12124. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  12125. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  12126. ** non-ASCII UTF character. Hence the test for whether or not a character is
  12127. ** part of an identifier is 0x46.
  12128. **
  12129. ** SQLite's versions are identical to the standard versions assuming a
  12130. ** locale of "C". They are implemented as macros in sqliteInt.h.
  12131. */
  12132. #ifdef SQLITE_ASCII
  12133. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  12134. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  12135. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  12136. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  12137. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  12138. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  12139. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  12140. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  12141. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  12142. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  12143. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  12144. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  12145. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  12146. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  12147. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  12148. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  12149. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  12150. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  12151. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  12152. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  12153. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  12154. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  12155. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  12156. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  12157. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  12158. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  12159. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  12160. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  12161. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  12162. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  12163. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  12164. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  12165. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  12166. };
  12167. #endif
  12168. #ifndef SQLITE_USE_URI
  12169. # define SQLITE_USE_URI 0
  12170. #endif
  12171. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  12172. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  12173. #endif
  12174. /*
  12175. ** The following singleton contains the global configuration for
  12176. ** the SQLite library.
  12177. */
  12178. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  12179. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  12180. 1, /* bCoreMutex */
  12181. SQLITE_THREADSAFE==1, /* bFullMutex */
  12182. SQLITE_USE_URI, /* bOpenUri */
  12183. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  12184. 0x7ffffffe, /* mxStrlen */
  12185. 128, /* szLookaside */
  12186. 500, /* nLookaside */
  12187. {0,0,0,0,0,0,0,0}, /* m */
  12188. {0,0,0,0,0,0,0,0,0}, /* mutex */
  12189. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  12190. (void*)0, /* pHeap */
  12191. 0, /* nHeap */
  12192. 0, 0, /* mnHeap, mxHeap */
  12193. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  12194. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  12195. (void*)0, /* pScratch */
  12196. 0, /* szScratch */
  12197. 0, /* nScratch */
  12198. (void*)0, /* pPage */
  12199. 0, /* szPage */
  12200. 0, /* nPage */
  12201. 0, /* mxParserStack */
  12202. 0, /* sharedCacheEnabled */
  12203. /* All the rest should always be initialized to zero */
  12204. 0, /* isInit */
  12205. 0, /* inProgress */
  12206. 0, /* isMutexInit */
  12207. 0, /* isMallocInit */
  12208. 0, /* isPCacheInit */
  12209. 0, /* pInitMutex */
  12210. 0, /* nRefInitMutex */
  12211. 0, /* xLog */
  12212. 0, /* pLogArg */
  12213. 0, /* bLocaltimeFault */
  12214. #ifdef SQLITE_ENABLE_SQLLOG
  12215. 0, /* xSqllog */
  12216. 0 /* pSqllogArg */
  12217. #endif
  12218. };
  12219. /*
  12220. ** Hash table for global functions - functions common to all
  12221. ** database connections. After initialization, this table is
  12222. ** read-only.
  12223. */
  12224. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12225. /*
  12226. ** Constant tokens for values 0 and 1.
  12227. */
  12228. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  12229. { "0", 1 },
  12230. { "1", 1 }
  12231. };
  12232. /*
  12233. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  12234. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  12235. ** the database page that contains the pending byte. It never attempts
  12236. ** to read or write that page. The pending byte page is set assign
  12237. ** for use by the VFS layers as space for managing file locks.
  12238. **
  12239. ** During testing, it is often desirable to move the pending byte to
  12240. ** a different position in the file. This allows code that has to
  12241. ** deal with the pending byte to run on files that are much smaller
  12242. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  12243. ** move the pending byte.
  12244. **
  12245. ** IMPORTANT: Changing the pending byte to any value other than
  12246. ** 0x40000000 results in an incompatible database file format!
  12247. ** Changing the pending byte during operating results in undefined
  12248. ** and dileterious behavior.
  12249. */
  12250. #ifndef SQLITE_OMIT_WSD
  12251. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  12252. #endif
  12253. /*
  12254. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  12255. ** created by mkopcodeh.awk during compilation. Data is obtained
  12256. ** from the comments following the "case OP_xxxx:" statements in
  12257. ** the vdbe.c file.
  12258. */
  12259. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  12260. /************** End of global.c **********************************************/
  12261. /************** Begin file ctime.c *******************************************/
  12262. /*
  12263. ** 2010 February 23
  12264. **
  12265. ** The author disclaims copyright to this source code. In place of
  12266. ** a legal notice, here is a blessing:
  12267. **
  12268. ** May you do good and not evil.
  12269. ** May you find forgiveness for yourself and forgive others.
  12270. ** May you share freely, never taking more than you give.
  12271. **
  12272. *************************************************************************
  12273. **
  12274. ** This file implements routines used to report what compile-time options
  12275. ** SQLite was built with.
  12276. */
  12277. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  12278. /*
  12279. ** An array of names of all compile-time options. This array should
  12280. ** be sorted A-Z.
  12281. **
  12282. ** This array looks large, but in a typical installation actually uses
  12283. ** only a handful of compile-time options, so most times this array is usually
  12284. ** rather short and uses little memory space.
  12285. */
  12286. static const char * const azCompileOpt[] = {
  12287. /* These macros are provided to "stringify" the value of the define
  12288. ** for those options in which the value is meaningful. */
  12289. #define CTIMEOPT_VAL_(opt) #opt
  12290. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  12291. #ifdef SQLITE_32BIT_ROWID
  12292. "32BIT_ROWID",
  12293. #endif
  12294. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  12295. "4_BYTE_ALIGNED_MALLOC",
  12296. #endif
  12297. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  12298. "CASE_SENSITIVE_LIKE",
  12299. #endif
  12300. #ifdef SQLITE_CHECK_PAGES
  12301. "CHECK_PAGES",
  12302. #endif
  12303. #ifdef SQLITE_COVERAGE_TEST
  12304. "COVERAGE_TEST",
  12305. #endif
  12306. #ifdef SQLITE_DEBUG
  12307. "DEBUG",
  12308. #endif
  12309. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  12310. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  12311. #endif
  12312. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  12313. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  12314. #endif
  12315. #ifdef SQLITE_DISABLE_DIRSYNC
  12316. "DISABLE_DIRSYNC",
  12317. #endif
  12318. #ifdef SQLITE_DISABLE_LFS
  12319. "DISABLE_LFS",
  12320. #endif
  12321. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  12322. "ENABLE_ATOMIC_WRITE",
  12323. #endif
  12324. #ifdef SQLITE_ENABLE_CEROD
  12325. "ENABLE_CEROD",
  12326. #endif
  12327. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  12328. "ENABLE_COLUMN_METADATA",
  12329. #endif
  12330. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  12331. "ENABLE_EXPENSIVE_ASSERT",
  12332. #endif
  12333. #ifdef SQLITE_ENABLE_FTS1
  12334. "ENABLE_FTS1",
  12335. #endif
  12336. #ifdef SQLITE_ENABLE_FTS2
  12337. "ENABLE_FTS2",
  12338. #endif
  12339. #ifdef SQLITE_ENABLE_FTS3
  12340. "ENABLE_FTS3",
  12341. #endif
  12342. #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  12343. "ENABLE_FTS3_PARENTHESIS",
  12344. #endif
  12345. #ifdef SQLITE_ENABLE_FTS4
  12346. "ENABLE_FTS4",
  12347. #endif
  12348. #ifdef SQLITE_ENABLE_ICU
  12349. "ENABLE_ICU",
  12350. #endif
  12351. #ifdef SQLITE_ENABLE_IOTRACE
  12352. "ENABLE_IOTRACE",
  12353. #endif
  12354. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  12355. "ENABLE_LOAD_EXTENSION",
  12356. #endif
  12357. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  12358. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  12359. #endif
  12360. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  12361. "ENABLE_MEMORY_MANAGEMENT",
  12362. #endif
  12363. #ifdef SQLITE_ENABLE_MEMSYS3
  12364. "ENABLE_MEMSYS3",
  12365. #endif
  12366. #ifdef SQLITE_ENABLE_MEMSYS5
  12367. "ENABLE_MEMSYS5",
  12368. #endif
  12369. #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  12370. "ENABLE_OVERSIZE_CELL_CHECK",
  12371. #endif
  12372. #ifdef SQLITE_ENABLE_RTREE
  12373. "ENABLE_RTREE",
  12374. #endif
  12375. #if defined(SQLITE_ENABLE_STAT4)
  12376. "ENABLE_STAT4",
  12377. #elif defined(SQLITE_ENABLE_STAT3)
  12378. "ENABLE_STAT3",
  12379. #endif
  12380. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  12381. "ENABLE_UNLOCK_NOTIFY",
  12382. #endif
  12383. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  12384. "ENABLE_UPDATE_DELETE_LIMIT",
  12385. #endif
  12386. #ifdef SQLITE_HAS_CODEC
  12387. "HAS_CODEC",
  12388. #endif
  12389. #ifdef SQLITE_HAVE_ISNAN
  12390. "HAVE_ISNAN",
  12391. #endif
  12392. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  12393. "HOMEGROWN_RECURSIVE_MUTEX",
  12394. #endif
  12395. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  12396. "IGNORE_AFP_LOCK_ERRORS",
  12397. #endif
  12398. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  12399. "IGNORE_FLOCK_LOCK_ERRORS",
  12400. #endif
  12401. #ifdef SQLITE_INT64_TYPE
  12402. "INT64_TYPE",
  12403. #endif
  12404. #ifdef SQLITE_LOCK_TRACE
  12405. "LOCK_TRACE",
  12406. #endif
  12407. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  12408. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  12409. #endif
  12410. #ifdef SQLITE_MAX_SCHEMA_RETRY
  12411. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  12412. #endif
  12413. #ifdef SQLITE_MEMDEBUG
  12414. "MEMDEBUG",
  12415. #endif
  12416. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  12417. "MIXED_ENDIAN_64BIT_FLOAT",
  12418. #endif
  12419. #ifdef SQLITE_NO_SYNC
  12420. "NO_SYNC",
  12421. #endif
  12422. #ifdef SQLITE_OMIT_ALTERTABLE
  12423. "OMIT_ALTERTABLE",
  12424. #endif
  12425. #ifdef SQLITE_OMIT_ANALYZE
  12426. "OMIT_ANALYZE",
  12427. #endif
  12428. #ifdef SQLITE_OMIT_ATTACH
  12429. "OMIT_ATTACH",
  12430. #endif
  12431. #ifdef SQLITE_OMIT_AUTHORIZATION
  12432. "OMIT_AUTHORIZATION",
  12433. #endif
  12434. #ifdef SQLITE_OMIT_AUTOINCREMENT
  12435. "OMIT_AUTOINCREMENT",
  12436. #endif
  12437. #ifdef SQLITE_OMIT_AUTOINIT
  12438. "OMIT_AUTOINIT",
  12439. #endif
  12440. #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
  12441. "OMIT_AUTOMATIC_INDEX",
  12442. #endif
  12443. #ifdef SQLITE_OMIT_AUTORESET
  12444. "OMIT_AUTORESET",
  12445. #endif
  12446. #ifdef SQLITE_OMIT_AUTOVACUUM
  12447. "OMIT_AUTOVACUUM",
  12448. #endif
  12449. #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  12450. "OMIT_BETWEEN_OPTIMIZATION",
  12451. #endif
  12452. #ifdef SQLITE_OMIT_BLOB_LITERAL
  12453. "OMIT_BLOB_LITERAL",
  12454. #endif
  12455. #ifdef SQLITE_OMIT_BTREECOUNT
  12456. "OMIT_BTREECOUNT",
  12457. #endif
  12458. #ifdef SQLITE_OMIT_BUILTIN_TEST
  12459. "OMIT_BUILTIN_TEST",
  12460. #endif
  12461. #ifdef SQLITE_OMIT_CAST
  12462. "OMIT_CAST",
  12463. #endif
  12464. #ifdef SQLITE_OMIT_CHECK
  12465. "OMIT_CHECK",
  12466. #endif
  12467. #ifdef SQLITE_OMIT_COMPLETE
  12468. "OMIT_COMPLETE",
  12469. #endif
  12470. #ifdef SQLITE_OMIT_COMPOUND_SELECT
  12471. "OMIT_COMPOUND_SELECT",
  12472. #endif
  12473. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  12474. "OMIT_DATETIME_FUNCS",
  12475. #endif
  12476. #ifdef SQLITE_OMIT_DECLTYPE
  12477. "OMIT_DECLTYPE",
  12478. #endif
  12479. #ifdef SQLITE_OMIT_DEPRECATED
  12480. "OMIT_DEPRECATED",
  12481. #endif
  12482. #ifdef SQLITE_OMIT_DISKIO
  12483. "OMIT_DISKIO",
  12484. #endif
  12485. #ifdef SQLITE_OMIT_EXPLAIN
  12486. "OMIT_EXPLAIN",
  12487. #endif
  12488. #ifdef SQLITE_OMIT_FLAG_PRAGMAS
  12489. "OMIT_FLAG_PRAGMAS",
  12490. #endif
  12491. #ifdef SQLITE_OMIT_FLOATING_POINT
  12492. "OMIT_FLOATING_POINT",
  12493. #endif
  12494. #ifdef SQLITE_OMIT_FOREIGN_KEY
  12495. "OMIT_FOREIGN_KEY",
  12496. #endif
  12497. #ifdef SQLITE_OMIT_GET_TABLE
  12498. "OMIT_GET_TABLE",
  12499. #endif
  12500. #ifdef SQLITE_OMIT_INCRBLOB
  12501. "OMIT_INCRBLOB",
  12502. #endif
  12503. #ifdef SQLITE_OMIT_INTEGRITY_CHECK
  12504. "OMIT_INTEGRITY_CHECK",
  12505. #endif
  12506. #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
  12507. "OMIT_LIKE_OPTIMIZATION",
  12508. #endif
  12509. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  12510. "OMIT_LOAD_EXTENSION",
  12511. #endif
  12512. #ifdef SQLITE_OMIT_LOCALTIME
  12513. "OMIT_LOCALTIME",
  12514. #endif
  12515. #ifdef SQLITE_OMIT_LOOKASIDE
  12516. "OMIT_LOOKASIDE",
  12517. #endif
  12518. #ifdef SQLITE_OMIT_MEMORYDB
  12519. "OMIT_MEMORYDB",
  12520. #endif
  12521. #ifdef SQLITE_OMIT_OR_OPTIMIZATION
  12522. "OMIT_OR_OPTIMIZATION",
  12523. #endif
  12524. #ifdef SQLITE_OMIT_PAGER_PRAGMAS
  12525. "OMIT_PAGER_PRAGMAS",
  12526. #endif
  12527. #ifdef SQLITE_OMIT_PRAGMA
  12528. "OMIT_PRAGMA",
  12529. #endif
  12530. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  12531. "OMIT_PROGRESS_CALLBACK",
  12532. #endif
  12533. #ifdef SQLITE_OMIT_QUICKBALANCE
  12534. "OMIT_QUICKBALANCE",
  12535. #endif
  12536. #ifdef SQLITE_OMIT_REINDEX
  12537. "OMIT_REINDEX",
  12538. #endif
  12539. #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
  12540. "OMIT_SCHEMA_PRAGMAS",
  12541. #endif
  12542. #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  12543. "OMIT_SCHEMA_VERSION_PRAGMAS",
  12544. #endif
  12545. #ifdef SQLITE_OMIT_SHARED_CACHE
  12546. "OMIT_SHARED_CACHE",
  12547. #endif
  12548. #ifdef SQLITE_OMIT_SUBQUERY
  12549. "OMIT_SUBQUERY",
  12550. #endif
  12551. #ifdef SQLITE_OMIT_TCL_VARIABLE
  12552. "OMIT_TCL_VARIABLE",
  12553. #endif
  12554. #ifdef SQLITE_OMIT_TEMPDB
  12555. "OMIT_TEMPDB",
  12556. #endif
  12557. #ifdef SQLITE_OMIT_TRACE
  12558. "OMIT_TRACE",
  12559. #endif
  12560. #ifdef SQLITE_OMIT_TRIGGER
  12561. "OMIT_TRIGGER",
  12562. #endif
  12563. #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  12564. "OMIT_TRUNCATE_OPTIMIZATION",
  12565. #endif
  12566. #ifdef SQLITE_OMIT_UTF16
  12567. "OMIT_UTF16",
  12568. #endif
  12569. #ifdef SQLITE_OMIT_VACUUM
  12570. "OMIT_VACUUM",
  12571. #endif
  12572. #ifdef SQLITE_OMIT_VIEW
  12573. "OMIT_VIEW",
  12574. #endif
  12575. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12576. "OMIT_VIRTUALTABLE",
  12577. #endif
  12578. #ifdef SQLITE_OMIT_WAL
  12579. "OMIT_WAL",
  12580. #endif
  12581. #ifdef SQLITE_OMIT_WSD
  12582. "OMIT_WSD",
  12583. #endif
  12584. #ifdef SQLITE_OMIT_XFER_OPT
  12585. "OMIT_XFER_OPT",
  12586. #endif
  12587. #ifdef SQLITE_PERFORMANCE_TRACE
  12588. "PERFORMANCE_TRACE",
  12589. #endif
  12590. #ifdef SQLITE_PROXY_DEBUG
  12591. "PROXY_DEBUG",
  12592. #endif
  12593. #ifdef SQLITE_RTREE_INT_ONLY
  12594. "RTREE_INT_ONLY",
  12595. #endif
  12596. #ifdef SQLITE_SECURE_DELETE
  12597. "SECURE_DELETE",
  12598. #endif
  12599. #ifdef SQLITE_SMALL_STACK
  12600. "SMALL_STACK",
  12601. #endif
  12602. #ifdef SQLITE_SOUNDEX
  12603. "SOUNDEX",
  12604. #endif
  12605. #ifdef SQLITE_TCL
  12606. "TCL",
  12607. #endif
  12608. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  12609. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  12610. #endif
  12611. #ifdef SQLITE_TEST
  12612. "TEST",
  12613. #endif
  12614. #if defined(SQLITE_THREADSAFE)
  12615. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  12616. #endif
  12617. #ifdef SQLITE_USE_ALLOCA
  12618. "USE_ALLOCA",
  12619. #endif
  12620. #ifdef SQLITE_ZERO_MALLOC
  12621. "ZERO_MALLOC"
  12622. #endif
  12623. };
  12624. /*
  12625. ** Given the name of a compile-time option, return true if that option
  12626. ** was used and false if not.
  12627. **
  12628. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  12629. ** is not required for a match.
  12630. */
  12631. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  12632. int i, n;
  12633. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  12634. n = sqlite3Strlen30(zOptName);
  12635. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  12636. ** linear search is adequate. No need for a binary search. */
  12637. for(i=0; i<ArraySize(azCompileOpt); i++){
  12638. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  12639. && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
  12640. ){
  12641. return 1;
  12642. }
  12643. }
  12644. return 0;
  12645. }
  12646. /*
  12647. ** Return the N-th compile-time option string. If N is out of range,
  12648. ** return a NULL pointer.
  12649. */
  12650. SQLITE_API const char *sqlite3_compileoption_get(int N){
  12651. if( N>=0 && N<ArraySize(azCompileOpt) ){
  12652. return azCompileOpt[N];
  12653. }
  12654. return 0;
  12655. }
  12656. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  12657. /************** End of ctime.c ***********************************************/
  12658. /************** Begin file status.c ******************************************/
  12659. /*
  12660. ** 2008 June 18
  12661. **
  12662. ** The author disclaims copyright to this source code. In place of
  12663. ** a legal notice, here is a blessing:
  12664. **
  12665. ** May you do good and not evil.
  12666. ** May you find forgiveness for yourself and forgive others.
  12667. ** May you share freely, never taking more than you give.
  12668. **
  12669. *************************************************************************
  12670. **
  12671. ** This module implements the sqlite3_status() interface and related
  12672. ** functionality.
  12673. */
  12674. /************** Include vdbeInt.h in the middle of status.c ******************/
  12675. /************** Begin file vdbeInt.h *****************************************/
  12676. /*
  12677. ** 2003 September 6
  12678. **
  12679. ** The author disclaims copyright to this source code. In place of
  12680. ** a legal notice, here is a blessing:
  12681. **
  12682. ** May you do good and not evil.
  12683. ** May you find forgiveness for yourself and forgive others.
  12684. ** May you share freely, never taking more than you give.
  12685. **
  12686. *************************************************************************
  12687. ** This is the header file for information that is private to the
  12688. ** VDBE. This information used to all be at the top of the single
  12689. ** source code file "vdbe.c". When that file became too big (over
  12690. ** 6000 lines long) it was split up into several smaller files and
  12691. ** this header information was factored out.
  12692. */
  12693. #ifndef _VDBEINT_H_
  12694. #define _VDBEINT_H_
  12695. /*
  12696. ** The maximum number of times that a statement will try to reparse
  12697. ** itself before giving up and returning SQLITE_SCHEMA.
  12698. */
  12699. #ifndef SQLITE_MAX_SCHEMA_RETRY
  12700. # define SQLITE_MAX_SCHEMA_RETRY 50
  12701. #endif
  12702. /*
  12703. ** SQL is translated into a sequence of instructions to be
  12704. ** executed by a virtual machine. Each instruction is an instance
  12705. ** of the following structure.
  12706. */
  12707. typedef struct VdbeOp Op;
  12708. /*
  12709. ** Boolean values
  12710. */
  12711. typedef unsigned char Bool;
  12712. /* Opaque type used by code in vdbesort.c */
  12713. typedef struct VdbeSorter VdbeSorter;
  12714. /* Opaque type used by the explainer */
  12715. typedef struct Explain Explain;
  12716. /* Elements of the linked list at Vdbe.pAuxData */
  12717. typedef struct AuxData AuxData;
  12718. /*
  12719. ** A cursor is a pointer into a single BTree within a database file.
  12720. ** The cursor can seek to a BTree entry with a particular key, or
  12721. ** loop over all entries of the Btree. You can also insert new BTree
  12722. ** entries or retrieve the key or data from the entry that the cursor
  12723. ** is currently pointing to.
  12724. **
  12725. ** Every cursor that the virtual machine has open is represented by an
  12726. ** instance of the following structure.
  12727. */
  12728. struct VdbeCursor {
  12729. BtCursor *pCursor; /* The cursor structure of the backend */
  12730. Btree *pBt; /* Separate file holding temporary table */
  12731. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  12732. int iDb; /* Index of cursor database in db->aDb[] (or -1) */
  12733. int pseudoTableReg; /* Register holding pseudotable content. */
  12734. int nField; /* Number of fields in the header */
  12735. Bool zeroed; /* True if zeroed out and ready for reuse */
  12736. Bool rowidIsValid; /* True if lastRowid is valid */
  12737. Bool atFirst; /* True if pointing to first entry */
  12738. Bool useRandomRowid; /* Generate new record numbers semi-randomly */
  12739. Bool nullRow; /* True if pointing to a row with no data */
  12740. Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  12741. Bool isTable; /* True if a table requiring integer keys */
  12742. Bool isIndex; /* True if an index containing keys only - no data */
  12743. Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
  12744. Bool isSorter; /* True if a new-style sorter */
  12745. Bool multiPseudo; /* Multi-register pseudo-cursor */
  12746. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  12747. const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
  12748. i64 seqCount; /* Sequence counter */
  12749. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  12750. i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
  12751. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  12752. /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
  12753. ** OP_IsUnique opcode on this cursor. */
  12754. int seekResult;
  12755. /* Cached information about the header for the data record that the
  12756. ** cursor is currently pointing to. Only valid if cacheStatus matches
  12757. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  12758. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  12759. ** the cache is out of date.
  12760. **
  12761. ** aRow might point to (ephemeral) data for the current row, or it might
  12762. ** be NULL.
  12763. */
  12764. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  12765. int payloadSize; /* Total number of bytes in the record */
  12766. u32 *aType; /* Type values for all entries in the record */
  12767. u32 *aOffset; /* Cached offsets to the start of each columns data */
  12768. u8 *aRow; /* Data for the current row, if all on one page */
  12769. };
  12770. typedef struct VdbeCursor VdbeCursor;
  12771. /*
  12772. ** When a sub-program is executed (OP_Program), a structure of this type
  12773. ** is allocated to store the current value of the program counter, as
  12774. ** well as the current memory cell array and various other frame specific
  12775. ** values stored in the Vdbe struct. When the sub-program is finished,
  12776. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  12777. ** restoring the state of the VM to as it was before the sub-program
  12778. ** began executing.
  12779. **
  12780. ** The memory for a VdbeFrame object is allocated and managed by a memory
  12781. ** cell in the parent (calling) frame. When the memory cell is deleted or
  12782. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  12783. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  12784. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  12785. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  12786. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  12787. ** child frame are released.
  12788. **
  12789. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  12790. ** set to NULL if the currently executing frame is the main program.
  12791. */
  12792. typedef struct VdbeFrame VdbeFrame;
  12793. struct VdbeFrame {
  12794. Vdbe *v; /* VM this frame belongs to */
  12795. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  12796. Op *aOp; /* Program instructions for parent frame */
  12797. Mem *aMem; /* Array of memory cells for parent frame */
  12798. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  12799. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  12800. void *token; /* Copy of SubProgram.token */
  12801. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  12802. int nCursor; /* Number of entries in apCsr */
  12803. int pc; /* Program Counter in parent (calling) frame */
  12804. int nOp; /* Size of aOp array */
  12805. int nMem; /* Number of entries in aMem */
  12806. int nOnceFlag; /* Number of entries in aOnceFlag */
  12807. int nChildMem; /* Number of memory cells for child frame */
  12808. int nChildCsr; /* Number of cursors for child frame */
  12809. int nChange; /* Statement changes (Vdbe.nChanges) */
  12810. };
  12811. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  12812. /*
  12813. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  12814. */
  12815. #define CACHE_STALE 0
  12816. /*
  12817. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  12818. ** structures. Each Mem struct may cache multiple representations (string,
  12819. ** integer etc.) of the same value.
  12820. */
  12821. struct Mem {
  12822. sqlite3 *db; /* The associated database connection */
  12823. char *z; /* String or BLOB value */
  12824. double r; /* Real value */
  12825. union {
  12826. i64 i; /* Integer value used when MEM_Int is set in flags */
  12827. int nZero; /* Used when bit MEM_Zero is set in flags */
  12828. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  12829. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  12830. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  12831. } u;
  12832. int n; /* Number of characters in string value, excluding '\0' */
  12833. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  12834. u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
  12835. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  12836. #ifdef SQLITE_DEBUG
  12837. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  12838. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  12839. #endif
  12840. void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
  12841. char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
  12842. };
  12843. /* One or more of the following flags are set to indicate the validOK
  12844. ** representations of the value stored in the Mem struct.
  12845. **
  12846. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  12847. ** No other flags may be set in this case.
  12848. **
  12849. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  12850. ** Usually this is encoded in the same unicode encoding as the main
  12851. ** database (see below for exceptions). If the MEM_Term flag is also
  12852. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  12853. ** flags may coexist with the MEM_Str flag.
  12854. */
  12855. #define MEM_Null 0x0001 /* Value is NULL */
  12856. #define MEM_Str 0x0002 /* Value is a string */
  12857. #define MEM_Int 0x0004 /* Value is an integer */
  12858. #define MEM_Real 0x0008 /* Value is a real number */
  12859. #define MEM_Blob 0x0010 /* Value is a BLOB */
  12860. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  12861. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  12862. #define MEM_Invalid 0x0080 /* Value is undefined */
  12863. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  12864. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  12865. /* Whenever Mem contains a valid string or blob representation, one of
  12866. ** the following flags must be set to determine the memory management
  12867. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  12868. ** string is \000 or \u0000 terminated
  12869. */
  12870. #define MEM_Term 0x0200 /* String rep is nul terminated */
  12871. #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
  12872. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  12873. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  12874. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  12875. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  12876. #ifdef SQLITE_OMIT_INCRBLOB
  12877. #undef MEM_Zero
  12878. #define MEM_Zero 0x0000
  12879. #endif
  12880. /*
  12881. ** Clear any existing type flags from a Mem and replace them with f
  12882. */
  12883. #define MemSetTypeFlag(p, f) \
  12884. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  12885. /*
  12886. ** Return true if a memory cell is not marked as invalid. This macro
  12887. ** is for use inside assert() statements only.
  12888. */
  12889. #ifdef SQLITE_DEBUG
  12890. #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
  12891. #endif
  12892. /*
  12893. ** Each auxilliary data pointer stored by a user defined function
  12894. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  12895. ** of this structure. All such structures associated with a single VM
  12896. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  12897. ** when the VM is halted (if not before).
  12898. */
  12899. struct AuxData {
  12900. int iOp; /* Instruction number of OP_Function opcode */
  12901. int iArg; /* Index of function argument. */
  12902. void *pAux; /* Aux data pointer */
  12903. void (*xDelete)(void *); /* Destructor for the aux data */
  12904. AuxData *pNext; /* Next element in list */
  12905. };
  12906. /*
  12907. ** The "context" argument for a installable function. A pointer to an
  12908. ** instance of this structure is the first argument to the routines used
  12909. ** implement the SQL functions.
  12910. **
  12911. ** There is a typedef for this structure in sqlite.h. So all routines,
  12912. ** even the public interface to SQLite, can use a pointer to this structure.
  12913. ** But this file is the only place where the internal details of this
  12914. ** structure are known.
  12915. **
  12916. ** This structure is defined inside of vdbeInt.h because it uses substructures
  12917. ** (Mem) which are only defined there.
  12918. */
  12919. struct sqlite3_context {
  12920. FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
  12921. Mem s; /* The return value is stored here */
  12922. Mem *pMem; /* Memory cell used to store aggregate context */
  12923. CollSeq *pColl; /* Collating sequence */
  12924. Vdbe *pVdbe; /* The VM that owns this context */
  12925. int iOp; /* Instruction number of OP_Function */
  12926. int isError; /* Error code returned by the function. */
  12927. u8 skipFlag; /* Skip skip accumulator loading if true */
  12928. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  12929. };
  12930. /*
  12931. ** An Explain object accumulates indented output which is helpful
  12932. ** in describing recursive data structures.
  12933. */
  12934. struct Explain {
  12935. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  12936. StrAccum str; /* The string being accumulated */
  12937. int nIndent; /* Number of elements in aIndent */
  12938. u16 aIndent[100]; /* Levels of indentation */
  12939. char zBase[100]; /* Initial space */
  12940. };
  12941. /* A bitfield type for use inside of structures. Always follow with :N where
  12942. ** N is the number of bits.
  12943. */
  12944. typedef unsigned bft; /* Bit Field Type */
  12945. /*
  12946. ** An instance of the virtual machine. This structure contains the complete
  12947. ** state of the virtual machine.
  12948. **
  12949. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  12950. ** is really a pointer to an instance of this structure.
  12951. **
  12952. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  12953. ** any virtual table method invocations made by the vdbe program. It is
  12954. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  12955. ** variable is used for two purposes: to allow xDestroy methods to execute
  12956. ** "DROP TABLE" statements and to prevent some nasty side effects of
  12957. ** malloc failure when SQLite is invoked recursively by a virtual table
  12958. ** method function.
  12959. */
  12960. struct Vdbe {
  12961. sqlite3 *db; /* The database connection that owns this statement */
  12962. Op *aOp; /* Space to hold the virtual machine's program */
  12963. Mem *aMem; /* The memory locations */
  12964. Mem **apArg; /* Arguments to currently executing user function */
  12965. Mem *aColName; /* Column names to return */
  12966. Mem *pResultSet; /* Pointer to an array of results */
  12967. int nMem; /* Number of memory locations currently allocated */
  12968. int nOp; /* Number of instructions in the program */
  12969. int nOpAlloc; /* Number of slots allocated for aOp[] */
  12970. int nLabel; /* Number of labels used */
  12971. int *aLabel; /* Space to hold the labels */
  12972. u16 nResColumn; /* Number of columns in one row of the result set */
  12973. int nCursor; /* Number of slots in apCsr[] */
  12974. u32 magic; /* Magic number for sanity checking */
  12975. char *zErrMsg; /* Error message written here */
  12976. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  12977. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  12978. Mem *aVar; /* Values for the OP_Variable opcode. */
  12979. char **azVar; /* Name of variables */
  12980. ynVar nVar; /* Number of entries in aVar[] */
  12981. ynVar nzVar; /* Number of entries in azVar[] */
  12982. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  12983. int pc; /* The program counter */
  12984. int rc; /* Value to return */
  12985. u8 errorAction; /* Recovery action to do in case of an error */
  12986. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  12987. bft explain:2; /* True if EXPLAIN present on SQL command */
  12988. bft inVtabMethod:2; /* See comments above */
  12989. bft changeCntOn:1; /* True to update the change-counter */
  12990. bft expired:1; /* True if the VM needs to be recompiled */
  12991. bft runOnlyOnce:1; /* Automatically expire on reset */
  12992. bft usesStmtJournal:1; /* True if uses a statement journal */
  12993. bft readOnly:1; /* True for statements that do not write */
  12994. bft bIsReader:1; /* True for statements that read */
  12995. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  12996. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  12997. int nChange; /* Number of db changes made since last reset */
  12998. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  12999. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  13000. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  13001. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  13002. #ifndef SQLITE_OMIT_TRACE
  13003. i64 startTime; /* Time when query started - used for profiling */
  13004. #endif
  13005. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  13006. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  13007. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  13008. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  13009. char *zSql; /* Text of the SQL statement that generated this */
  13010. void *pFree; /* Free this when deleting the vdbe */
  13011. #ifdef SQLITE_DEBUG
  13012. FILE *trace; /* Write an execution trace here, if not NULL */
  13013. #endif
  13014. #ifdef SQLITE_ENABLE_TREE_EXPLAIN
  13015. Explain *pExplain; /* The explainer */
  13016. char *zExplain; /* Explanation of data structures */
  13017. #endif
  13018. VdbeFrame *pFrame; /* Parent frame */
  13019. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  13020. int nFrame; /* Number of frames in pFrame list */
  13021. u32 expmask; /* Binding to these vars invalidates VM */
  13022. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  13023. int nOnceFlag; /* Size of array aOnceFlag[] */
  13024. u8 *aOnceFlag; /* Flags for OP_Once */
  13025. AuxData *pAuxData; /* Linked list of auxdata allocations */
  13026. };
  13027. /*
  13028. ** The following are allowed values for Vdbe.magic
  13029. */
  13030. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  13031. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  13032. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  13033. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  13034. /*
  13035. ** Function prototypes
  13036. */
  13037. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  13038. void sqliteVdbePopStack(Vdbe*,int);
  13039. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  13040. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  13041. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  13042. #endif
  13043. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  13044. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  13045. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
  13046. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  13047. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
  13048. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  13049. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
  13050. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
  13051. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  13052. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  13053. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  13054. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  13055. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  13056. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  13057. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  13058. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  13059. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  13060. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  13061. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  13062. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  13063. #ifdef SQLITE_OMIT_FLOATING_POINT
  13064. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  13065. #else
  13066. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  13067. #endif
  13068. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  13069. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  13070. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  13071. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  13072. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
  13073. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  13074. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  13075. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  13076. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  13077. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  13078. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  13079. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
  13080. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  13081. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
  13082. #define VdbeMemRelease(X) \
  13083. if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
  13084. sqlite3VdbeMemReleaseExternal(X);
  13085. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  13086. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  13087. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  13088. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  13089. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  13090. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  13091. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
  13092. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  13093. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
  13094. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  13095. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  13096. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  13097. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
  13098. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
  13099. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
  13100. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  13101. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  13102. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  13103. #else
  13104. # define sqlite3VdbeEnter(X)
  13105. # define sqlite3VdbeLeave(X)
  13106. #endif
  13107. #ifdef SQLITE_DEBUG
  13108. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  13109. #endif
  13110. #ifndef SQLITE_OMIT_FOREIGN_KEY
  13111. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  13112. #else
  13113. # define sqlite3VdbeCheckFk(p,i) 0
  13114. #endif
  13115. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  13116. #ifdef SQLITE_DEBUG
  13117. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  13118. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  13119. #endif
  13120. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  13121. #ifndef SQLITE_OMIT_INCRBLOB
  13122. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  13123. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  13124. #else
  13125. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  13126. #define ExpandBlob(P) SQLITE_OK
  13127. #endif
  13128. #endif /* !defined(_VDBEINT_H_) */
  13129. /************** End of vdbeInt.h *********************************************/
  13130. /************** Continuing where we left off in status.c *********************/
  13131. /*
  13132. ** Variables in which to record status information.
  13133. */
  13134. typedef struct sqlite3StatType sqlite3StatType;
  13135. static SQLITE_WSD struct sqlite3StatType {
  13136. int nowValue[10]; /* Current value */
  13137. int mxValue[10]; /* Maximum value */
  13138. } sqlite3Stat = { {0,}, {0,} };
  13139. /* The "wsdStat" macro will resolve to the status information
  13140. ** state vector. If writable static data is unsupported on the target,
  13141. ** we have to locate the state vector at run-time. In the more common
  13142. ** case where writable static data is supported, wsdStat can refer directly
  13143. ** to the "sqlite3Stat" state vector declared above.
  13144. */
  13145. #ifdef SQLITE_OMIT_WSD
  13146. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  13147. # define wsdStat x[0]
  13148. #else
  13149. # define wsdStatInit
  13150. # define wsdStat sqlite3Stat
  13151. #endif
  13152. /*
  13153. ** Return the current value of a status parameter.
  13154. */
  13155. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  13156. wsdStatInit;
  13157. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13158. return wsdStat.nowValue[op];
  13159. }
  13160. /*
  13161. ** Add N to the value of a status record. It is assumed that the
  13162. ** caller holds appropriate locks.
  13163. */
  13164. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  13165. wsdStatInit;
  13166. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13167. wsdStat.nowValue[op] += N;
  13168. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13169. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13170. }
  13171. }
  13172. /*
  13173. ** Set the value of a status to X.
  13174. */
  13175. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  13176. wsdStatInit;
  13177. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13178. wsdStat.nowValue[op] = X;
  13179. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13180. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13181. }
  13182. }
  13183. /*
  13184. ** Query status information.
  13185. **
  13186. ** This implementation assumes that reading or writing an aligned
  13187. ** 32-bit integer is an atomic operation. If that assumption is not true,
  13188. ** then this routine is not threadsafe.
  13189. */
  13190. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  13191. wsdStatInit;
  13192. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  13193. return SQLITE_MISUSE_BKPT;
  13194. }
  13195. *pCurrent = wsdStat.nowValue[op];
  13196. *pHighwater = wsdStat.mxValue[op];
  13197. if( resetFlag ){
  13198. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13199. }
  13200. return SQLITE_OK;
  13201. }
  13202. /*
  13203. ** Query status information for a single database connection
  13204. */
  13205. SQLITE_API int sqlite3_db_status(
  13206. sqlite3 *db, /* The database connection whose status is desired */
  13207. int op, /* Status verb */
  13208. int *pCurrent, /* Write current value here */
  13209. int *pHighwater, /* Write high-water mark here */
  13210. int resetFlag /* Reset high-water mark if true */
  13211. ){
  13212. int rc = SQLITE_OK; /* Return code */
  13213. sqlite3_mutex_enter(db->mutex);
  13214. switch( op ){
  13215. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  13216. *pCurrent = db->lookaside.nOut;
  13217. *pHighwater = db->lookaside.mxOut;
  13218. if( resetFlag ){
  13219. db->lookaside.mxOut = db->lookaside.nOut;
  13220. }
  13221. break;
  13222. }
  13223. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  13224. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  13225. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  13226. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  13227. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  13228. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  13229. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  13230. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  13231. *pCurrent = 0;
  13232. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  13233. if( resetFlag ){
  13234. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  13235. }
  13236. break;
  13237. }
  13238. /*
  13239. ** Return an approximation for the amount of memory currently used
  13240. ** by all pagers associated with the given database connection. The
  13241. ** highwater mark is meaningless and is returned as zero.
  13242. */
  13243. case SQLITE_DBSTATUS_CACHE_USED: {
  13244. int totalUsed = 0;
  13245. int i;
  13246. sqlite3BtreeEnterAll(db);
  13247. for(i=0; i<db->nDb; i++){
  13248. Btree *pBt = db->aDb[i].pBt;
  13249. if( pBt ){
  13250. Pager *pPager = sqlite3BtreePager(pBt);
  13251. totalUsed += sqlite3PagerMemUsed(pPager);
  13252. }
  13253. }
  13254. sqlite3BtreeLeaveAll(db);
  13255. *pCurrent = totalUsed;
  13256. *pHighwater = 0;
  13257. break;
  13258. }
  13259. /*
  13260. ** *pCurrent gets an accurate estimate of the amount of memory used
  13261. ** to store the schema for all databases (main, temp, and any ATTACHed
  13262. ** databases. *pHighwater is set to zero.
  13263. */
  13264. case SQLITE_DBSTATUS_SCHEMA_USED: {
  13265. int i; /* Used to iterate through schemas */
  13266. int nByte = 0; /* Used to accumulate return value */
  13267. sqlite3BtreeEnterAll(db);
  13268. db->pnBytesFreed = &nByte;
  13269. for(i=0; i<db->nDb; i++){
  13270. Schema *pSchema = db->aDb[i].pSchema;
  13271. if( ALWAYS(pSchema!=0) ){
  13272. HashElem *p;
  13273. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  13274. pSchema->tblHash.count
  13275. + pSchema->trigHash.count
  13276. + pSchema->idxHash.count
  13277. + pSchema->fkeyHash.count
  13278. );
  13279. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  13280. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  13281. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  13282. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  13283. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  13284. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  13285. }
  13286. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  13287. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  13288. }
  13289. }
  13290. }
  13291. db->pnBytesFreed = 0;
  13292. sqlite3BtreeLeaveAll(db);
  13293. *pHighwater = 0;
  13294. *pCurrent = nByte;
  13295. break;
  13296. }
  13297. /*
  13298. ** *pCurrent gets an accurate estimate of the amount of memory used
  13299. ** to store all prepared statements.
  13300. ** *pHighwater is set to zero.
  13301. */
  13302. case SQLITE_DBSTATUS_STMT_USED: {
  13303. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  13304. int nByte = 0; /* Used to accumulate return value */
  13305. db->pnBytesFreed = &nByte;
  13306. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  13307. sqlite3VdbeClearObject(db, pVdbe);
  13308. sqlite3DbFree(db, pVdbe);
  13309. }
  13310. db->pnBytesFreed = 0;
  13311. *pHighwater = 0;
  13312. *pCurrent = nByte;
  13313. break;
  13314. }
  13315. /*
  13316. ** Set *pCurrent to the total cache hits or misses encountered by all
  13317. ** pagers the database handle is connected to. *pHighwater is always set
  13318. ** to zero.
  13319. */
  13320. case SQLITE_DBSTATUS_CACHE_HIT:
  13321. case SQLITE_DBSTATUS_CACHE_MISS:
  13322. case SQLITE_DBSTATUS_CACHE_WRITE:{
  13323. int i;
  13324. int nRet = 0;
  13325. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  13326. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  13327. for(i=0; i<db->nDb; i++){
  13328. if( db->aDb[i].pBt ){
  13329. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  13330. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  13331. }
  13332. }
  13333. *pHighwater = 0;
  13334. *pCurrent = nRet;
  13335. break;
  13336. }
  13337. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  13338. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  13339. ** have been satisfied. The *pHighwater is always set to zero.
  13340. */
  13341. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  13342. *pHighwater = 0;
  13343. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  13344. break;
  13345. }
  13346. default: {
  13347. rc = SQLITE_ERROR;
  13348. }
  13349. }
  13350. sqlite3_mutex_leave(db->mutex);
  13351. return rc;
  13352. }
  13353. /************** End of status.c **********************************************/
  13354. /************** Begin file date.c ********************************************/
  13355. /*
  13356. ** 2003 October 31
  13357. **
  13358. ** The author disclaims copyright to this source code. In place of
  13359. ** a legal notice, here is a blessing:
  13360. **
  13361. ** May you do good and not evil.
  13362. ** May you find forgiveness for yourself and forgive others.
  13363. ** May you share freely, never taking more than you give.
  13364. **
  13365. *************************************************************************
  13366. ** This file contains the C functions that implement date and time
  13367. ** functions for SQLite.
  13368. **
  13369. ** There is only one exported symbol in this file - the function
  13370. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  13371. ** All other code has file scope.
  13372. **
  13373. ** SQLite processes all times and dates as Julian Day numbers. The
  13374. ** dates and times are stored as the number of days since noon
  13375. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  13376. ** calendar system.
  13377. **
  13378. ** 1970-01-01 00:00:00 is JD 2440587.5
  13379. ** 2000-01-01 00:00:00 is JD 2451544.5
  13380. **
  13381. ** This implemention requires years to be expressed as a 4-digit number
  13382. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  13383. ** be represented, even though julian day numbers allow a much wider
  13384. ** range of dates.
  13385. **
  13386. ** The Gregorian calendar system is used for all dates and times,
  13387. ** even those that predate the Gregorian calendar. Historians usually
  13388. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  13389. ** dates afterwards, depending on locale. Beware of this difference.
  13390. **
  13391. ** The conversion algorithms are implemented based on descriptions
  13392. ** in the following text:
  13393. **
  13394. ** Jean Meeus
  13395. ** Astronomical Algorithms, 2nd Edition, 1998
  13396. ** ISBM 0-943396-61-1
  13397. ** Willmann-Bell, Inc
  13398. ** Richmond, Virginia (USA)
  13399. */
  13400. /* #include <stdlib.h> */
  13401. /* #include <assert.h> */
  13402. #include <time.h>
  13403. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  13404. /*
  13405. ** A structure for holding a single date and time.
  13406. */
  13407. typedef struct DateTime DateTime;
  13408. struct DateTime {
  13409. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  13410. int Y, M, D; /* Year, month, and day */
  13411. int h, m; /* Hour and minutes */
  13412. int tz; /* Timezone offset in minutes */
  13413. double s; /* Seconds */
  13414. char validYMD; /* True (1) if Y,M,D are valid */
  13415. char validHMS; /* True (1) if h,m,s are valid */
  13416. char validJD; /* True (1) if iJD is valid */
  13417. char validTZ; /* True (1) if tz is valid */
  13418. };
  13419. /*
  13420. ** Convert zDate into one or more integers. Additional arguments
  13421. ** come in groups of 5 as follows:
  13422. **
  13423. ** N number of digits in the integer
  13424. ** min minimum allowed value of the integer
  13425. ** max maximum allowed value of the integer
  13426. ** nextC first character after the integer
  13427. ** pVal where to write the integers value.
  13428. **
  13429. ** Conversions continue until one with nextC==0 is encountered.
  13430. ** The function returns the number of successful conversions.
  13431. */
  13432. static int getDigits(const char *zDate, ...){
  13433. va_list ap;
  13434. int val;
  13435. int N;
  13436. int min;
  13437. int max;
  13438. int nextC;
  13439. int *pVal;
  13440. int cnt = 0;
  13441. va_start(ap, zDate);
  13442. do{
  13443. N = va_arg(ap, int);
  13444. min = va_arg(ap, int);
  13445. max = va_arg(ap, int);
  13446. nextC = va_arg(ap, int);
  13447. pVal = va_arg(ap, int*);
  13448. val = 0;
  13449. while( N-- ){
  13450. if( !sqlite3Isdigit(*zDate) ){
  13451. goto end_getDigits;
  13452. }
  13453. val = val*10 + *zDate - '0';
  13454. zDate++;
  13455. }
  13456. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  13457. goto end_getDigits;
  13458. }
  13459. *pVal = val;
  13460. zDate++;
  13461. cnt++;
  13462. }while( nextC );
  13463. end_getDigits:
  13464. va_end(ap);
  13465. return cnt;
  13466. }
  13467. /*
  13468. ** Parse a timezone extension on the end of a date-time.
  13469. ** The extension is of the form:
  13470. **
  13471. ** (+/-)HH:MM
  13472. **
  13473. ** Or the "zulu" notation:
  13474. **
  13475. ** Z
  13476. **
  13477. ** If the parse is successful, write the number of minutes
  13478. ** of change in p->tz and return 0. If a parser error occurs,
  13479. ** return non-zero.
  13480. **
  13481. ** A missing specifier is not considered an error.
  13482. */
  13483. static int parseTimezone(const char *zDate, DateTime *p){
  13484. int sgn = 0;
  13485. int nHr, nMn;
  13486. int c;
  13487. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13488. p->tz = 0;
  13489. c = *zDate;
  13490. if( c=='-' ){
  13491. sgn = -1;
  13492. }else if( c=='+' ){
  13493. sgn = +1;
  13494. }else if( c=='Z' || c=='z' ){
  13495. zDate++;
  13496. goto zulu_time;
  13497. }else{
  13498. return c!=0;
  13499. }
  13500. zDate++;
  13501. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  13502. return 1;
  13503. }
  13504. zDate += 5;
  13505. p->tz = sgn*(nMn + nHr*60);
  13506. zulu_time:
  13507. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13508. return *zDate!=0;
  13509. }
  13510. /*
  13511. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  13512. ** The HH, MM, and SS must each be exactly 2 digits. The
  13513. ** fractional seconds FFFF can be one or more digits.
  13514. **
  13515. ** Return 1 if there is a parsing error and 0 on success.
  13516. */
  13517. static int parseHhMmSs(const char *zDate, DateTime *p){
  13518. int h, m, s;
  13519. double ms = 0.0;
  13520. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  13521. return 1;
  13522. }
  13523. zDate += 5;
  13524. if( *zDate==':' ){
  13525. zDate++;
  13526. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  13527. return 1;
  13528. }
  13529. zDate += 2;
  13530. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  13531. double rScale = 1.0;
  13532. zDate++;
  13533. while( sqlite3Isdigit(*zDate) ){
  13534. ms = ms*10.0 + *zDate - '0';
  13535. rScale *= 10.0;
  13536. zDate++;
  13537. }
  13538. ms /= rScale;
  13539. }
  13540. }else{
  13541. s = 0;
  13542. }
  13543. p->validJD = 0;
  13544. p->validHMS = 1;
  13545. p->h = h;
  13546. p->m = m;
  13547. p->s = s + ms;
  13548. if( parseTimezone(zDate, p) ) return 1;
  13549. p->validTZ = (p->tz!=0)?1:0;
  13550. return 0;
  13551. }
  13552. /*
  13553. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  13554. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  13555. **
  13556. ** Reference: Meeus page 61
  13557. */
  13558. static void computeJD(DateTime *p){
  13559. int Y, M, D, A, B, X1, X2;
  13560. if( p->validJD ) return;
  13561. if( p->validYMD ){
  13562. Y = p->Y;
  13563. M = p->M;
  13564. D = p->D;
  13565. }else{
  13566. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  13567. M = 1;
  13568. D = 1;
  13569. }
  13570. if( M<=2 ){
  13571. Y--;
  13572. M += 12;
  13573. }
  13574. A = Y/100;
  13575. B = 2 - A + (A/4);
  13576. X1 = 36525*(Y+4716)/100;
  13577. X2 = 306001*(M+1)/10000;
  13578. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  13579. p->validJD = 1;
  13580. if( p->validHMS ){
  13581. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  13582. if( p->validTZ ){
  13583. p->iJD -= p->tz*60000;
  13584. p->validYMD = 0;
  13585. p->validHMS = 0;
  13586. p->validTZ = 0;
  13587. }
  13588. }
  13589. }
  13590. /*
  13591. ** Parse dates of the form
  13592. **
  13593. ** YYYY-MM-DD HH:MM:SS.FFF
  13594. ** YYYY-MM-DD HH:MM:SS
  13595. ** YYYY-MM-DD HH:MM
  13596. ** YYYY-MM-DD
  13597. **
  13598. ** Write the result into the DateTime structure and return 0
  13599. ** on success and 1 if the input string is not a well-formed
  13600. ** date.
  13601. */
  13602. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  13603. int Y, M, D, neg;
  13604. if( zDate[0]=='-' ){
  13605. zDate++;
  13606. neg = 1;
  13607. }else{
  13608. neg = 0;
  13609. }
  13610. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  13611. return 1;
  13612. }
  13613. zDate += 10;
  13614. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  13615. if( parseHhMmSs(zDate, p)==0 ){
  13616. /* We got the time */
  13617. }else if( *zDate==0 ){
  13618. p->validHMS = 0;
  13619. }else{
  13620. return 1;
  13621. }
  13622. p->validJD = 0;
  13623. p->validYMD = 1;
  13624. p->Y = neg ? -Y : Y;
  13625. p->M = M;
  13626. p->D = D;
  13627. if( p->validTZ ){
  13628. computeJD(p);
  13629. }
  13630. return 0;
  13631. }
  13632. /*
  13633. ** Set the time to the current time reported by the VFS.
  13634. **
  13635. ** Return the number of errors.
  13636. */
  13637. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  13638. p->iJD = sqlite3StmtCurrentTime(context);
  13639. if( p->iJD>0 ){
  13640. p->validJD = 1;
  13641. return 0;
  13642. }else{
  13643. return 1;
  13644. }
  13645. }
  13646. /*
  13647. ** Attempt to parse the given string into a Julian Day Number. Return
  13648. ** the number of errors.
  13649. **
  13650. ** The following are acceptable forms for the input string:
  13651. **
  13652. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  13653. ** DDDD.DD
  13654. ** now
  13655. **
  13656. ** In the first form, the +/-HH:MM is always optional. The fractional
  13657. ** seconds extension (the ".FFF") is optional. The seconds portion
  13658. ** (":SS.FFF") is option. The year and date can be omitted as long
  13659. ** as there is a time string. The time string can be omitted as long
  13660. ** as there is a year and date.
  13661. */
  13662. static int parseDateOrTime(
  13663. sqlite3_context *context,
  13664. const char *zDate,
  13665. DateTime *p
  13666. ){
  13667. double r;
  13668. if( parseYyyyMmDd(zDate,p)==0 ){
  13669. return 0;
  13670. }else if( parseHhMmSs(zDate, p)==0 ){
  13671. return 0;
  13672. }else if( sqlite3StrICmp(zDate,"now")==0){
  13673. return setDateTimeToCurrent(context, p);
  13674. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  13675. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  13676. p->validJD = 1;
  13677. return 0;
  13678. }
  13679. return 1;
  13680. }
  13681. /*
  13682. ** Compute the Year, Month, and Day from the julian day number.
  13683. */
  13684. static void computeYMD(DateTime *p){
  13685. int Z, A, B, C, D, E, X1;
  13686. if( p->validYMD ) return;
  13687. if( !p->validJD ){
  13688. p->Y = 2000;
  13689. p->M = 1;
  13690. p->D = 1;
  13691. }else{
  13692. Z = (int)((p->iJD + 43200000)/86400000);
  13693. A = (int)((Z - 1867216.25)/36524.25);
  13694. A = Z + 1 + A - (A/4);
  13695. B = A + 1524;
  13696. C = (int)((B - 122.1)/365.25);
  13697. D = (36525*C)/100;
  13698. E = (int)((B-D)/30.6001);
  13699. X1 = (int)(30.6001*E);
  13700. p->D = B - D - X1;
  13701. p->M = E<14 ? E-1 : E-13;
  13702. p->Y = p->M>2 ? C - 4716 : C - 4715;
  13703. }
  13704. p->validYMD = 1;
  13705. }
  13706. /*
  13707. ** Compute the Hour, Minute, and Seconds from the julian day number.
  13708. */
  13709. static void computeHMS(DateTime *p){
  13710. int s;
  13711. if( p->validHMS ) return;
  13712. computeJD(p);
  13713. s = (int)((p->iJD + 43200000) % 86400000);
  13714. p->s = s/1000.0;
  13715. s = (int)p->s;
  13716. p->s -= s;
  13717. p->h = s/3600;
  13718. s -= p->h*3600;
  13719. p->m = s/60;
  13720. p->s += s - p->m*60;
  13721. p->validHMS = 1;
  13722. }
  13723. /*
  13724. ** Compute both YMD and HMS
  13725. */
  13726. static void computeYMD_HMS(DateTime *p){
  13727. computeYMD(p);
  13728. computeHMS(p);
  13729. }
  13730. /*
  13731. ** Clear the YMD and HMS and the TZ
  13732. */
  13733. static void clearYMD_HMS_TZ(DateTime *p){
  13734. p->validYMD = 0;
  13735. p->validHMS = 0;
  13736. p->validTZ = 0;
  13737. }
  13738. /*
  13739. ** On recent Windows platforms, the localtime_s() function is available
  13740. ** as part of the "Secure CRT". It is essentially equivalent to
  13741. ** localtime_r() available under most POSIX platforms, except that the
  13742. ** order of the parameters is reversed.
  13743. **
  13744. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  13745. **
  13746. ** If the user has not indicated to use localtime_r() or localtime_s()
  13747. ** already, check for an MSVC build environment that provides
  13748. ** localtime_s().
  13749. */
  13750. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  13751. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  13752. #define HAVE_LOCALTIME_S 1
  13753. #endif
  13754. #ifndef SQLITE_OMIT_LOCALTIME
  13755. /*
  13756. ** The following routine implements the rough equivalent of localtime_r()
  13757. ** using whatever operating-system specific localtime facility that
  13758. ** is available. This routine returns 0 on success and
  13759. ** non-zero on any kind of error.
  13760. **
  13761. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  13762. ** routine will always fail.
  13763. **
  13764. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  13765. ** library function localtime_r() is used to assist in the calculation of
  13766. ** local time.
  13767. */
  13768. static int osLocaltime(time_t *t, struct tm *pTm){
  13769. int rc;
  13770. #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
  13771. && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
  13772. struct tm *pX;
  13773. #if SQLITE_THREADSAFE>0
  13774. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  13775. #endif
  13776. sqlite3_mutex_enter(mutex);
  13777. pX = localtime(t);
  13778. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13779. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  13780. #endif
  13781. if( pX ) *pTm = *pX;
  13782. sqlite3_mutex_leave(mutex);
  13783. rc = pX==0;
  13784. #else
  13785. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13786. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  13787. #endif
  13788. #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
  13789. rc = localtime_r(t, pTm)==0;
  13790. #else
  13791. rc = localtime_s(pTm, t);
  13792. #endif /* HAVE_LOCALTIME_R */
  13793. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  13794. return rc;
  13795. }
  13796. #endif /* SQLITE_OMIT_LOCALTIME */
  13797. #ifndef SQLITE_OMIT_LOCALTIME
  13798. /*
  13799. ** Compute the difference (in milliseconds) between localtime and UTC
  13800. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  13801. ** return this value and set *pRc to SQLITE_OK.
  13802. **
  13803. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  13804. ** is undefined in this case.
  13805. */
  13806. static sqlite3_int64 localtimeOffset(
  13807. DateTime *p, /* Date at which to calculate offset */
  13808. sqlite3_context *pCtx, /* Write error here if one occurs */
  13809. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  13810. ){
  13811. DateTime x, y;
  13812. time_t t;
  13813. struct tm sLocal;
  13814. /* Initialize the contents of sLocal to avoid a compiler warning. */
  13815. memset(&sLocal, 0, sizeof(sLocal));
  13816. x = *p;
  13817. computeYMD_HMS(&x);
  13818. if( x.Y<1971 || x.Y>=2038 ){
  13819. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  13820. ** works for years between 1970 and 2037. For dates outside this range,
  13821. ** SQLite attempts to map the year into an equivalent year within this
  13822. ** range, do the calculation, then map the year back.
  13823. */
  13824. x.Y = 2000;
  13825. x.M = 1;
  13826. x.D = 1;
  13827. x.h = 0;
  13828. x.m = 0;
  13829. x.s = 0.0;
  13830. } else {
  13831. int s = (int)(x.s + 0.5);
  13832. x.s = s;
  13833. }
  13834. x.tz = 0;
  13835. x.validJD = 0;
  13836. computeJD(&x);
  13837. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  13838. if( osLocaltime(&t, &sLocal) ){
  13839. sqlite3_result_error(pCtx, "local time unavailable", -1);
  13840. *pRc = SQLITE_ERROR;
  13841. return 0;
  13842. }
  13843. y.Y = sLocal.tm_year + 1900;
  13844. y.M = sLocal.tm_mon + 1;
  13845. y.D = sLocal.tm_mday;
  13846. y.h = sLocal.tm_hour;
  13847. y.m = sLocal.tm_min;
  13848. y.s = sLocal.tm_sec;
  13849. y.validYMD = 1;
  13850. y.validHMS = 1;
  13851. y.validJD = 0;
  13852. y.validTZ = 0;
  13853. computeJD(&y);
  13854. *pRc = SQLITE_OK;
  13855. return y.iJD - x.iJD;
  13856. }
  13857. #endif /* SQLITE_OMIT_LOCALTIME */
  13858. /*
  13859. ** Process a modifier to a date-time stamp. The modifiers are
  13860. ** as follows:
  13861. **
  13862. ** NNN days
  13863. ** NNN hours
  13864. ** NNN minutes
  13865. ** NNN.NNNN seconds
  13866. ** NNN months
  13867. ** NNN years
  13868. ** start of month
  13869. ** start of year
  13870. ** start of week
  13871. ** start of day
  13872. ** weekday N
  13873. ** unixepoch
  13874. ** localtime
  13875. ** utc
  13876. **
  13877. ** Return 0 on success and 1 if there is any kind of error. If the error
  13878. ** is in a system call (i.e. localtime()), then an error message is written
  13879. ** to context pCtx. If the error is an unrecognized modifier, no error is
  13880. ** written to pCtx.
  13881. */
  13882. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  13883. int rc = 1;
  13884. int n;
  13885. double r;
  13886. char *z, zBuf[30];
  13887. z = zBuf;
  13888. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  13889. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  13890. }
  13891. z[n] = 0;
  13892. switch( z[0] ){
  13893. #ifndef SQLITE_OMIT_LOCALTIME
  13894. case 'l': {
  13895. /* localtime
  13896. **
  13897. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  13898. ** show local time.
  13899. */
  13900. if( strcmp(z, "localtime")==0 ){
  13901. computeJD(p);
  13902. p->iJD += localtimeOffset(p, pCtx, &rc);
  13903. clearYMD_HMS_TZ(p);
  13904. }
  13905. break;
  13906. }
  13907. #endif
  13908. case 'u': {
  13909. /*
  13910. ** unixepoch
  13911. **
  13912. ** Treat the current value of p->iJD as the number of
  13913. ** seconds since 1970. Convert to a real julian day number.
  13914. */
  13915. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  13916. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  13917. clearYMD_HMS_TZ(p);
  13918. rc = 0;
  13919. }
  13920. #ifndef SQLITE_OMIT_LOCALTIME
  13921. else if( strcmp(z, "utc")==0 ){
  13922. sqlite3_int64 c1;
  13923. computeJD(p);
  13924. c1 = localtimeOffset(p, pCtx, &rc);
  13925. if( rc==SQLITE_OK ){
  13926. p->iJD -= c1;
  13927. clearYMD_HMS_TZ(p);
  13928. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  13929. }
  13930. }
  13931. #endif
  13932. break;
  13933. }
  13934. case 'w': {
  13935. /*
  13936. ** weekday N
  13937. **
  13938. ** Move the date to the same time on the next occurrence of
  13939. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  13940. ** date is already on the appropriate weekday, this is a no-op.
  13941. */
  13942. if( strncmp(z, "weekday ", 8)==0
  13943. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  13944. && (n=(int)r)==r && n>=0 && r<7 ){
  13945. sqlite3_int64 Z;
  13946. computeYMD_HMS(p);
  13947. p->validTZ = 0;
  13948. p->validJD = 0;
  13949. computeJD(p);
  13950. Z = ((p->iJD + 129600000)/86400000) % 7;
  13951. if( Z>n ) Z -= 7;
  13952. p->iJD += (n - Z)*86400000;
  13953. clearYMD_HMS_TZ(p);
  13954. rc = 0;
  13955. }
  13956. break;
  13957. }
  13958. case 's': {
  13959. /*
  13960. ** start of TTTTT
  13961. **
  13962. ** Move the date backwards to the beginning of the current day,
  13963. ** or month or year.
  13964. */
  13965. if( strncmp(z, "start of ", 9)!=0 ) break;
  13966. z += 9;
  13967. computeYMD(p);
  13968. p->validHMS = 1;
  13969. p->h = p->m = 0;
  13970. p->s = 0.0;
  13971. p->validTZ = 0;
  13972. p->validJD = 0;
  13973. if( strcmp(z,"month")==0 ){
  13974. p->D = 1;
  13975. rc = 0;
  13976. }else if( strcmp(z,"year")==0 ){
  13977. computeYMD(p);
  13978. p->M = 1;
  13979. p->D = 1;
  13980. rc = 0;
  13981. }else if( strcmp(z,"day")==0 ){
  13982. rc = 0;
  13983. }
  13984. break;
  13985. }
  13986. case '+':
  13987. case '-':
  13988. case '0':
  13989. case '1':
  13990. case '2':
  13991. case '3':
  13992. case '4':
  13993. case '5':
  13994. case '6':
  13995. case '7':
  13996. case '8':
  13997. case '9': {
  13998. double rRounder;
  13999. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  14000. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  14001. rc = 1;
  14002. break;
  14003. }
  14004. if( z[n]==':' ){
  14005. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  14006. ** specified number of hours, minutes, seconds, and fractional seconds
  14007. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  14008. ** omitted.
  14009. */
  14010. const char *z2 = z;
  14011. DateTime tx;
  14012. sqlite3_int64 day;
  14013. if( !sqlite3Isdigit(*z2) ) z2++;
  14014. memset(&tx, 0, sizeof(tx));
  14015. if( parseHhMmSs(z2, &tx) ) break;
  14016. computeJD(&tx);
  14017. tx.iJD -= 43200000;
  14018. day = tx.iJD/86400000;
  14019. tx.iJD -= day*86400000;
  14020. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  14021. computeJD(p);
  14022. clearYMD_HMS_TZ(p);
  14023. p->iJD += tx.iJD;
  14024. rc = 0;
  14025. break;
  14026. }
  14027. z += n;
  14028. while( sqlite3Isspace(*z) ) z++;
  14029. n = sqlite3Strlen30(z);
  14030. if( n>10 || n<3 ) break;
  14031. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  14032. computeJD(p);
  14033. rc = 0;
  14034. rRounder = r<0 ? -0.5 : +0.5;
  14035. if( n==3 && strcmp(z,"day")==0 ){
  14036. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  14037. }else if( n==4 && strcmp(z,"hour")==0 ){
  14038. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  14039. }else if( n==6 && strcmp(z,"minute")==0 ){
  14040. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  14041. }else if( n==6 && strcmp(z,"second")==0 ){
  14042. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  14043. }else if( n==5 && strcmp(z,"month")==0 ){
  14044. int x, y;
  14045. computeYMD_HMS(p);
  14046. p->M += (int)r;
  14047. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  14048. p->Y += x;
  14049. p->M -= x*12;
  14050. p->validJD = 0;
  14051. computeJD(p);
  14052. y = (int)r;
  14053. if( y!=r ){
  14054. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  14055. }
  14056. }else if( n==4 && strcmp(z,"year")==0 ){
  14057. int y = (int)r;
  14058. computeYMD_HMS(p);
  14059. p->Y += y;
  14060. p->validJD = 0;
  14061. computeJD(p);
  14062. if( y!=r ){
  14063. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  14064. }
  14065. }else{
  14066. rc = 1;
  14067. }
  14068. clearYMD_HMS_TZ(p);
  14069. break;
  14070. }
  14071. default: {
  14072. break;
  14073. }
  14074. }
  14075. return rc;
  14076. }
  14077. /*
  14078. ** Process time function arguments. argv[0] is a date-time stamp.
  14079. ** argv[1] and following are modifiers. Parse them all and write
  14080. ** the resulting time into the DateTime structure p. Return 0
  14081. ** on success and 1 if there are any errors.
  14082. **
  14083. ** If there are zero parameters (if even argv[0] is undefined)
  14084. ** then assume a default value of "now" for argv[0].
  14085. */
  14086. static int isDate(
  14087. sqlite3_context *context,
  14088. int argc,
  14089. sqlite3_value **argv,
  14090. DateTime *p
  14091. ){
  14092. int i;
  14093. const unsigned char *z;
  14094. int eType;
  14095. memset(p, 0, sizeof(*p));
  14096. if( argc==0 ){
  14097. return setDateTimeToCurrent(context, p);
  14098. }
  14099. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  14100. || eType==SQLITE_INTEGER ){
  14101. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  14102. p->validJD = 1;
  14103. }else{
  14104. z = sqlite3_value_text(argv[0]);
  14105. if( !z || parseDateOrTime(context, (char*)z, p) ){
  14106. return 1;
  14107. }
  14108. }
  14109. for(i=1; i<argc; i++){
  14110. z = sqlite3_value_text(argv[i]);
  14111. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  14112. }
  14113. return 0;
  14114. }
  14115. /*
  14116. ** The following routines implement the various date and time functions
  14117. ** of SQLite.
  14118. */
  14119. /*
  14120. ** julianday( TIMESTRING, MOD, MOD, ...)
  14121. **
  14122. ** Return the julian day number of the date specified in the arguments
  14123. */
  14124. static void juliandayFunc(
  14125. sqlite3_context *context,
  14126. int argc,
  14127. sqlite3_value **argv
  14128. ){
  14129. DateTime x;
  14130. if( isDate(context, argc, argv, &x)==0 ){
  14131. computeJD(&x);
  14132. sqlite3_result_double(context, x.iJD/86400000.0);
  14133. }
  14134. }
  14135. /*
  14136. ** datetime( TIMESTRING, MOD, MOD, ...)
  14137. **
  14138. ** Return YYYY-MM-DD HH:MM:SS
  14139. */
  14140. static void datetimeFunc(
  14141. sqlite3_context *context,
  14142. int argc,
  14143. sqlite3_value **argv
  14144. ){
  14145. DateTime x;
  14146. if( isDate(context, argc, argv, &x)==0 ){
  14147. char zBuf[100];
  14148. computeYMD_HMS(&x);
  14149. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  14150. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  14151. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14152. }
  14153. }
  14154. /*
  14155. ** time( TIMESTRING, MOD, MOD, ...)
  14156. **
  14157. ** Return HH:MM:SS
  14158. */
  14159. static void timeFunc(
  14160. sqlite3_context *context,
  14161. int argc,
  14162. sqlite3_value **argv
  14163. ){
  14164. DateTime x;
  14165. if( isDate(context, argc, argv, &x)==0 ){
  14166. char zBuf[100];
  14167. computeHMS(&x);
  14168. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  14169. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14170. }
  14171. }
  14172. /*
  14173. ** date( TIMESTRING, MOD, MOD, ...)
  14174. **
  14175. ** Return YYYY-MM-DD
  14176. */
  14177. static void dateFunc(
  14178. sqlite3_context *context,
  14179. int argc,
  14180. sqlite3_value **argv
  14181. ){
  14182. DateTime x;
  14183. if( isDate(context, argc, argv, &x)==0 ){
  14184. char zBuf[100];
  14185. computeYMD(&x);
  14186. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  14187. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14188. }
  14189. }
  14190. /*
  14191. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  14192. **
  14193. ** Return a string described by FORMAT. Conversions as follows:
  14194. **
  14195. ** %d day of month
  14196. ** %f ** fractional seconds SS.SSS
  14197. ** %H hour 00-24
  14198. ** %j day of year 000-366
  14199. ** %J ** Julian day number
  14200. ** %m month 01-12
  14201. ** %M minute 00-59
  14202. ** %s seconds since 1970-01-01
  14203. ** %S seconds 00-59
  14204. ** %w day of week 0-6 sunday==0
  14205. ** %W week of year 00-53
  14206. ** %Y year 0000-9999
  14207. ** %% %
  14208. */
  14209. static void strftimeFunc(
  14210. sqlite3_context *context,
  14211. int argc,
  14212. sqlite3_value **argv
  14213. ){
  14214. DateTime x;
  14215. u64 n;
  14216. size_t i,j;
  14217. char *z;
  14218. sqlite3 *db;
  14219. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  14220. char zBuf[100];
  14221. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  14222. db = sqlite3_context_db_handle(context);
  14223. for(i=0, n=1; zFmt[i]; i++, n++){
  14224. if( zFmt[i]=='%' ){
  14225. switch( zFmt[i+1] ){
  14226. case 'd':
  14227. case 'H':
  14228. case 'm':
  14229. case 'M':
  14230. case 'S':
  14231. case 'W':
  14232. n++;
  14233. /* fall thru */
  14234. case 'w':
  14235. case '%':
  14236. break;
  14237. case 'f':
  14238. n += 8;
  14239. break;
  14240. case 'j':
  14241. n += 3;
  14242. break;
  14243. case 'Y':
  14244. n += 8;
  14245. break;
  14246. case 's':
  14247. case 'J':
  14248. n += 50;
  14249. break;
  14250. default:
  14251. return; /* ERROR. return a NULL */
  14252. }
  14253. i++;
  14254. }
  14255. }
  14256. testcase( n==sizeof(zBuf)-1 );
  14257. testcase( n==sizeof(zBuf) );
  14258. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  14259. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  14260. if( n<sizeof(zBuf) ){
  14261. z = zBuf;
  14262. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  14263. sqlite3_result_error_toobig(context);
  14264. return;
  14265. }else{
  14266. z = sqlite3DbMallocRaw(db, (int)n);
  14267. if( z==0 ){
  14268. sqlite3_result_error_nomem(context);
  14269. return;
  14270. }
  14271. }
  14272. computeJD(&x);
  14273. computeYMD_HMS(&x);
  14274. for(i=j=0; zFmt[i]; i++){
  14275. if( zFmt[i]!='%' ){
  14276. z[j++] = zFmt[i];
  14277. }else{
  14278. i++;
  14279. switch( zFmt[i] ){
  14280. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  14281. case 'f': {
  14282. double s = x.s;
  14283. if( s>59.999 ) s = 59.999;
  14284. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  14285. j += sqlite3Strlen30(&z[j]);
  14286. break;
  14287. }
  14288. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  14289. case 'W': /* Fall thru */
  14290. case 'j': {
  14291. int nDay; /* Number of days since 1st day of year */
  14292. DateTime y = x;
  14293. y.validJD = 0;
  14294. y.M = 1;
  14295. y.D = 1;
  14296. computeJD(&y);
  14297. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  14298. if( zFmt[i]=='W' ){
  14299. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  14300. wd = (int)(((x.iJD+43200000)/86400000)%7);
  14301. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  14302. j += 2;
  14303. }else{
  14304. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  14305. j += 3;
  14306. }
  14307. break;
  14308. }
  14309. case 'J': {
  14310. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  14311. j+=sqlite3Strlen30(&z[j]);
  14312. break;
  14313. }
  14314. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  14315. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  14316. case 's': {
  14317. sqlite3_snprintf(30,&z[j],"%lld",
  14318. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  14319. j += sqlite3Strlen30(&z[j]);
  14320. break;
  14321. }
  14322. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  14323. case 'w': {
  14324. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  14325. break;
  14326. }
  14327. case 'Y': {
  14328. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  14329. break;
  14330. }
  14331. default: z[j++] = '%'; break;
  14332. }
  14333. }
  14334. }
  14335. z[j] = 0;
  14336. sqlite3_result_text(context, z, -1,
  14337. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  14338. }
  14339. /*
  14340. ** current_time()
  14341. **
  14342. ** This function returns the same value as time('now').
  14343. */
  14344. static void ctimeFunc(
  14345. sqlite3_context *context,
  14346. int NotUsed,
  14347. sqlite3_value **NotUsed2
  14348. ){
  14349. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14350. timeFunc(context, 0, 0);
  14351. }
  14352. /*
  14353. ** current_date()
  14354. **
  14355. ** This function returns the same value as date('now').
  14356. */
  14357. static void cdateFunc(
  14358. sqlite3_context *context,
  14359. int NotUsed,
  14360. sqlite3_value **NotUsed2
  14361. ){
  14362. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14363. dateFunc(context, 0, 0);
  14364. }
  14365. /*
  14366. ** current_timestamp()
  14367. **
  14368. ** This function returns the same value as datetime('now').
  14369. */
  14370. static void ctimestampFunc(
  14371. sqlite3_context *context,
  14372. int NotUsed,
  14373. sqlite3_value **NotUsed2
  14374. ){
  14375. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14376. datetimeFunc(context, 0, 0);
  14377. }
  14378. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  14379. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  14380. /*
  14381. ** If the library is compiled to omit the full-scale date and time
  14382. ** handling (to get a smaller binary), the following minimal version
  14383. ** of the functions current_time(), current_date() and current_timestamp()
  14384. ** are included instead. This is to support column declarations that
  14385. ** include "DEFAULT CURRENT_TIME" etc.
  14386. **
  14387. ** This function uses the C-library functions time(), gmtime()
  14388. ** and strftime(). The format string to pass to strftime() is supplied
  14389. ** as the user-data for the function.
  14390. */
  14391. static void currentTimeFunc(
  14392. sqlite3_context *context,
  14393. int argc,
  14394. sqlite3_value **argv
  14395. ){
  14396. time_t t;
  14397. char *zFormat = (char *)sqlite3_user_data(context);
  14398. sqlite3 *db;
  14399. sqlite3_int64 iT;
  14400. struct tm *pTm;
  14401. struct tm sNow;
  14402. char zBuf[20];
  14403. UNUSED_PARAMETER(argc);
  14404. UNUSED_PARAMETER(argv);
  14405. iT = sqlite3StmtCurrentTime(context);
  14406. if( iT<=0 ) return;
  14407. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  14408. #ifdef HAVE_GMTIME_R
  14409. pTm = gmtime_r(&t, &sNow);
  14410. #else
  14411. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14412. pTm = gmtime(&t);
  14413. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  14414. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14415. #endif
  14416. if( pTm ){
  14417. strftime(zBuf, 20, zFormat, &sNow);
  14418. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14419. }
  14420. }
  14421. #endif
  14422. /*
  14423. ** This function registered all of the above C functions as SQL
  14424. ** functions. This should be the only routine in this file with
  14425. ** external linkage.
  14426. */
  14427. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  14428. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  14429. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  14430. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  14431. FUNCTION(date, -1, 0, 0, dateFunc ),
  14432. FUNCTION(time, -1, 0, 0, timeFunc ),
  14433. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  14434. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  14435. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  14436. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  14437. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  14438. #else
  14439. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  14440. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  14441. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  14442. #endif
  14443. };
  14444. int i;
  14445. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  14446. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  14447. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  14448. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  14449. }
  14450. }
  14451. /************** End of date.c ************************************************/
  14452. /************** Begin file os.c **********************************************/
  14453. /*
  14454. ** 2005 November 29
  14455. **
  14456. ** The author disclaims copyright to this source code. In place of
  14457. ** a legal notice, here is a blessing:
  14458. **
  14459. ** May you do good and not evil.
  14460. ** May you find forgiveness for yourself and forgive others.
  14461. ** May you share freely, never taking more than you give.
  14462. **
  14463. ******************************************************************************
  14464. **
  14465. ** This file contains OS interface code that is common to all
  14466. ** architectures.
  14467. */
  14468. #define _SQLITE_OS_C_ 1
  14469. #undef _SQLITE_OS_C_
  14470. /*
  14471. ** The default SQLite sqlite3_vfs implementations do not allocate
  14472. ** memory (actually, os_unix.c allocates a small amount of memory
  14473. ** from within OsOpen()), but some third-party implementations may.
  14474. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  14475. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  14476. **
  14477. ** The following functions are instrumented for malloc() failure
  14478. ** testing:
  14479. **
  14480. ** sqlite3OsRead()
  14481. ** sqlite3OsWrite()
  14482. ** sqlite3OsSync()
  14483. ** sqlite3OsFileSize()
  14484. ** sqlite3OsLock()
  14485. ** sqlite3OsCheckReservedLock()
  14486. ** sqlite3OsFileControl()
  14487. ** sqlite3OsShmMap()
  14488. ** sqlite3OsOpen()
  14489. ** sqlite3OsDelete()
  14490. ** sqlite3OsAccess()
  14491. ** sqlite3OsFullPathname()
  14492. **
  14493. */
  14494. #if defined(SQLITE_TEST)
  14495. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  14496. #define DO_OS_MALLOC_TEST(x) \
  14497. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  14498. void *pTstAlloc = sqlite3Malloc(10); \
  14499. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  14500. sqlite3_free(pTstAlloc); \
  14501. }
  14502. #else
  14503. #define DO_OS_MALLOC_TEST(x)
  14504. #endif
  14505. /*
  14506. ** The following routines are convenience wrappers around methods
  14507. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  14508. ** of this would be completely automatic if SQLite were coded using
  14509. ** C++ instead of plain old C.
  14510. */
  14511. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  14512. int rc = SQLITE_OK;
  14513. if( pId->pMethods ){
  14514. rc = pId->pMethods->xClose(pId);
  14515. pId->pMethods = 0;
  14516. }
  14517. return rc;
  14518. }
  14519. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  14520. DO_OS_MALLOC_TEST(id);
  14521. return id->pMethods->xRead(id, pBuf, amt, offset);
  14522. }
  14523. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  14524. DO_OS_MALLOC_TEST(id);
  14525. return id->pMethods->xWrite(id, pBuf, amt, offset);
  14526. }
  14527. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  14528. return id->pMethods->xTruncate(id, size);
  14529. }
  14530. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  14531. DO_OS_MALLOC_TEST(id);
  14532. return id->pMethods->xSync(id, flags);
  14533. }
  14534. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  14535. DO_OS_MALLOC_TEST(id);
  14536. return id->pMethods->xFileSize(id, pSize);
  14537. }
  14538. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  14539. DO_OS_MALLOC_TEST(id);
  14540. return id->pMethods->xLock(id, lockType);
  14541. }
  14542. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  14543. return id->pMethods->xUnlock(id, lockType);
  14544. }
  14545. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  14546. DO_OS_MALLOC_TEST(id);
  14547. return id->pMethods->xCheckReservedLock(id, pResOut);
  14548. }
  14549. /*
  14550. ** Use sqlite3OsFileControl() when we are doing something that might fail
  14551. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  14552. ** when simply tossing information over the wall to the VFS and we do not
  14553. ** really care if the VFS receives and understands the information since it
  14554. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  14555. ** routine has no return value since the return value would be meaningless.
  14556. */
  14557. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  14558. DO_OS_MALLOC_TEST(id);
  14559. return id->pMethods->xFileControl(id, op, pArg);
  14560. }
  14561. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  14562. (void)id->pMethods->xFileControl(id, op, pArg);
  14563. }
  14564. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  14565. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  14566. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  14567. }
  14568. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  14569. return id->pMethods->xDeviceCharacteristics(id);
  14570. }
  14571. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  14572. return id->pMethods->xShmLock(id, offset, n, flags);
  14573. }
  14574. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  14575. id->pMethods->xShmBarrier(id);
  14576. }
  14577. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  14578. return id->pMethods->xShmUnmap(id, deleteFlag);
  14579. }
  14580. SQLITE_PRIVATE int sqlite3OsShmMap(
  14581. sqlite3_file *id, /* Database file handle */
  14582. int iPage,
  14583. int pgsz,
  14584. int bExtend, /* True to extend file if necessary */
  14585. void volatile **pp /* OUT: Pointer to mapping */
  14586. ){
  14587. DO_OS_MALLOC_TEST(id);
  14588. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  14589. }
  14590. #if SQLITE_MAX_MMAP_SIZE>0
  14591. /* The real implementation of xFetch and xUnfetch */
  14592. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  14593. DO_OS_MALLOC_TEST(id);
  14594. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  14595. }
  14596. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  14597. return id->pMethods->xUnfetch(id, iOff, p);
  14598. }
  14599. #else
  14600. /* No-op stubs to use when memory-mapped I/O is disabled */
  14601. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  14602. *pp = 0;
  14603. return SQLITE_OK;
  14604. }
  14605. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  14606. return SQLITE_OK;
  14607. }
  14608. #endif
  14609. /*
  14610. ** The next group of routines are convenience wrappers around the
  14611. ** VFS methods.
  14612. */
  14613. SQLITE_PRIVATE int sqlite3OsOpen(
  14614. sqlite3_vfs *pVfs,
  14615. const char *zPath,
  14616. sqlite3_file *pFile,
  14617. int flags,
  14618. int *pFlagsOut
  14619. ){
  14620. int rc;
  14621. DO_OS_MALLOC_TEST(0);
  14622. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  14623. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  14624. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  14625. ** reaching the VFS. */
  14626. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  14627. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  14628. return rc;
  14629. }
  14630. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  14631. DO_OS_MALLOC_TEST(0);
  14632. assert( dirSync==0 || dirSync==1 );
  14633. return pVfs->xDelete(pVfs, zPath, dirSync);
  14634. }
  14635. SQLITE_PRIVATE int sqlite3OsAccess(
  14636. sqlite3_vfs *pVfs,
  14637. const char *zPath,
  14638. int flags,
  14639. int *pResOut
  14640. ){
  14641. DO_OS_MALLOC_TEST(0);
  14642. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  14643. }
  14644. SQLITE_PRIVATE int sqlite3OsFullPathname(
  14645. sqlite3_vfs *pVfs,
  14646. const char *zPath,
  14647. int nPathOut,
  14648. char *zPathOut
  14649. ){
  14650. DO_OS_MALLOC_TEST(0);
  14651. zPathOut[0] = 0;
  14652. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  14653. }
  14654. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14655. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  14656. return pVfs->xDlOpen(pVfs, zPath);
  14657. }
  14658. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14659. pVfs->xDlError(pVfs, nByte, zBufOut);
  14660. }
  14661. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  14662. return pVfs->xDlSym(pVfs, pHdle, zSym);
  14663. }
  14664. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  14665. pVfs->xDlClose(pVfs, pHandle);
  14666. }
  14667. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  14668. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14669. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  14670. }
  14671. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  14672. return pVfs->xSleep(pVfs, nMicro);
  14673. }
  14674. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  14675. int rc;
  14676. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  14677. ** method to get the current date and time if that method is available
  14678. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  14679. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  14680. ** unavailable.
  14681. */
  14682. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  14683. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  14684. }else{
  14685. double r;
  14686. rc = pVfs->xCurrentTime(pVfs, &r);
  14687. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  14688. }
  14689. return rc;
  14690. }
  14691. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  14692. sqlite3_vfs *pVfs,
  14693. const char *zFile,
  14694. sqlite3_file **ppFile,
  14695. int flags,
  14696. int *pOutFlags
  14697. ){
  14698. int rc = SQLITE_NOMEM;
  14699. sqlite3_file *pFile;
  14700. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  14701. if( pFile ){
  14702. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  14703. if( rc!=SQLITE_OK ){
  14704. sqlite3_free(pFile);
  14705. }else{
  14706. *ppFile = pFile;
  14707. }
  14708. }
  14709. return rc;
  14710. }
  14711. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  14712. int rc = SQLITE_OK;
  14713. assert( pFile );
  14714. rc = sqlite3OsClose(pFile);
  14715. sqlite3_free(pFile);
  14716. return rc;
  14717. }
  14718. /*
  14719. ** This function is a wrapper around the OS specific implementation of
  14720. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  14721. ** ability to simulate a malloc failure, so that the handling of an
  14722. ** error in sqlite3_os_init() by the upper layers can be tested.
  14723. */
  14724. SQLITE_PRIVATE int sqlite3OsInit(void){
  14725. void *p = sqlite3_malloc(10);
  14726. if( p==0 ) return SQLITE_NOMEM;
  14727. sqlite3_free(p);
  14728. return sqlite3_os_init();
  14729. }
  14730. /*
  14731. ** The list of all registered VFS implementations.
  14732. */
  14733. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  14734. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  14735. /*
  14736. ** Locate a VFS by name. If no name is given, simply return the
  14737. ** first VFS on the list.
  14738. */
  14739. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  14740. sqlite3_vfs *pVfs = 0;
  14741. #if SQLITE_THREADSAFE
  14742. sqlite3_mutex *mutex;
  14743. #endif
  14744. #ifndef SQLITE_OMIT_AUTOINIT
  14745. int rc = sqlite3_initialize();
  14746. if( rc ) return 0;
  14747. #endif
  14748. #if SQLITE_THREADSAFE
  14749. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14750. #endif
  14751. sqlite3_mutex_enter(mutex);
  14752. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  14753. if( zVfs==0 ) break;
  14754. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  14755. }
  14756. sqlite3_mutex_leave(mutex);
  14757. return pVfs;
  14758. }
  14759. /*
  14760. ** Unlink a VFS from the linked list
  14761. */
  14762. static void vfsUnlink(sqlite3_vfs *pVfs){
  14763. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  14764. if( pVfs==0 ){
  14765. /* No-op */
  14766. }else if( vfsList==pVfs ){
  14767. vfsList = pVfs->pNext;
  14768. }else if( vfsList ){
  14769. sqlite3_vfs *p = vfsList;
  14770. while( p->pNext && p->pNext!=pVfs ){
  14771. p = p->pNext;
  14772. }
  14773. if( p->pNext==pVfs ){
  14774. p->pNext = pVfs->pNext;
  14775. }
  14776. }
  14777. }
  14778. /*
  14779. ** Register a VFS with the system. It is harmless to register the same
  14780. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  14781. ** true.
  14782. */
  14783. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  14784. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  14785. #ifndef SQLITE_OMIT_AUTOINIT
  14786. int rc = sqlite3_initialize();
  14787. if( rc ) return rc;
  14788. #endif
  14789. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  14790. sqlite3_mutex_enter(mutex);
  14791. vfsUnlink(pVfs);
  14792. if( makeDflt || vfsList==0 ){
  14793. pVfs->pNext = vfsList;
  14794. vfsList = pVfs;
  14795. }else{
  14796. pVfs->pNext = vfsList->pNext;
  14797. vfsList->pNext = pVfs;
  14798. }
  14799. assert(vfsList);
  14800. sqlite3_mutex_leave(mutex);
  14801. return SQLITE_OK;
  14802. }
  14803. /*
  14804. ** Unregister a VFS so that it is no longer accessible.
  14805. */
  14806. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  14807. #if SQLITE_THREADSAFE
  14808. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14809. #endif
  14810. sqlite3_mutex_enter(mutex);
  14811. vfsUnlink(pVfs);
  14812. sqlite3_mutex_leave(mutex);
  14813. return SQLITE_OK;
  14814. }
  14815. /************** End of os.c **************************************************/
  14816. /************** Begin file fault.c *******************************************/
  14817. /*
  14818. ** 2008 Jan 22
  14819. **
  14820. ** The author disclaims copyright to this source code. In place of
  14821. ** a legal notice, here is a blessing:
  14822. **
  14823. ** May you do good and not evil.
  14824. ** May you find forgiveness for yourself and forgive others.
  14825. ** May you share freely, never taking more than you give.
  14826. **
  14827. *************************************************************************
  14828. **
  14829. ** This file contains code to support the concept of "benign"
  14830. ** malloc failures (when the xMalloc() or xRealloc() method of the
  14831. ** sqlite3_mem_methods structure fails to allocate a block of memory
  14832. ** and returns 0).
  14833. **
  14834. ** Most malloc failures are non-benign. After they occur, SQLite
  14835. ** abandons the current operation and returns an error code (usually
  14836. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  14837. ** fatal. For example, if a malloc fails while resizing a hash table, this
  14838. ** is completely recoverable simply by not carrying out the resize. The
  14839. ** hash table will continue to function normally. So a malloc failure
  14840. ** during a hash table resize is a benign fault.
  14841. */
  14842. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14843. /*
  14844. ** Global variables.
  14845. */
  14846. typedef struct BenignMallocHooks BenignMallocHooks;
  14847. static SQLITE_WSD struct BenignMallocHooks {
  14848. void (*xBenignBegin)(void);
  14849. void (*xBenignEnd)(void);
  14850. } sqlite3Hooks = { 0, 0 };
  14851. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  14852. ** structure. If writable static data is unsupported on the target,
  14853. ** we have to locate the state vector at run-time. In the more common
  14854. ** case where writable static data is supported, wsdHooks can refer directly
  14855. ** to the "sqlite3Hooks" state vector declared above.
  14856. */
  14857. #ifdef SQLITE_OMIT_WSD
  14858. # define wsdHooksInit \
  14859. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  14860. # define wsdHooks x[0]
  14861. #else
  14862. # define wsdHooksInit
  14863. # define wsdHooks sqlite3Hooks
  14864. #endif
  14865. /*
  14866. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  14867. ** sqlite3EndBenignMalloc() are called, respectively.
  14868. */
  14869. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  14870. void (*xBenignBegin)(void),
  14871. void (*xBenignEnd)(void)
  14872. ){
  14873. wsdHooksInit;
  14874. wsdHooks.xBenignBegin = xBenignBegin;
  14875. wsdHooks.xBenignEnd = xBenignEnd;
  14876. }
  14877. /*
  14878. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  14879. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  14880. ** indicates that subsequent malloc failures are non-benign.
  14881. */
  14882. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  14883. wsdHooksInit;
  14884. if( wsdHooks.xBenignBegin ){
  14885. wsdHooks.xBenignBegin();
  14886. }
  14887. }
  14888. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  14889. wsdHooksInit;
  14890. if( wsdHooks.xBenignEnd ){
  14891. wsdHooks.xBenignEnd();
  14892. }
  14893. }
  14894. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  14895. /************** End of fault.c ***********************************************/
  14896. /************** Begin file mem0.c ********************************************/
  14897. /*
  14898. ** 2008 October 28
  14899. **
  14900. ** The author disclaims copyright to this source code. In place of
  14901. ** a legal notice, here is a blessing:
  14902. **
  14903. ** May you do good and not evil.
  14904. ** May you find forgiveness for yourself and forgive others.
  14905. ** May you share freely, never taking more than you give.
  14906. **
  14907. *************************************************************************
  14908. **
  14909. ** This file contains a no-op memory allocation drivers for use when
  14910. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  14911. ** here always fail. SQLite will not operate with these drivers. These
  14912. ** are merely placeholders. Real drivers must be substituted using
  14913. ** sqlite3_config() before SQLite will operate.
  14914. */
  14915. /*
  14916. ** This version of the memory allocator is the default. It is
  14917. ** used when no other memory allocator is specified using compile-time
  14918. ** macros.
  14919. */
  14920. #ifdef SQLITE_ZERO_MALLOC
  14921. /*
  14922. ** No-op versions of all memory allocation routines
  14923. */
  14924. static void *sqlite3MemMalloc(int nByte){ return 0; }
  14925. static void sqlite3MemFree(void *pPrior){ return; }
  14926. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  14927. static int sqlite3MemSize(void *pPrior){ return 0; }
  14928. static int sqlite3MemRoundup(int n){ return n; }
  14929. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  14930. static void sqlite3MemShutdown(void *NotUsed){ return; }
  14931. /*
  14932. ** This routine is the only routine in this file with external linkage.
  14933. **
  14934. ** Populate the low-level memory allocation function pointers in
  14935. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  14936. */
  14937. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  14938. static const sqlite3_mem_methods defaultMethods = {
  14939. sqlite3MemMalloc,
  14940. sqlite3MemFree,
  14941. sqlite3MemRealloc,
  14942. sqlite3MemSize,
  14943. sqlite3MemRoundup,
  14944. sqlite3MemInit,
  14945. sqlite3MemShutdown,
  14946. 0
  14947. };
  14948. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  14949. }
  14950. #endif /* SQLITE_ZERO_MALLOC */
  14951. /************** End of mem0.c ************************************************/
  14952. /************** Begin file mem1.c ********************************************/
  14953. /*
  14954. ** 2007 August 14
  14955. **
  14956. ** The author disclaims copyright to this source code. In place of
  14957. ** a legal notice, here is a blessing:
  14958. **
  14959. ** May you do good and not evil.
  14960. ** May you find forgiveness for yourself and forgive others.
  14961. ** May you share freely, never taking more than you give.
  14962. **
  14963. *************************************************************************
  14964. **
  14965. ** This file contains low-level memory allocation drivers for when
  14966. ** SQLite will use the standard C-library malloc/realloc/free interface
  14967. ** to obtain the memory it needs.
  14968. **
  14969. ** This file contains implementations of the low-level memory allocation
  14970. ** routines specified in the sqlite3_mem_methods object. The content of
  14971. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  14972. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  14973. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  14974. ** default configuration is to use memory allocation routines in this
  14975. ** file.
  14976. **
  14977. ** C-preprocessor macro summary:
  14978. **
  14979. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  14980. ** the malloc_usable_size() interface exists
  14981. ** on the target platform. Or, this symbol
  14982. ** can be set manually, if desired.
  14983. ** If an equivalent interface exists by
  14984. ** a different name, using a separate -D
  14985. ** option to rename it.
  14986. **
  14987. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  14988. ** memory allocator. Set this symbol to enable
  14989. ** building on older macs.
  14990. **
  14991. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  14992. ** _msize() on windows systems. This might
  14993. ** be necessary when compiling for Delphi,
  14994. ** for example.
  14995. */
  14996. /*
  14997. ** This version of the memory allocator is the default. It is
  14998. ** used when no other memory allocator is specified using compile-time
  14999. ** macros.
  15000. */
  15001. #ifdef SQLITE_SYSTEM_MALLOC
  15002. /*
  15003. ** The MSVCRT has malloc_usable_size() but it is called _msize().
  15004. ** The use of _msize() is automatic, but can be disabled by compiling
  15005. ** with -DSQLITE_WITHOUT_MSIZE
  15006. */
  15007. #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  15008. # define SQLITE_MALLOCSIZE _msize
  15009. #endif
  15010. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15011. /*
  15012. ** Use the zone allocator available on apple products unless the
  15013. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  15014. */
  15015. #include <sys/sysctl.h>
  15016. #include <malloc/malloc.h>
  15017. #include <libkern/OSAtomic.h>
  15018. static malloc_zone_t* _sqliteZone_;
  15019. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  15020. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  15021. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  15022. #define SQLITE_MALLOCSIZE(x) \
  15023. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  15024. #else /* if not __APPLE__ */
  15025. /*
  15026. ** Use standard C library malloc and free on non-Apple systems.
  15027. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  15028. */
  15029. #define SQLITE_MALLOC(x) malloc(x)
  15030. #define SQLITE_FREE(x) free(x)
  15031. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  15032. #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
  15033. || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
  15034. # include <malloc.h> /* Needed for malloc_usable_size on linux */
  15035. #endif
  15036. #ifdef HAVE_MALLOC_USABLE_SIZE
  15037. # ifndef SQLITE_MALLOCSIZE
  15038. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  15039. # endif
  15040. #else
  15041. # undef SQLITE_MALLOCSIZE
  15042. #endif
  15043. #endif /* __APPLE__ or not __APPLE__ */
  15044. /*
  15045. ** Like malloc(), but remember the size of the allocation
  15046. ** so that we can find it later using sqlite3MemSize().
  15047. **
  15048. ** For this low-level routine, we are guaranteed that nByte>0 because
  15049. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  15050. ** routines.
  15051. */
  15052. static void *sqlite3MemMalloc(int nByte){
  15053. #ifdef SQLITE_MALLOCSIZE
  15054. void *p = SQLITE_MALLOC( nByte );
  15055. if( p==0 ){
  15056. testcase( sqlite3GlobalConfig.xLog!=0 );
  15057. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15058. }
  15059. return p;
  15060. #else
  15061. sqlite3_int64 *p;
  15062. assert( nByte>0 );
  15063. nByte = ROUND8(nByte);
  15064. p = SQLITE_MALLOC( nByte+8 );
  15065. if( p ){
  15066. p[0] = nByte;
  15067. p++;
  15068. }else{
  15069. testcase( sqlite3GlobalConfig.xLog!=0 );
  15070. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15071. }
  15072. return (void *)p;
  15073. #endif
  15074. }
  15075. /*
  15076. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  15077. ** or sqlite3MemRealloc().
  15078. **
  15079. ** For this low-level routine, we already know that pPrior!=0 since
  15080. ** cases where pPrior==0 will have been intecepted and dealt with
  15081. ** by higher-level routines.
  15082. */
  15083. static void sqlite3MemFree(void *pPrior){
  15084. #ifdef SQLITE_MALLOCSIZE
  15085. SQLITE_FREE(pPrior);
  15086. #else
  15087. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15088. assert( pPrior!=0 );
  15089. p--;
  15090. SQLITE_FREE(p);
  15091. #endif
  15092. }
  15093. /*
  15094. ** Report the allocated size of a prior return from xMalloc()
  15095. ** or xRealloc().
  15096. */
  15097. static int sqlite3MemSize(void *pPrior){
  15098. #ifdef SQLITE_MALLOCSIZE
  15099. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  15100. #else
  15101. sqlite3_int64 *p;
  15102. if( pPrior==0 ) return 0;
  15103. p = (sqlite3_int64*)pPrior;
  15104. p--;
  15105. return (int)p[0];
  15106. #endif
  15107. }
  15108. /*
  15109. ** Like realloc(). Resize an allocation previously obtained from
  15110. ** sqlite3MemMalloc().
  15111. **
  15112. ** For this low-level interface, we know that pPrior!=0. Cases where
  15113. ** pPrior==0 while have been intercepted by higher-level routine and
  15114. ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
  15115. ** cases where nByte<=0 will have been intercepted by higher-level
  15116. ** routines and redirected to xFree.
  15117. */
  15118. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15119. #ifdef SQLITE_MALLOCSIZE
  15120. void *p = SQLITE_REALLOC(pPrior, nByte);
  15121. if( p==0 ){
  15122. testcase( sqlite3GlobalConfig.xLog!=0 );
  15123. sqlite3_log(SQLITE_NOMEM,
  15124. "failed memory resize %u to %u bytes",
  15125. SQLITE_MALLOCSIZE(pPrior), nByte);
  15126. }
  15127. return p;
  15128. #else
  15129. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15130. assert( pPrior!=0 && nByte>0 );
  15131. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  15132. p--;
  15133. p = SQLITE_REALLOC(p, nByte+8 );
  15134. if( p ){
  15135. p[0] = nByte;
  15136. p++;
  15137. }else{
  15138. testcase( sqlite3GlobalConfig.xLog!=0 );
  15139. sqlite3_log(SQLITE_NOMEM,
  15140. "failed memory resize %u to %u bytes",
  15141. sqlite3MemSize(pPrior), nByte);
  15142. }
  15143. return (void*)p;
  15144. #endif
  15145. }
  15146. /*
  15147. ** Round up a request size to the next valid allocation size.
  15148. */
  15149. static int sqlite3MemRoundup(int n){
  15150. return ROUND8(n);
  15151. }
  15152. /*
  15153. ** Initialize this module.
  15154. */
  15155. static int sqlite3MemInit(void *NotUsed){
  15156. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15157. int cpuCount;
  15158. size_t len;
  15159. if( _sqliteZone_ ){
  15160. return SQLITE_OK;
  15161. }
  15162. len = sizeof(cpuCount);
  15163. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  15164. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  15165. if( cpuCount>1 ){
  15166. /* defer MT decisions to system malloc */
  15167. _sqliteZone_ = malloc_default_zone();
  15168. }else{
  15169. /* only 1 core, use our own zone to contention over global locks,
  15170. ** e.g. we have our own dedicated locks */
  15171. bool success;
  15172. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  15173. malloc_set_zone_name(newzone, "Sqlite_Heap");
  15174. do{
  15175. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  15176. (void * volatile *)&_sqliteZone_);
  15177. }while(!_sqliteZone_);
  15178. if( !success ){
  15179. /* somebody registered a zone first */
  15180. malloc_destroy_zone(newzone);
  15181. }
  15182. }
  15183. #endif
  15184. UNUSED_PARAMETER(NotUsed);
  15185. return SQLITE_OK;
  15186. }
  15187. /*
  15188. ** Deinitialize this module.
  15189. */
  15190. static void sqlite3MemShutdown(void *NotUsed){
  15191. UNUSED_PARAMETER(NotUsed);
  15192. return;
  15193. }
  15194. /*
  15195. ** This routine is the only routine in this file with external linkage.
  15196. **
  15197. ** Populate the low-level memory allocation function pointers in
  15198. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15199. */
  15200. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15201. static const sqlite3_mem_methods defaultMethods = {
  15202. sqlite3MemMalloc,
  15203. sqlite3MemFree,
  15204. sqlite3MemRealloc,
  15205. sqlite3MemSize,
  15206. sqlite3MemRoundup,
  15207. sqlite3MemInit,
  15208. sqlite3MemShutdown,
  15209. 0
  15210. };
  15211. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15212. }
  15213. #endif /* SQLITE_SYSTEM_MALLOC */
  15214. /************** End of mem1.c ************************************************/
  15215. /************** Begin file mem2.c ********************************************/
  15216. /*
  15217. ** 2007 August 15
  15218. **
  15219. ** The author disclaims copyright to this source code. In place of
  15220. ** a legal notice, here is a blessing:
  15221. **
  15222. ** May you do good and not evil.
  15223. ** May you find forgiveness for yourself and forgive others.
  15224. ** May you share freely, never taking more than you give.
  15225. **
  15226. *************************************************************************
  15227. **
  15228. ** This file contains low-level memory allocation drivers for when
  15229. ** SQLite will use the standard C-library malloc/realloc/free interface
  15230. ** to obtain the memory it needs while adding lots of additional debugging
  15231. ** information to each allocation in order to help detect and fix memory
  15232. ** leaks and memory usage errors.
  15233. **
  15234. ** This file contains implementations of the low-level memory allocation
  15235. ** routines specified in the sqlite3_mem_methods object.
  15236. */
  15237. /*
  15238. ** This version of the memory allocator is used only if the
  15239. ** SQLITE_MEMDEBUG macro is defined
  15240. */
  15241. #ifdef SQLITE_MEMDEBUG
  15242. /*
  15243. ** The backtrace functionality is only available with GLIBC
  15244. */
  15245. #ifdef __GLIBC__
  15246. extern int backtrace(void**,int);
  15247. extern void backtrace_symbols_fd(void*const*,int,int);
  15248. #else
  15249. # define backtrace(A,B) 1
  15250. # define backtrace_symbols_fd(A,B,C)
  15251. #endif
  15252. /* #include <stdio.h> */
  15253. /*
  15254. ** Each memory allocation looks like this:
  15255. **
  15256. ** ------------------------------------------------------------------------
  15257. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  15258. ** ------------------------------------------------------------------------
  15259. **
  15260. ** The application code sees only a pointer to the allocation. We have
  15261. ** to back up from the allocation pointer to find the MemBlockHdr. The
  15262. ** MemBlockHdr tells us the size of the allocation and the number of
  15263. ** backtrace pointers. There is also a guard word at the end of the
  15264. ** MemBlockHdr.
  15265. */
  15266. struct MemBlockHdr {
  15267. i64 iSize; /* Size of this allocation */
  15268. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  15269. char nBacktrace; /* Number of backtraces on this alloc */
  15270. char nBacktraceSlots; /* Available backtrace slots */
  15271. u8 nTitle; /* Bytes of title; includes '\0' */
  15272. u8 eType; /* Allocation type code */
  15273. int iForeGuard; /* Guard word for sanity */
  15274. };
  15275. /*
  15276. ** Guard words
  15277. */
  15278. #define FOREGUARD 0x80F5E153
  15279. #define REARGUARD 0xE4676B53
  15280. /*
  15281. ** Number of malloc size increments to track.
  15282. */
  15283. #define NCSIZE 1000
  15284. /*
  15285. ** All of the static variables used by this module are collected
  15286. ** into a single structure named "mem". This is to keep the
  15287. ** static variables organized and to reduce namespace pollution
  15288. ** when this module is combined with other in the amalgamation.
  15289. */
  15290. static struct {
  15291. /*
  15292. ** Mutex to control access to the memory allocation subsystem.
  15293. */
  15294. sqlite3_mutex *mutex;
  15295. /*
  15296. ** Head and tail of a linked list of all outstanding allocations
  15297. */
  15298. struct MemBlockHdr *pFirst;
  15299. struct MemBlockHdr *pLast;
  15300. /*
  15301. ** The number of levels of backtrace to save in new allocations.
  15302. */
  15303. int nBacktrace;
  15304. void (*xBacktrace)(int, int, void **);
  15305. /*
  15306. ** Title text to insert in front of each block
  15307. */
  15308. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  15309. char zTitle[100]; /* The title text */
  15310. /*
  15311. ** sqlite3MallocDisallow() increments the following counter.
  15312. ** sqlite3MallocAllow() decrements it.
  15313. */
  15314. int disallow; /* Do not allow memory allocation */
  15315. /*
  15316. ** Gather statistics on the sizes of memory allocations.
  15317. ** nAlloc[i] is the number of allocation attempts of i*8
  15318. ** bytes. i==NCSIZE is the number of allocation attempts for
  15319. ** sizes more than NCSIZE*8 bytes.
  15320. */
  15321. int nAlloc[NCSIZE]; /* Total number of allocations */
  15322. int nCurrent[NCSIZE]; /* Current number of allocations */
  15323. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  15324. } mem;
  15325. /*
  15326. ** Adjust memory usage statistics
  15327. */
  15328. static void adjustStats(int iSize, int increment){
  15329. int i = ROUND8(iSize)/8;
  15330. if( i>NCSIZE-1 ){
  15331. i = NCSIZE - 1;
  15332. }
  15333. if( increment>0 ){
  15334. mem.nAlloc[i]++;
  15335. mem.nCurrent[i]++;
  15336. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  15337. mem.mxCurrent[i] = mem.nCurrent[i];
  15338. }
  15339. }else{
  15340. mem.nCurrent[i]--;
  15341. assert( mem.nCurrent[i]>=0 );
  15342. }
  15343. }
  15344. /*
  15345. ** Given an allocation, find the MemBlockHdr for that allocation.
  15346. **
  15347. ** This routine checks the guards at either end of the allocation and
  15348. ** if they are incorrect it asserts.
  15349. */
  15350. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  15351. struct MemBlockHdr *p;
  15352. int *pInt;
  15353. u8 *pU8;
  15354. int nReserve;
  15355. p = (struct MemBlockHdr*)pAllocation;
  15356. p--;
  15357. assert( p->iForeGuard==(int)FOREGUARD );
  15358. nReserve = ROUND8(p->iSize);
  15359. pInt = (int*)pAllocation;
  15360. pU8 = (u8*)pAllocation;
  15361. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  15362. /* This checks any of the "extra" bytes allocated due
  15363. ** to rounding up to an 8 byte boundary to ensure
  15364. ** they haven't been overwritten.
  15365. */
  15366. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  15367. return p;
  15368. }
  15369. /*
  15370. ** Return the number of bytes currently allocated at address p.
  15371. */
  15372. static int sqlite3MemSize(void *p){
  15373. struct MemBlockHdr *pHdr;
  15374. if( !p ){
  15375. return 0;
  15376. }
  15377. pHdr = sqlite3MemsysGetHeader(p);
  15378. return (int)pHdr->iSize;
  15379. }
  15380. /*
  15381. ** Initialize the memory allocation subsystem.
  15382. */
  15383. static int sqlite3MemInit(void *NotUsed){
  15384. UNUSED_PARAMETER(NotUsed);
  15385. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  15386. if( !sqlite3GlobalConfig.bMemstat ){
  15387. /* If memory status is enabled, then the malloc.c wrapper will already
  15388. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  15389. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15390. }
  15391. return SQLITE_OK;
  15392. }
  15393. /*
  15394. ** Deinitialize the memory allocation subsystem.
  15395. */
  15396. static void sqlite3MemShutdown(void *NotUsed){
  15397. UNUSED_PARAMETER(NotUsed);
  15398. mem.mutex = 0;
  15399. }
  15400. /*
  15401. ** Round up a request size to the next valid allocation size.
  15402. */
  15403. static int sqlite3MemRoundup(int n){
  15404. return ROUND8(n);
  15405. }
  15406. /*
  15407. ** Fill a buffer with pseudo-random bytes. This is used to preset
  15408. ** the content of a new memory allocation to unpredictable values and
  15409. ** to clear the content of a freed allocation to unpredictable values.
  15410. */
  15411. static void randomFill(char *pBuf, int nByte){
  15412. unsigned int x, y, r;
  15413. x = SQLITE_PTR_TO_INT(pBuf);
  15414. y = nByte | 1;
  15415. while( nByte >= 4 ){
  15416. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  15417. y = y*1103515245 + 12345;
  15418. r = x ^ y;
  15419. *(int*)pBuf = r;
  15420. pBuf += 4;
  15421. nByte -= 4;
  15422. }
  15423. while( nByte-- > 0 ){
  15424. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  15425. y = y*1103515245 + 12345;
  15426. r = x ^ y;
  15427. *(pBuf++) = r & 0xff;
  15428. }
  15429. }
  15430. /*
  15431. ** Allocate nByte bytes of memory.
  15432. */
  15433. static void *sqlite3MemMalloc(int nByte){
  15434. struct MemBlockHdr *pHdr;
  15435. void **pBt;
  15436. char *z;
  15437. int *pInt;
  15438. void *p = 0;
  15439. int totalSize;
  15440. int nReserve;
  15441. sqlite3_mutex_enter(mem.mutex);
  15442. assert( mem.disallow==0 );
  15443. nReserve = ROUND8(nByte);
  15444. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  15445. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  15446. p = malloc(totalSize);
  15447. if( p ){
  15448. z = p;
  15449. pBt = (void**)&z[mem.nTitle];
  15450. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  15451. pHdr->pNext = 0;
  15452. pHdr->pPrev = mem.pLast;
  15453. if( mem.pLast ){
  15454. mem.pLast->pNext = pHdr;
  15455. }else{
  15456. mem.pFirst = pHdr;
  15457. }
  15458. mem.pLast = pHdr;
  15459. pHdr->iForeGuard = FOREGUARD;
  15460. pHdr->eType = MEMTYPE_HEAP;
  15461. pHdr->nBacktraceSlots = mem.nBacktrace;
  15462. pHdr->nTitle = mem.nTitle;
  15463. if( mem.nBacktrace ){
  15464. void *aAddr[40];
  15465. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  15466. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  15467. assert(pBt[0]);
  15468. if( mem.xBacktrace ){
  15469. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  15470. }
  15471. }else{
  15472. pHdr->nBacktrace = 0;
  15473. }
  15474. if( mem.nTitle ){
  15475. memcpy(z, mem.zTitle, mem.nTitle);
  15476. }
  15477. pHdr->iSize = nByte;
  15478. adjustStats(nByte, +1);
  15479. pInt = (int*)&pHdr[1];
  15480. pInt[nReserve/sizeof(int)] = REARGUARD;
  15481. randomFill((char*)pInt, nByte);
  15482. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  15483. p = (void*)pInt;
  15484. }
  15485. sqlite3_mutex_leave(mem.mutex);
  15486. return p;
  15487. }
  15488. /*
  15489. ** Free memory.
  15490. */
  15491. static void sqlite3MemFree(void *pPrior){
  15492. struct MemBlockHdr *pHdr;
  15493. void **pBt;
  15494. char *z;
  15495. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  15496. || mem.mutex!=0 );
  15497. pHdr = sqlite3MemsysGetHeader(pPrior);
  15498. pBt = (void**)pHdr;
  15499. pBt -= pHdr->nBacktraceSlots;
  15500. sqlite3_mutex_enter(mem.mutex);
  15501. if( pHdr->pPrev ){
  15502. assert( pHdr->pPrev->pNext==pHdr );
  15503. pHdr->pPrev->pNext = pHdr->pNext;
  15504. }else{
  15505. assert( mem.pFirst==pHdr );
  15506. mem.pFirst = pHdr->pNext;
  15507. }
  15508. if( pHdr->pNext ){
  15509. assert( pHdr->pNext->pPrev==pHdr );
  15510. pHdr->pNext->pPrev = pHdr->pPrev;
  15511. }else{
  15512. assert( mem.pLast==pHdr );
  15513. mem.pLast = pHdr->pPrev;
  15514. }
  15515. z = (char*)pBt;
  15516. z -= pHdr->nTitle;
  15517. adjustStats((int)pHdr->iSize, -1);
  15518. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  15519. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  15520. free(z);
  15521. sqlite3_mutex_leave(mem.mutex);
  15522. }
  15523. /*
  15524. ** Change the size of an existing memory allocation.
  15525. **
  15526. ** For this debugging implementation, we *always* make a copy of the
  15527. ** allocation into a new place in memory. In this way, if the
  15528. ** higher level code is using pointer to the old allocation, it is
  15529. ** much more likely to break and we are much more liking to find
  15530. ** the error.
  15531. */
  15532. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15533. struct MemBlockHdr *pOldHdr;
  15534. void *pNew;
  15535. assert( mem.disallow==0 );
  15536. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  15537. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  15538. pNew = sqlite3MemMalloc(nByte);
  15539. if( pNew ){
  15540. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  15541. if( nByte>pOldHdr->iSize ){
  15542. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  15543. }
  15544. sqlite3MemFree(pPrior);
  15545. }
  15546. return pNew;
  15547. }
  15548. /*
  15549. ** Populate the low-level memory allocation function pointers in
  15550. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15551. */
  15552. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15553. static const sqlite3_mem_methods defaultMethods = {
  15554. sqlite3MemMalloc,
  15555. sqlite3MemFree,
  15556. sqlite3MemRealloc,
  15557. sqlite3MemSize,
  15558. sqlite3MemRoundup,
  15559. sqlite3MemInit,
  15560. sqlite3MemShutdown,
  15561. 0
  15562. };
  15563. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15564. }
  15565. /*
  15566. ** Set the "type" of an allocation.
  15567. */
  15568. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  15569. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15570. struct MemBlockHdr *pHdr;
  15571. pHdr = sqlite3MemsysGetHeader(p);
  15572. assert( pHdr->iForeGuard==FOREGUARD );
  15573. pHdr->eType = eType;
  15574. }
  15575. }
  15576. /*
  15577. ** Return TRUE if the mask of type in eType matches the type of the
  15578. ** allocation p. Also return true if p==NULL.
  15579. **
  15580. ** This routine is designed for use within an assert() statement, to
  15581. ** verify the type of an allocation. For example:
  15582. **
  15583. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  15584. */
  15585. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  15586. int rc = 1;
  15587. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15588. struct MemBlockHdr *pHdr;
  15589. pHdr = sqlite3MemsysGetHeader(p);
  15590. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15591. if( (pHdr->eType&eType)==0 ){
  15592. rc = 0;
  15593. }
  15594. }
  15595. return rc;
  15596. }
  15597. /*
  15598. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  15599. ** allocation p. Also return true if p==NULL.
  15600. **
  15601. ** This routine is designed for use within an assert() statement, to
  15602. ** verify the type of an allocation. For example:
  15603. **
  15604. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  15605. */
  15606. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  15607. int rc = 1;
  15608. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15609. struct MemBlockHdr *pHdr;
  15610. pHdr = sqlite3MemsysGetHeader(p);
  15611. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15612. if( (pHdr->eType&eType)!=0 ){
  15613. rc = 0;
  15614. }
  15615. }
  15616. return rc;
  15617. }
  15618. /*
  15619. ** Set the number of backtrace levels kept for each allocation.
  15620. ** A value of zero turns off backtracing. The number is always rounded
  15621. ** up to a multiple of 2.
  15622. */
  15623. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  15624. if( depth<0 ){ depth = 0; }
  15625. if( depth>20 ){ depth = 20; }
  15626. depth = (depth+1)&0xfe;
  15627. mem.nBacktrace = depth;
  15628. }
  15629. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  15630. mem.xBacktrace = xBacktrace;
  15631. }
  15632. /*
  15633. ** Set the title string for subsequent allocations.
  15634. */
  15635. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  15636. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  15637. sqlite3_mutex_enter(mem.mutex);
  15638. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  15639. memcpy(mem.zTitle, zTitle, n);
  15640. mem.zTitle[n] = 0;
  15641. mem.nTitle = ROUND8(n);
  15642. sqlite3_mutex_leave(mem.mutex);
  15643. }
  15644. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  15645. struct MemBlockHdr *pHdr;
  15646. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15647. void **pBt = (void**)pHdr;
  15648. pBt -= pHdr->nBacktraceSlots;
  15649. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  15650. }
  15651. }
  15652. /*
  15653. ** Open the file indicated and write a log of all unfreed memory
  15654. ** allocations into that log.
  15655. */
  15656. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  15657. FILE *out;
  15658. struct MemBlockHdr *pHdr;
  15659. void **pBt;
  15660. int i;
  15661. out = fopen(zFilename, "w");
  15662. if( out==0 ){
  15663. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  15664. zFilename);
  15665. return;
  15666. }
  15667. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15668. char *z = (char*)pHdr;
  15669. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  15670. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  15671. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  15672. if( pHdr->nBacktrace ){
  15673. fflush(out);
  15674. pBt = (void**)pHdr;
  15675. pBt -= pHdr->nBacktraceSlots;
  15676. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  15677. fprintf(out, "\n");
  15678. }
  15679. }
  15680. fprintf(out, "COUNTS:\n");
  15681. for(i=0; i<NCSIZE-1; i++){
  15682. if( mem.nAlloc[i] ){
  15683. fprintf(out, " %5d: %10d %10d %10d\n",
  15684. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  15685. }
  15686. }
  15687. if( mem.nAlloc[NCSIZE-1] ){
  15688. fprintf(out, " %5d: %10d %10d %10d\n",
  15689. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  15690. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  15691. }
  15692. fclose(out);
  15693. }
  15694. /*
  15695. ** Return the number of times sqlite3MemMalloc() has been called.
  15696. */
  15697. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  15698. int i;
  15699. int nTotal = 0;
  15700. for(i=0; i<NCSIZE; i++){
  15701. nTotal += mem.nAlloc[i];
  15702. }
  15703. return nTotal;
  15704. }
  15705. #endif /* SQLITE_MEMDEBUG */
  15706. /************** End of mem2.c ************************************************/
  15707. /************** Begin file mem3.c ********************************************/
  15708. /*
  15709. ** 2007 October 14
  15710. **
  15711. ** The author disclaims copyright to this source code. In place of
  15712. ** a legal notice, here is a blessing:
  15713. **
  15714. ** May you do good and not evil.
  15715. ** May you find forgiveness for yourself and forgive others.
  15716. ** May you share freely, never taking more than you give.
  15717. **
  15718. *************************************************************************
  15719. ** This file contains the C functions that implement a memory
  15720. ** allocation subsystem for use by SQLite.
  15721. **
  15722. ** This version of the memory allocation subsystem omits all
  15723. ** use of malloc(). The SQLite user supplies a block of memory
  15724. ** before calling sqlite3_initialize() from which allocations
  15725. ** are made and returned by the xMalloc() and xRealloc()
  15726. ** implementations. Once sqlite3_initialize() has been called,
  15727. ** the amount of memory available to SQLite is fixed and cannot
  15728. ** be changed.
  15729. **
  15730. ** This version of the memory allocation subsystem is included
  15731. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  15732. */
  15733. /*
  15734. ** This version of the memory allocator is only built into the library
  15735. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  15736. ** mean that the library will use a memory-pool by default, just that
  15737. ** it is available. The mempool allocator is activated by calling
  15738. ** sqlite3_config().
  15739. */
  15740. #ifdef SQLITE_ENABLE_MEMSYS3
  15741. /*
  15742. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  15743. */
  15744. #define MX_SMALL 10
  15745. /*
  15746. ** Number of freelist hash slots
  15747. */
  15748. #define N_HASH 61
  15749. /*
  15750. ** A memory allocation (also called a "chunk") consists of two or
  15751. ** more blocks where each block is 8 bytes. The first 8 bytes are
  15752. ** a header that is not returned to the user.
  15753. **
  15754. ** A chunk is two or more blocks that is either checked out or
  15755. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  15756. ** size of the allocation in blocks if the allocation is free.
  15757. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  15758. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  15759. ** is true if the previous chunk is checked out and false if the
  15760. ** previous chunk is free. The u.hdr.prevSize field is the size of
  15761. ** the previous chunk in blocks if the previous chunk is on the
  15762. ** freelist. If the previous chunk is checked out, then
  15763. ** u.hdr.prevSize can be part of the data for that chunk and should
  15764. ** not be read or written.
  15765. **
  15766. ** We often identify a chunk by its index in mem3.aPool[]. When
  15767. ** this is done, the chunk index refers to the second block of
  15768. ** the chunk. In this way, the first chunk has an index of 1.
  15769. ** A chunk index of 0 means "no such chunk" and is the equivalent
  15770. ** of a NULL pointer.
  15771. **
  15772. ** The second block of free chunks is of the form u.list. The
  15773. ** two fields form a double-linked list of chunks of related sizes.
  15774. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  15775. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  15776. **
  15777. ** The second block of a chunk is user data if the chunk is checked
  15778. ** out. If a chunk is checked out, the user data may extend into
  15779. ** the u.hdr.prevSize value of the following chunk.
  15780. */
  15781. typedef struct Mem3Block Mem3Block;
  15782. struct Mem3Block {
  15783. union {
  15784. struct {
  15785. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  15786. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  15787. } hdr;
  15788. struct {
  15789. u32 next; /* Index in mem3.aPool[] of next free chunk */
  15790. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  15791. } list;
  15792. } u;
  15793. };
  15794. /*
  15795. ** All of the static variables used by this module are collected
  15796. ** into a single structure named "mem3". This is to keep the
  15797. ** static variables organized and to reduce namespace pollution
  15798. ** when this module is combined with other in the amalgamation.
  15799. */
  15800. static SQLITE_WSD struct Mem3Global {
  15801. /*
  15802. ** Memory available for allocation. nPool is the size of the array
  15803. ** (in Mem3Blocks) pointed to by aPool less 2.
  15804. */
  15805. u32 nPool;
  15806. Mem3Block *aPool;
  15807. /*
  15808. ** True if we are evaluating an out-of-memory callback.
  15809. */
  15810. int alarmBusy;
  15811. /*
  15812. ** Mutex to control access to the memory allocation subsystem.
  15813. */
  15814. sqlite3_mutex *mutex;
  15815. /*
  15816. ** The minimum amount of free space that we have seen.
  15817. */
  15818. u32 mnMaster;
  15819. /*
  15820. ** iMaster is the index of the master chunk. Most new allocations
  15821. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  15822. ** of the current master. iMaster is 0 if there is not master chunk.
  15823. ** The master chunk is not in either the aiHash[] or aiSmall[].
  15824. */
  15825. u32 iMaster;
  15826. u32 szMaster;
  15827. /*
  15828. ** Array of lists of free blocks according to the block size
  15829. ** for smaller chunks, or a hash on the block size for larger
  15830. ** chunks.
  15831. */
  15832. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  15833. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  15834. } mem3 = { 97535575 };
  15835. #define mem3 GLOBAL(struct Mem3Global, mem3)
  15836. /*
  15837. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  15838. ** on. *pRoot is the list that i is a member of.
  15839. */
  15840. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  15841. u32 next = mem3.aPool[i].u.list.next;
  15842. u32 prev = mem3.aPool[i].u.list.prev;
  15843. assert( sqlite3_mutex_held(mem3.mutex) );
  15844. if( prev==0 ){
  15845. *pRoot = next;
  15846. }else{
  15847. mem3.aPool[prev].u.list.next = next;
  15848. }
  15849. if( next ){
  15850. mem3.aPool[next].u.list.prev = prev;
  15851. }
  15852. mem3.aPool[i].u.list.next = 0;
  15853. mem3.aPool[i].u.list.prev = 0;
  15854. }
  15855. /*
  15856. ** Unlink the chunk at index i from
  15857. ** whatever list is currently a member of.
  15858. */
  15859. static void memsys3Unlink(u32 i){
  15860. u32 size, hash;
  15861. assert( sqlite3_mutex_held(mem3.mutex) );
  15862. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15863. assert( i>=1 );
  15864. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15865. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15866. assert( size>=2 );
  15867. if( size <= MX_SMALL ){
  15868. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  15869. }else{
  15870. hash = size % N_HASH;
  15871. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  15872. }
  15873. }
  15874. /*
  15875. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  15876. ** at *pRoot.
  15877. */
  15878. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  15879. assert( sqlite3_mutex_held(mem3.mutex) );
  15880. mem3.aPool[i].u.list.next = *pRoot;
  15881. mem3.aPool[i].u.list.prev = 0;
  15882. if( *pRoot ){
  15883. mem3.aPool[*pRoot].u.list.prev = i;
  15884. }
  15885. *pRoot = i;
  15886. }
  15887. /*
  15888. ** Link the chunk at index i into either the appropriate
  15889. ** small chunk list, or into the large chunk hash table.
  15890. */
  15891. static void memsys3Link(u32 i){
  15892. u32 size, hash;
  15893. assert( sqlite3_mutex_held(mem3.mutex) );
  15894. assert( i>=1 );
  15895. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15896. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15897. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15898. assert( size>=2 );
  15899. if( size <= MX_SMALL ){
  15900. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  15901. }else{
  15902. hash = size % N_HASH;
  15903. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  15904. }
  15905. }
  15906. /*
  15907. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  15908. ** will already be held (obtained by code in malloc.c) if
  15909. ** sqlite3GlobalConfig.bMemStat is true.
  15910. */
  15911. static void memsys3Enter(void){
  15912. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  15913. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15914. }
  15915. sqlite3_mutex_enter(mem3.mutex);
  15916. }
  15917. static void memsys3Leave(void){
  15918. sqlite3_mutex_leave(mem3.mutex);
  15919. }
  15920. /*
  15921. ** Called when we are unable to satisfy an allocation of nBytes.
  15922. */
  15923. static void memsys3OutOfMemory(int nByte){
  15924. if( !mem3.alarmBusy ){
  15925. mem3.alarmBusy = 1;
  15926. assert( sqlite3_mutex_held(mem3.mutex) );
  15927. sqlite3_mutex_leave(mem3.mutex);
  15928. sqlite3_release_memory(nByte);
  15929. sqlite3_mutex_enter(mem3.mutex);
  15930. mem3.alarmBusy = 0;
  15931. }
  15932. }
  15933. /*
  15934. ** Chunk i is a free chunk that has been unlinked. Adjust its
  15935. ** size parameters for check-out and return a pointer to the
  15936. ** user portion of the chunk.
  15937. */
  15938. static void *memsys3Checkout(u32 i, u32 nBlock){
  15939. u32 x;
  15940. assert( sqlite3_mutex_held(mem3.mutex) );
  15941. assert( i>=1 );
  15942. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  15943. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  15944. x = mem3.aPool[i-1].u.hdr.size4x;
  15945. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  15946. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  15947. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  15948. return &mem3.aPool[i];
  15949. }
  15950. /*
  15951. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  15952. ** Return a pointer to the new allocation. Or, if the master chunk
  15953. ** is not large enough, return 0.
  15954. */
  15955. static void *memsys3FromMaster(u32 nBlock){
  15956. assert( sqlite3_mutex_held(mem3.mutex) );
  15957. assert( mem3.szMaster>=nBlock );
  15958. if( nBlock>=mem3.szMaster-1 ){
  15959. /* Use the entire master */
  15960. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  15961. mem3.iMaster = 0;
  15962. mem3.szMaster = 0;
  15963. mem3.mnMaster = 0;
  15964. return p;
  15965. }else{
  15966. /* Split the master block. Return the tail. */
  15967. u32 newi, x;
  15968. newi = mem3.iMaster + mem3.szMaster - nBlock;
  15969. assert( newi > mem3.iMaster+1 );
  15970. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  15971. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  15972. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  15973. mem3.szMaster -= nBlock;
  15974. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  15975. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  15976. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  15977. if( mem3.szMaster < mem3.mnMaster ){
  15978. mem3.mnMaster = mem3.szMaster;
  15979. }
  15980. return (void*)&mem3.aPool[newi];
  15981. }
  15982. }
  15983. /*
  15984. ** *pRoot is the head of a list of free chunks of the same size
  15985. ** or same size hash. In other words, *pRoot is an entry in either
  15986. ** mem3.aiSmall[] or mem3.aiHash[].
  15987. **
  15988. ** This routine examines all entries on the given list and tries
  15989. ** to coalesce each entries with adjacent free chunks.
  15990. **
  15991. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  15992. ** the current mem3.iMaster with the new larger chunk. In order for
  15993. ** this mem3.iMaster replacement to work, the master chunk must be
  15994. ** linked into the hash tables. That is not the normal state of
  15995. ** affairs, of course. The calling routine must link the master
  15996. ** chunk before invoking this routine, then must unlink the (possibly
  15997. ** changed) master chunk once this routine has finished.
  15998. */
  15999. static void memsys3Merge(u32 *pRoot){
  16000. u32 iNext, prev, size, i, x;
  16001. assert( sqlite3_mutex_held(mem3.mutex) );
  16002. for(i=*pRoot; i>0; i=iNext){
  16003. iNext = mem3.aPool[i].u.list.next;
  16004. size = mem3.aPool[i-1].u.hdr.size4x;
  16005. assert( (size&1)==0 );
  16006. if( (size&2)==0 ){
  16007. memsys3UnlinkFromList(i, pRoot);
  16008. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  16009. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  16010. if( prev==iNext ){
  16011. iNext = mem3.aPool[prev].u.list.next;
  16012. }
  16013. memsys3Unlink(prev);
  16014. size = i + size/4 - prev;
  16015. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  16016. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  16017. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  16018. memsys3Link(prev);
  16019. i = prev;
  16020. }else{
  16021. size /= 4;
  16022. }
  16023. if( size>mem3.szMaster ){
  16024. mem3.iMaster = i;
  16025. mem3.szMaster = size;
  16026. }
  16027. }
  16028. }
  16029. /*
  16030. ** Return a block of memory of at least nBytes in size.
  16031. ** Return NULL if unable.
  16032. **
  16033. ** This function assumes that the necessary mutexes, if any, are
  16034. ** already held by the caller. Hence "Unsafe".
  16035. */
  16036. static void *memsys3MallocUnsafe(int nByte){
  16037. u32 i;
  16038. u32 nBlock;
  16039. u32 toFree;
  16040. assert( sqlite3_mutex_held(mem3.mutex) );
  16041. assert( sizeof(Mem3Block)==8 );
  16042. if( nByte<=12 ){
  16043. nBlock = 2;
  16044. }else{
  16045. nBlock = (nByte + 11)/8;
  16046. }
  16047. assert( nBlock>=2 );
  16048. /* STEP 1:
  16049. ** Look for an entry of the correct size in either the small
  16050. ** chunk table or in the large chunk hash table. This is
  16051. ** successful most of the time (about 9 times out of 10).
  16052. */
  16053. if( nBlock <= MX_SMALL ){
  16054. i = mem3.aiSmall[nBlock-2];
  16055. if( i>0 ){
  16056. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  16057. return memsys3Checkout(i, nBlock);
  16058. }
  16059. }else{
  16060. int hash = nBlock % N_HASH;
  16061. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  16062. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  16063. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  16064. return memsys3Checkout(i, nBlock);
  16065. }
  16066. }
  16067. }
  16068. /* STEP 2:
  16069. ** Try to satisfy the allocation by carving a piece off of the end
  16070. ** of the master chunk. This step usually works if step 1 fails.
  16071. */
  16072. if( mem3.szMaster>=nBlock ){
  16073. return memsys3FromMaster(nBlock);
  16074. }
  16075. /* STEP 3:
  16076. ** Loop through the entire memory pool. Coalesce adjacent free
  16077. ** chunks. Recompute the master chunk as the largest free chunk.
  16078. ** Then try again to satisfy the allocation by carving a piece off
  16079. ** of the end of the master chunk. This step happens very
  16080. ** rarely (we hope!)
  16081. */
  16082. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  16083. memsys3OutOfMemory(toFree);
  16084. if( mem3.iMaster ){
  16085. memsys3Link(mem3.iMaster);
  16086. mem3.iMaster = 0;
  16087. mem3.szMaster = 0;
  16088. }
  16089. for(i=0; i<N_HASH; i++){
  16090. memsys3Merge(&mem3.aiHash[i]);
  16091. }
  16092. for(i=0; i<MX_SMALL-1; i++){
  16093. memsys3Merge(&mem3.aiSmall[i]);
  16094. }
  16095. if( mem3.szMaster ){
  16096. memsys3Unlink(mem3.iMaster);
  16097. if( mem3.szMaster>=nBlock ){
  16098. return memsys3FromMaster(nBlock);
  16099. }
  16100. }
  16101. }
  16102. /* If none of the above worked, then we fail. */
  16103. return 0;
  16104. }
  16105. /*
  16106. ** Free an outstanding memory allocation.
  16107. **
  16108. ** This function assumes that the necessary mutexes, if any, are
  16109. ** already held by the caller. Hence "Unsafe".
  16110. */
  16111. static void memsys3FreeUnsafe(void *pOld){
  16112. Mem3Block *p = (Mem3Block*)pOld;
  16113. int i;
  16114. u32 size, x;
  16115. assert( sqlite3_mutex_held(mem3.mutex) );
  16116. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  16117. i = p - mem3.aPool;
  16118. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  16119. size = mem3.aPool[i-1].u.hdr.size4x/4;
  16120. assert( i+size<=mem3.nPool+1 );
  16121. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  16122. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  16123. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  16124. memsys3Link(i);
  16125. /* Try to expand the master using the newly freed chunk */
  16126. if( mem3.iMaster ){
  16127. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  16128. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  16129. mem3.iMaster -= size;
  16130. mem3.szMaster += size;
  16131. memsys3Unlink(mem3.iMaster);
  16132. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16133. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16134. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16135. }
  16136. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16137. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  16138. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  16139. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  16140. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16141. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16142. }
  16143. }
  16144. }
  16145. /*
  16146. ** Return the size of an outstanding allocation, in bytes. The
  16147. ** size returned omits the 8-byte header overhead. This only
  16148. ** works for chunks that are currently checked out.
  16149. */
  16150. static int memsys3Size(void *p){
  16151. Mem3Block *pBlock;
  16152. if( p==0 ) return 0;
  16153. pBlock = (Mem3Block*)p;
  16154. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  16155. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  16156. }
  16157. /*
  16158. ** Round up a request size to the next valid allocation size.
  16159. */
  16160. static int memsys3Roundup(int n){
  16161. if( n<=12 ){
  16162. return 12;
  16163. }else{
  16164. return ((n+11)&~7) - 4;
  16165. }
  16166. }
  16167. /*
  16168. ** Allocate nBytes of memory.
  16169. */
  16170. static void *memsys3Malloc(int nBytes){
  16171. sqlite3_int64 *p;
  16172. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  16173. memsys3Enter();
  16174. p = memsys3MallocUnsafe(nBytes);
  16175. memsys3Leave();
  16176. return (void*)p;
  16177. }
  16178. /*
  16179. ** Free memory.
  16180. */
  16181. static void memsys3Free(void *pPrior){
  16182. assert( pPrior );
  16183. memsys3Enter();
  16184. memsys3FreeUnsafe(pPrior);
  16185. memsys3Leave();
  16186. }
  16187. /*
  16188. ** Change the size of an existing memory allocation
  16189. */
  16190. static void *memsys3Realloc(void *pPrior, int nBytes){
  16191. int nOld;
  16192. void *p;
  16193. if( pPrior==0 ){
  16194. return sqlite3_malloc(nBytes);
  16195. }
  16196. if( nBytes<=0 ){
  16197. sqlite3_free(pPrior);
  16198. return 0;
  16199. }
  16200. nOld = memsys3Size(pPrior);
  16201. if( nBytes<=nOld && nBytes>=nOld-128 ){
  16202. return pPrior;
  16203. }
  16204. memsys3Enter();
  16205. p = memsys3MallocUnsafe(nBytes);
  16206. if( p ){
  16207. if( nOld<nBytes ){
  16208. memcpy(p, pPrior, nOld);
  16209. }else{
  16210. memcpy(p, pPrior, nBytes);
  16211. }
  16212. memsys3FreeUnsafe(pPrior);
  16213. }
  16214. memsys3Leave();
  16215. return p;
  16216. }
  16217. /*
  16218. ** Initialize this module.
  16219. */
  16220. static int memsys3Init(void *NotUsed){
  16221. UNUSED_PARAMETER(NotUsed);
  16222. if( !sqlite3GlobalConfig.pHeap ){
  16223. return SQLITE_ERROR;
  16224. }
  16225. /* Store a pointer to the memory block in global structure mem3. */
  16226. assert( sizeof(Mem3Block)==8 );
  16227. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  16228. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  16229. /* Initialize the master block. */
  16230. mem3.szMaster = mem3.nPool;
  16231. mem3.mnMaster = mem3.szMaster;
  16232. mem3.iMaster = 1;
  16233. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  16234. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  16235. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  16236. return SQLITE_OK;
  16237. }
  16238. /*
  16239. ** Deinitialize this module.
  16240. */
  16241. static void memsys3Shutdown(void *NotUsed){
  16242. UNUSED_PARAMETER(NotUsed);
  16243. mem3.mutex = 0;
  16244. return;
  16245. }
  16246. /*
  16247. ** Open the file indicated and write a log of all unfreed memory
  16248. ** allocations into that log.
  16249. */
  16250. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  16251. #ifdef SQLITE_DEBUG
  16252. FILE *out;
  16253. u32 i, j;
  16254. u32 size;
  16255. if( zFilename==0 || zFilename[0]==0 ){
  16256. out = stdout;
  16257. }else{
  16258. out = fopen(zFilename, "w");
  16259. if( out==0 ){
  16260. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16261. zFilename);
  16262. return;
  16263. }
  16264. }
  16265. memsys3Enter();
  16266. fprintf(out, "CHUNKS:\n");
  16267. for(i=1; i<=mem3.nPool; i+=size/4){
  16268. size = mem3.aPool[i-1].u.hdr.size4x;
  16269. if( size/4<=1 ){
  16270. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  16271. assert( 0 );
  16272. break;
  16273. }
  16274. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  16275. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  16276. assert( 0 );
  16277. break;
  16278. }
  16279. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  16280. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  16281. assert( 0 );
  16282. break;
  16283. }
  16284. if( size&1 ){
  16285. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  16286. }else{
  16287. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  16288. i==mem3.iMaster ? " **master**" : "");
  16289. }
  16290. }
  16291. for(i=0; i<MX_SMALL-1; i++){
  16292. if( mem3.aiSmall[i]==0 ) continue;
  16293. fprintf(out, "small(%2d):", i);
  16294. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  16295. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16296. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16297. }
  16298. fprintf(out, "\n");
  16299. }
  16300. for(i=0; i<N_HASH; i++){
  16301. if( mem3.aiHash[i]==0 ) continue;
  16302. fprintf(out, "hash(%2d):", i);
  16303. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  16304. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16305. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16306. }
  16307. fprintf(out, "\n");
  16308. }
  16309. fprintf(out, "master=%d\n", mem3.iMaster);
  16310. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  16311. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  16312. sqlite3_mutex_leave(mem3.mutex);
  16313. if( out==stdout ){
  16314. fflush(stdout);
  16315. }else{
  16316. fclose(out);
  16317. }
  16318. #else
  16319. UNUSED_PARAMETER(zFilename);
  16320. #endif
  16321. }
  16322. /*
  16323. ** This routine is the only routine in this file with external
  16324. ** linkage.
  16325. **
  16326. ** Populate the low-level memory allocation function pointers in
  16327. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  16328. ** arguments specify the block of memory to manage.
  16329. **
  16330. ** This routine is only called by sqlite3_config(), and therefore
  16331. ** is not required to be threadsafe (it is not).
  16332. */
  16333. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  16334. static const sqlite3_mem_methods mempoolMethods = {
  16335. memsys3Malloc,
  16336. memsys3Free,
  16337. memsys3Realloc,
  16338. memsys3Size,
  16339. memsys3Roundup,
  16340. memsys3Init,
  16341. memsys3Shutdown,
  16342. 0
  16343. };
  16344. return &mempoolMethods;
  16345. }
  16346. #endif /* SQLITE_ENABLE_MEMSYS3 */
  16347. /************** End of mem3.c ************************************************/
  16348. /************** Begin file mem5.c ********************************************/
  16349. /*
  16350. ** 2007 October 14
  16351. **
  16352. ** The author disclaims copyright to this source code. In place of
  16353. ** a legal notice, here is a blessing:
  16354. **
  16355. ** May you do good and not evil.
  16356. ** May you find forgiveness for yourself and forgive others.
  16357. ** May you share freely, never taking more than you give.
  16358. **
  16359. *************************************************************************
  16360. ** This file contains the C functions that implement a memory
  16361. ** allocation subsystem for use by SQLite.
  16362. **
  16363. ** This version of the memory allocation subsystem omits all
  16364. ** use of malloc(). The application gives SQLite a block of memory
  16365. ** before calling sqlite3_initialize() from which allocations
  16366. ** are made and returned by the xMalloc() and xRealloc()
  16367. ** implementations. Once sqlite3_initialize() has been called,
  16368. ** the amount of memory available to SQLite is fixed and cannot
  16369. ** be changed.
  16370. **
  16371. ** This version of the memory allocation subsystem is included
  16372. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  16373. **
  16374. ** This memory allocator uses the following algorithm:
  16375. **
  16376. ** 1. All memory allocations sizes are rounded up to a power of 2.
  16377. **
  16378. ** 2. If two adjacent free blocks are the halves of a larger block,
  16379. ** then the two blocks are coalesed into the single larger block.
  16380. **
  16381. ** 3. New memory is allocated from the first available free block.
  16382. **
  16383. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  16384. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  16385. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  16386. **
  16387. ** Let n be the size of the largest allocation divided by the minimum
  16388. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  16389. ** be the maximum amount of memory ever outstanding at one time. Let
  16390. ** N be the total amount of memory available for allocation. Robson
  16391. ** proved that this memory allocator will never breakdown due to
  16392. ** fragmentation as long as the following constraint holds:
  16393. **
  16394. ** N >= M*(1 + log2(n)/2) - n + 1
  16395. **
  16396. ** The sqlite3_status() logic tracks the maximum values of n and M so
  16397. ** that an application can, at any time, verify this constraint.
  16398. */
  16399. /*
  16400. ** This version of the memory allocator is used only when
  16401. ** SQLITE_ENABLE_MEMSYS5 is defined.
  16402. */
  16403. #ifdef SQLITE_ENABLE_MEMSYS5
  16404. /*
  16405. ** A minimum allocation is an instance of the following structure.
  16406. ** Larger allocations are an array of these structures where the
  16407. ** size of the array is a power of 2.
  16408. **
  16409. ** The size of this object must be a power of two. That fact is
  16410. ** verified in memsys5Init().
  16411. */
  16412. typedef struct Mem5Link Mem5Link;
  16413. struct Mem5Link {
  16414. int next; /* Index of next free chunk */
  16415. int prev; /* Index of previous free chunk */
  16416. };
  16417. /*
  16418. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  16419. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  16420. ** it is not actually possible to reach this limit.
  16421. */
  16422. #define LOGMAX 30
  16423. /*
  16424. ** Masks used for mem5.aCtrl[] elements.
  16425. */
  16426. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  16427. #define CTRL_FREE 0x20 /* True if not checked out */
  16428. /*
  16429. ** All of the static variables used by this module are collected
  16430. ** into a single structure named "mem5". This is to keep the
  16431. ** static variables organized and to reduce namespace pollution
  16432. ** when this module is combined with other in the amalgamation.
  16433. */
  16434. static SQLITE_WSD struct Mem5Global {
  16435. /*
  16436. ** Memory available for allocation
  16437. */
  16438. int szAtom; /* Smallest possible allocation in bytes */
  16439. int nBlock; /* Number of szAtom sized blocks in zPool */
  16440. u8 *zPool; /* Memory available to be allocated */
  16441. /*
  16442. ** Mutex to control access to the memory allocation subsystem.
  16443. */
  16444. sqlite3_mutex *mutex;
  16445. /*
  16446. ** Performance statistics
  16447. */
  16448. u64 nAlloc; /* Total number of calls to malloc */
  16449. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  16450. u64 totalExcess; /* Total internal fragmentation */
  16451. u32 currentOut; /* Current checkout, including internal fragmentation */
  16452. u32 currentCount; /* Current number of distinct checkouts */
  16453. u32 maxOut; /* Maximum instantaneous currentOut */
  16454. u32 maxCount; /* Maximum instantaneous currentCount */
  16455. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  16456. /*
  16457. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  16458. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  16459. ** and so forth.
  16460. */
  16461. int aiFreelist[LOGMAX+1];
  16462. /*
  16463. ** Space for tracking which blocks are checked out and the size
  16464. ** of each block. One byte per block.
  16465. */
  16466. u8 *aCtrl;
  16467. } mem5;
  16468. /*
  16469. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  16470. */
  16471. #define mem5 GLOBAL(struct Mem5Global, mem5)
  16472. /*
  16473. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  16474. ** structures, return a pointer to the idx-th such link.
  16475. */
  16476. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  16477. /*
  16478. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  16479. ** on. It should be found on mem5.aiFreelist[iLogsize].
  16480. */
  16481. static void memsys5Unlink(int i, int iLogsize){
  16482. int next, prev;
  16483. assert( i>=0 && i<mem5.nBlock );
  16484. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16485. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16486. next = MEM5LINK(i)->next;
  16487. prev = MEM5LINK(i)->prev;
  16488. if( prev<0 ){
  16489. mem5.aiFreelist[iLogsize] = next;
  16490. }else{
  16491. MEM5LINK(prev)->next = next;
  16492. }
  16493. if( next>=0 ){
  16494. MEM5LINK(next)->prev = prev;
  16495. }
  16496. }
  16497. /*
  16498. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  16499. ** free list.
  16500. */
  16501. static void memsys5Link(int i, int iLogsize){
  16502. int x;
  16503. assert( sqlite3_mutex_held(mem5.mutex) );
  16504. assert( i>=0 && i<mem5.nBlock );
  16505. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16506. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16507. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  16508. MEM5LINK(i)->prev = -1;
  16509. if( x>=0 ){
  16510. assert( x<mem5.nBlock );
  16511. MEM5LINK(x)->prev = i;
  16512. }
  16513. mem5.aiFreelist[iLogsize] = i;
  16514. }
  16515. /*
  16516. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  16517. ** will already be held (obtained by code in malloc.c) if
  16518. ** sqlite3GlobalConfig.bMemStat is true.
  16519. */
  16520. static void memsys5Enter(void){
  16521. sqlite3_mutex_enter(mem5.mutex);
  16522. }
  16523. static void memsys5Leave(void){
  16524. sqlite3_mutex_leave(mem5.mutex);
  16525. }
  16526. /*
  16527. ** Return the size of an outstanding allocation, in bytes. The
  16528. ** size returned omits the 8-byte header overhead. This only
  16529. ** works for chunks that are currently checked out.
  16530. */
  16531. static int memsys5Size(void *p){
  16532. int iSize = 0;
  16533. if( p ){
  16534. int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
  16535. assert( i>=0 && i<mem5.nBlock );
  16536. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  16537. }
  16538. return iSize;
  16539. }
  16540. /*
  16541. ** Find the first entry on the freelist iLogsize. Unlink that
  16542. ** entry and return its index.
  16543. */
  16544. static int memsys5UnlinkFirst(int iLogsize){
  16545. int i;
  16546. int iFirst;
  16547. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16548. i = iFirst = mem5.aiFreelist[iLogsize];
  16549. assert( iFirst>=0 );
  16550. while( i>0 ){
  16551. if( i<iFirst ) iFirst = i;
  16552. i = MEM5LINK(i)->next;
  16553. }
  16554. memsys5Unlink(iFirst, iLogsize);
  16555. return iFirst;
  16556. }
  16557. /*
  16558. ** Return a block of memory of at least nBytes in size.
  16559. ** Return NULL if unable. Return NULL if nBytes==0.
  16560. **
  16561. ** The caller guarantees that nByte is positive.
  16562. **
  16563. ** The caller has obtained a mutex prior to invoking this
  16564. ** routine so there is never any chance that two or more
  16565. ** threads can be in this routine at the same time.
  16566. */
  16567. static void *memsys5MallocUnsafe(int nByte){
  16568. int i; /* Index of a mem5.aPool[] slot */
  16569. int iBin; /* Index into mem5.aiFreelist[] */
  16570. int iFullSz; /* Size of allocation rounded up to power of 2 */
  16571. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  16572. /* nByte must be a positive */
  16573. assert( nByte>0 );
  16574. /* Keep track of the maximum allocation request. Even unfulfilled
  16575. ** requests are counted */
  16576. if( (u32)nByte>mem5.maxRequest ){
  16577. mem5.maxRequest = nByte;
  16578. }
  16579. /* Abort if the requested allocation size is larger than the largest
  16580. ** power of two that we can represent using 32-bit signed integers.
  16581. */
  16582. if( nByte > 0x40000000 ){
  16583. return 0;
  16584. }
  16585. /* Round nByte up to the next valid power of two */
  16586. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  16587. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  16588. ** block. If not, then split a block of the next larger power of
  16589. ** two in order to create a new free block of size iLogsize.
  16590. */
  16591. for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  16592. if( iBin>LOGMAX ){
  16593. testcase( sqlite3GlobalConfig.xLog!=0 );
  16594. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  16595. return 0;
  16596. }
  16597. i = memsys5UnlinkFirst(iBin);
  16598. while( iBin>iLogsize ){
  16599. int newSize;
  16600. iBin--;
  16601. newSize = 1 << iBin;
  16602. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  16603. memsys5Link(i+newSize, iBin);
  16604. }
  16605. mem5.aCtrl[i] = iLogsize;
  16606. /* Update allocator performance statistics. */
  16607. mem5.nAlloc++;
  16608. mem5.totalAlloc += iFullSz;
  16609. mem5.totalExcess += iFullSz - nByte;
  16610. mem5.currentCount++;
  16611. mem5.currentOut += iFullSz;
  16612. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  16613. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  16614. /* Return a pointer to the allocated memory. */
  16615. return (void*)&mem5.zPool[i*mem5.szAtom];
  16616. }
  16617. /*
  16618. ** Free an outstanding memory allocation.
  16619. */
  16620. static void memsys5FreeUnsafe(void *pOld){
  16621. u32 size, iLogsize;
  16622. int iBlock;
  16623. /* Set iBlock to the index of the block pointed to by pOld in
  16624. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  16625. */
  16626. iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
  16627. /* Check that the pointer pOld points to a valid, non-free block. */
  16628. assert( iBlock>=0 && iBlock<mem5.nBlock );
  16629. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  16630. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  16631. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  16632. size = 1<<iLogsize;
  16633. assert( iBlock+size-1<(u32)mem5.nBlock );
  16634. mem5.aCtrl[iBlock] |= CTRL_FREE;
  16635. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  16636. assert( mem5.currentCount>0 );
  16637. assert( mem5.currentOut>=(size*mem5.szAtom) );
  16638. mem5.currentCount--;
  16639. mem5.currentOut -= size*mem5.szAtom;
  16640. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  16641. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  16642. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16643. while( ALWAYS(iLogsize<LOGMAX) ){
  16644. int iBuddy;
  16645. if( (iBlock>>iLogsize) & 1 ){
  16646. iBuddy = iBlock - size;
  16647. }else{
  16648. iBuddy = iBlock + size;
  16649. }
  16650. assert( iBuddy>=0 );
  16651. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  16652. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  16653. memsys5Unlink(iBuddy, iLogsize);
  16654. iLogsize++;
  16655. if( iBuddy<iBlock ){
  16656. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  16657. mem5.aCtrl[iBlock] = 0;
  16658. iBlock = iBuddy;
  16659. }else{
  16660. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16661. mem5.aCtrl[iBuddy] = 0;
  16662. }
  16663. size *= 2;
  16664. }
  16665. memsys5Link(iBlock, iLogsize);
  16666. }
  16667. /*
  16668. ** Allocate nBytes of memory.
  16669. */
  16670. static void *memsys5Malloc(int nBytes){
  16671. sqlite3_int64 *p = 0;
  16672. if( nBytes>0 ){
  16673. memsys5Enter();
  16674. p = memsys5MallocUnsafe(nBytes);
  16675. memsys5Leave();
  16676. }
  16677. return (void*)p;
  16678. }
  16679. /*
  16680. ** Free memory.
  16681. **
  16682. ** The outer layer memory allocator prevents this routine from
  16683. ** being called with pPrior==0.
  16684. */
  16685. static void memsys5Free(void *pPrior){
  16686. assert( pPrior!=0 );
  16687. memsys5Enter();
  16688. memsys5FreeUnsafe(pPrior);
  16689. memsys5Leave();
  16690. }
  16691. /*
  16692. ** Change the size of an existing memory allocation.
  16693. **
  16694. ** The outer layer memory allocator prevents this routine from
  16695. ** being called with pPrior==0.
  16696. **
  16697. ** nBytes is always a value obtained from a prior call to
  16698. ** memsys5Round(). Hence nBytes is always a non-negative power
  16699. ** of two. If nBytes==0 that means that an oversize allocation
  16700. ** (an allocation larger than 0x40000000) was requested and this
  16701. ** routine should return 0 without freeing pPrior.
  16702. */
  16703. static void *memsys5Realloc(void *pPrior, int nBytes){
  16704. int nOld;
  16705. void *p;
  16706. assert( pPrior!=0 );
  16707. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  16708. assert( nBytes>=0 );
  16709. if( nBytes==0 ){
  16710. return 0;
  16711. }
  16712. nOld = memsys5Size(pPrior);
  16713. if( nBytes<=nOld ){
  16714. return pPrior;
  16715. }
  16716. memsys5Enter();
  16717. p = memsys5MallocUnsafe(nBytes);
  16718. if( p ){
  16719. memcpy(p, pPrior, nOld);
  16720. memsys5FreeUnsafe(pPrior);
  16721. }
  16722. memsys5Leave();
  16723. return p;
  16724. }
  16725. /*
  16726. ** Round up a request size to the next valid allocation size. If
  16727. ** the allocation is too large to be handled by this allocation system,
  16728. ** return 0.
  16729. **
  16730. ** All allocations must be a power of two and must be expressed by a
  16731. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  16732. ** or 1073741824 bytes.
  16733. */
  16734. static int memsys5Roundup(int n){
  16735. int iFullSz;
  16736. if( n > 0x40000000 ) return 0;
  16737. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  16738. return iFullSz;
  16739. }
  16740. /*
  16741. ** Return the ceiling of the logarithm base 2 of iValue.
  16742. **
  16743. ** Examples: memsys5Log(1) -> 0
  16744. ** memsys5Log(2) -> 1
  16745. ** memsys5Log(4) -> 2
  16746. ** memsys5Log(5) -> 3
  16747. ** memsys5Log(8) -> 3
  16748. ** memsys5Log(9) -> 4
  16749. */
  16750. static int memsys5Log(int iValue){
  16751. int iLog;
  16752. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  16753. return iLog;
  16754. }
  16755. /*
  16756. ** Initialize the memory allocator.
  16757. **
  16758. ** This routine is not threadsafe. The caller must be holding a mutex
  16759. ** to prevent multiple threads from entering at the same time.
  16760. */
  16761. static int memsys5Init(void *NotUsed){
  16762. int ii; /* Loop counter */
  16763. int nByte; /* Number of bytes of memory available to this allocator */
  16764. u8 *zByte; /* Memory usable by this allocator */
  16765. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  16766. int iOffset; /* An offset into mem5.aCtrl[] */
  16767. UNUSED_PARAMETER(NotUsed);
  16768. /* For the purposes of this routine, disable the mutex */
  16769. mem5.mutex = 0;
  16770. /* The size of a Mem5Link object must be a power of two. Verify that
  16771. ** this is case.
  16772. */
  16773. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  16774. nByte = sqlite3GlobalConfig.nHeap;
  16775. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  16776. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  16777. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  16778. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  16779. mem5.szAtom = (1<<nMinLog);
  16780. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  16781. mem5.szAtom = mem5.szAtom << 1;
  16782. }
  16783. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  16784. mem5.zPool = zByte;
  16785. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  16786. for(ii=0; ii<=LOGMAX; ii++){
  16787. mem5.aiFreelist[ii] = -1;
  16788. }
  16789. iOffset = 0;
  16790. for(ii=LOGMAX; ii>=0; ii--){
  16791. int nAlloc = (1<<ii);
  16792. if( (iOffset+nAlloc)<=mem5.nBlock ){
  16793. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  16794. memsys5Link(iOffset, ii);
  16795. iOffset += nAlloc;
  16796. }
  16797. assert((iOffset+nAlloc)>mem5.nBlock);
  16798. }
  16799. /* If a mutex is required for normal operation, allocate one */
  16800. if( sqlite3GlobalConfig.bMemstat==0 ){
  16801. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16802. }
  16803. return SQLITE_OK;
  16804. }
  16805. /*
  16806. ** Deinitialize this module.
  16807. */
  16808. static void memsys5Shutdown(void *NotUsed){
  16809. UNUSED_PARAMETER(NotUsed);
  16810. mem5.mutex = 0;
  16811. return;
  16812. }
  16813. #ifdef SQLITE_TEST
  16814. /*
  16815. ** Open the file indicated and write a log of all unfreed memory
  16816. ** allocations into that log.
  16817. */
  16818. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  16819. FILE *out;
  16820. int i, j, n;
  16821. int nMinLog;
  16822. if( zFilename==0 || zFilename[0]==0 ){
  16823. out = stdout;
  16824. }else{
  16825. out = fopen(zFilename, "w");
  16826. if( out==0 ){
  16827. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16828. zFilename);
  16829. return;
  16830. }
  16831. }
  16832. memsys5Enter();
  16833. nMinLog = memsys5Log(mem5.szAtom);
  16834. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  16835. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  16836. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  16837. }
  16838. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  16839. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  16840. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  16841. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  16842. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  16843. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  16844. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  16845. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  16846. memsys5Leave();
  16847. if( out==stdout ){
  16848. fflush(stdout);
  16849. }else{
  16850. fclose(out);
  16851. }
  16852. }
  16853. #endif
  16854. /*
  16855. ** This routine is the only routine in this file with external
  16856. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  16857. ** struct populated with the memsys5 methods.
  16858. */
  16859. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  16860. static const sqlite3_mem_methods memsys5Methods = {
  16861. memsys5Malloc,
  16862. memsys5Free,
  16863. memsys5Realloc,
  16864. memsys5Size,
  16865. memsys5Roundup,
  16866. memsys5Init,
  16867. memsys5Shutdown,
  16868. 0
  16869. };
  16870. return &memsys5Methods;
  16871. }
  16872. #endif /* SQLITE_ENABLE_MEMSYS5 */
  16873. /************** End of mem5.c ************************************************/
  16874. /************** Begin file mutex.c *******************************************/
  16875. /*
  16876. ** 2007 August 14
  16877. **
  16878. ** The author disclaims copyright to this source code. In place of
  16879. ** a legal notice, here is a blessing:
  16880. **
  16881. ** May you do good and not evil.
  16882. ** May you find forgiveness for yourself and forgive others.
  16883. ** May you share freely, never taking more than you give.
  16884. **
  16885. *************************************************************************
  16886. ** This file contains the C functions that implement mutexes.
  16887. **
  16888. ** This file contains code that is common across all mutex implementations.
  16889. */
  16890. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  16891. /*
  16892. ** For debugging purposes, record when the mutex subsystem is initialized
  16893. ** and uninitialized so that we can assert() if there is an attempt to
  16894. ** allocate a mutex while the system is uninitialized.
  16895. */
  16896. static SQLITE_WSD int mutexIsInit = 0;
  16897. #endif /* SQLITE_DEBUG */
  16898. #ifndef SQLITE_MUTEX_OMIT
  16899. /*
  16900. ** Initialize the mutex system.
  16901. */
  16902. SQLITE_PRIVATE int sqlite3MutexInit(void){
  16903. int rc = SQLITE_OK;
  16904. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  16905. /* If the xMutexAlloc method has not been set, then the user did not
  16906. ** install a mutex implementation via sqlite3_config() prior to
  16907. ** sqlite3_initialize() being called. This block copies pointers to
  16908. ** the default implementation into the sqlite3GlobalConfig structure.
  16909. */
  16910. sqlite3_mutex_methods const *pFrom;
  16911. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  16912. if( sqlite3GlobalConfig.bCoreMutex ){
  16913. pFrom = sqlite3DefaultMutex();
  16914. }else{
  16915. pFrom = sqlite3NoopMutex();
  16916. }
  16917. memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
  16918. memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
  16919. sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
  16920. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  16921. }
  16922. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  16923. #ifdef SQLITE_DEBUG
  16924. GLOBAL(int, mutexIsInit) = 1;
  16925. #endif
  16926. return rc;
  16927. }
  16928. /*
  16929. ** Shutdown the mutex system. This call frees resources allocated by
  16930. ** sqlite3MutexInit().
  16931. */
  16932. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  16933. int rc = SQLITE_OK;
  16934. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  16935. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  16936. }
  16937. #ifdef SQLITE_DEBUG
  16938. GLOBAL(int, mutexIsInit) = 0;
  16939. #endif
  16940. return rc;
  16941. }
  16942. /*
  16943. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  16944. */
  16945. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  16946. #ifndef SQLITE_OMIT_AUTOINIT
  16947. if( sqlite3_initialize() ) return 0;
  16948. #endif
  16949. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16950. }
  16951. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  16952. if( !sqlite3GlobalConfig.bCoreMutex ){
  16953. return 0;
  16954. }
  16955. assert( GLOBAL(int, mutexIsInit) );
  16956. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16957. }
  16958. /*
  16959. ** Free a dynamic mutex.
  16960. */
  16961. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  16962. if( p ){
  16963. sqlite3GlobalConfig.mutex.xMutexFree(p);
  16964. }
  16965. }
  16966. /*
  16967. ** Obtain the mutex p. If some other thread already has the mutex, block
  16968. ** until it can be obtained.
  16969. */
  16970. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  16971. if( p ){
  16972. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  16973. }
  16974. }
  16975. /*
  16976. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  16977. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  16978. */
  16979. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  16980. int rc = SQLITE_OK;
  16981. if( p ){
  16982. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  16983. }
  16984. return rc;
  16985. }
  16986. /*
  16987. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  16988. ** entered by the same thread. The behavior is undefined if the mutex
  16989. ** is not currently entered. If a NULL pointer is passed as an argument
  16990. ** this function is a no-op.
  16991. */
  16992. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  16993. if( p ){
  16994. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  16995. }
  16996. }
  16997. #ifndef NDEBUG
  16998. /*
  16999. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17000. ** intended for use inside assert() statements.
  17001. */
  17002. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  17003. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  17004. }
  17005. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  17006. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  17007. }
  17008. #endif
  17009. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17010. /************** End of mutex.c ***********************************************/
  17011. /************** Begin file mutex_noop.c **************************************/
  17012. /*
  17013. ** 2008 October 07
  17014. **
  17015. ** The author disclaims copyright to this source code. In place of
  17016. ** a legal notice, here is a blessing:
  17017. **
  17018. ** May you do good and not evil.
  17019. ** May you find forgiveness for yourself and forgive others.
  17020. ** May you share freely, never taking more than you give.
  17021. **
  17022. *************************************************************************
  17023. ** This file contains the C functions that implement mutexes.
  17024. **
  17025. ** This implementation in this file does not provide any mutual
  17026. ** exclusion and is thus suitable for use only in applications
  17027. ** that use SQLite in a single thread. The routines defined
  17028. ** here are place-holders. Applications can substitute working
  17029. ** mutex routines at start-time using the
  17030. **
  17031. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  17032. **
  17033. ** interface.
  17034. **
  17035. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  17036. ** that does error checking on mutexes to make sure they are being
  17037. ** called correctly.
  17038. */
  17039. #ifndef SQLITE_MUTEX_OMIT
  17040. #ifndef SQLITE_DEBUG
  17041. /*
  17042. ** Stub routines for all mutex methods.
  17043. **
  17044. ** This routines provide no mutual exclusion or error checking.
  17045. */
  17046. static int noopMutexInit(void){ return SQLITE_OK; }
  17047. static int noopMutexEnd(void){ return SQLITE_OK; }
  17048. static sqlite3_mutex *noopMutexAlloc(int id){
  17049. UNUSED_PARAMETER(id);
  17050. return (sqlite3_mutex*)8;
  17051. }
  17052. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17053. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17054. static int noopMutexTry(sqlite3_mutex *p){
  17055. UNUSED_PARAMETER(p);
  17056. return SQLITE_OK;
  17057. }
  17058. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17059. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17060. static const sqlite3_mutex_methods sMutex = {
  17061. noopMutexInit,
  17062. noopMutexEnd,
  17063. noopMutexAlloc,
  17064. noopMutexFree,
  17065. noopMutexEnter,
  17066. noopMutexTry,
  17067. noopMutexLeave,
  17068. 0,
  17069. 0,
  17070. };
  17071. return &sMutex;
  17072. }
  17073. #endif /* !SQLITE_DEBUG */
  17074. #ifdef SQLITE_DEBUG
  17075. /*
  17076. ** In this implementation, error checking is provided for testing
  17077. ** and debugging purposes. The mutexes still do not provide any
  17078. ** mutual exclusion.
  17079. */
  17080. /*
  17081. ** The mutex object
  17082. */
  17083. typedef struct sqlite3_debug_mutex {
  17084. int id; /* The mutex type */
  17085. int cnt; /* Number of entries without a matching leave */
  17086. } sqlite3_debug_mutex;
  17087. /*
  17088. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17089. ** intended for use inside assert() statements.
  17090. */
  17091. static int debugMutexHeld(sqlite3_mutex *pX){
  17092. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17093. return p==0 || p->cnt>0;
  17094. }
  17095. static int debugMutexNotheld(sqlite3_mutex *pX){
  17096. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17097. return p==0 || p->cnt==0;
  17098. }
  17099. /*
  17100. ** Initialize and deinitialize the mutex subsystem.
  17101. */
  17102. static int debugMutexInit(void){ return SQLITE_OK; }
  17103. static int debugMutexEnd(void){ return SQLITE_OK; }
  17104. /*
  17105. ** The sqlite3_mutex_alloc() routine allocates a new
  17106. ** mutex and returns a pointer to it. If it returns NULL
  17107. ** that means that a mutex could not be allocated.
  17108. */
  17109. static sqlite3_mutex *debugMutexAlloc(int id){
  17110. static sqlite3_debug_mutex aStatic[6];
  17111. sqlite3_debug_mutex *pNew = 0;
  17112. switch( id ){
  17113. case SQLITE_MUTEX_FAST:
  17114. case SQLITE_MUTEX_RECURSIVE: {
  17115. pNew = sqlite3Malloc(sizeof(*pNew));
  17116. if( pNew ){
  17117. pNew->id = id;
  17118. pNew->cnt = 0;
  17119. }
  17120. break;
  17121. }
  17122. default: {
  17123. assert( id-2 >= 0 );
  17124. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  17125. pNew = &aStatic[id-2];
  17126. pNew->id = id;
  17127. break;
  17128. }
  17129. }
  17130. return (sqlite3_mutex*)pNew;
  17131. }
  17132. /*
  17133. ** This routine deallocates a previously allocated mutex.
  17134. */
  17135. static void debugMutexFree(sqlite3_mutex *pX){
  17136. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17137. assert( p->cnt==0 );
  17138. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17139. sqlite3_free(p);
  17140. }
  17141. /*
  17142. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17143. ** to enter a mutex. If another thread is already within the mutex,
  17144. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17145. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17146. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17147. ** be entered multiple times by the same thread. In such cases the,
  17148. ** mutex must be exited an equal number of times before another thread
  17149. ** can enter. If the same thread tries to enter any other kind of mutex
  17150. ** more than once, the behavior is undefined.
  17151. */
  17152. static void debugMutexEnter(sqlite3_mutex *pX){
  17153. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17154. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17155. p->cnt++;
  17156. }
  17157. static int debugMutexTry(sqlite3_mutex *pX){
  17158. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17159. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17160. p->cnt++;
  17161. return SQLITE_OK;
  17162. }
  17163. /*
  17164. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17165. ** previously entered by the same thread. The behavior
  17166. ** is undefined if the mutex is not currently entered or
  17167. ** is not currently allocated. SQLite will never do either.
  17168. */
  17169. static void debugMutexLeave(sqlite3_mutex *pX){
  17170. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17171. assert( debugMutexHeld(pX) );
  17172. p->cnt--;
  17173. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17174. }
  17175. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17176. static const sqlite3_mutex_methods sMutex = {
  17177. debugMutexInit,
  17178. debugMutexEnd,
  17179. debugMutexAlloc,
  17180. debugMutexFree,
  17181. debugMutexEnter,
  17182. debugMutexTry,
  17183. debugMutexLeave,
  17184. debugMutexHeld,
  17185. debugMutexNotheld
  17186. };
  17187. return &sMutex;
  17188. }
  17189. #endif /* SQLITE_DEBUG */
  17190. /*
  17191. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  17192. ** is used regardless of the run-time threadsafety setting.
  17193. */
  17194. #ifdef SQLITE_MUTEX_NOOP
  17195. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17196. return sqlite3NoopMutex();
  17197. }
  17198. #endif /* defined(SQLITE_MUTEX_NOOP) */
  17199. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17200. /************** End of mutex_noop.c ******************************************/
  17201. /************** Begin file mutex_unix.c **************************************/
  17202. /*
  17203. ** 2007 August 28
  17204. **
  17205. ** The author disclaims copyright to this source code. In place of
  17206. ** a legal notice, here is a blessing:
  17207. **
  17208. ** May you do good and not evil.
  17209. ** May you find forgiveness for yourself and forgive others.
  17210. ** May you share freely, never taking more than you give.
  17211. **
  17212. *************************************************************************
  17213. ** This file contains the C functions that implement mutexes for pthreads
  17214. */
  17215. /*
  17216. ** The code in this file is only used if we are compiling threadsafe
  17217. ** under unix with pthreads.
  17218. **
  17219. ** Note that this implementation requires a version of pthreads that
  17220. ** supports recursive mutexes.
  17221. */
  17222. #ifdef SQLITE_MUTEX_PTHREADS
  17223. #include <pthread.h>
  17224. /*
  17225. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  17226. ** are necessary under two condidtions: (1) Debug builds and (2) using
  17227. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  17228. */
  17229. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  17230. # define SQLITE_MUTEX_NREF 1
  17231. #else
  17232. # define SQLITE_MUTEX_NREF 0
  17233. #endif
  17234. /*
  17235. ** Each recursive mutex is an instance of the following structure.
  17236. */
  17237. struct sqlite3_mutex {
  17238. pthread_mutex_t mutex; /* Mutex controlling the lock */
  17239. #if SQLITE_MUTEX_NREF
  17240. int id; /* Mutex type */
  17241. volatile int nRef; /* Number of entrances */
  17242. volatile pthread_t owner; /* Thread that is within this mutex */
  17243. int trace; /* True to trace changes */
  17244. #endif
  17245. };
  17246. #if SQLITE_MUTEX_NREF
  17247. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  17248. #else
  17249. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  17250. #endif
  17251. /*
  17252. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17253. ** intended for use only inside assert() statements. On some platforms,
  17254. ** there might be race conditions that can cause these routines to
  17255. ** deliver incorrect results. In particular, if pthread_equal() is
  17256. ** not an atomic operation, then these routines might delivery
  17257. ** incorrect results. On most platforms, pthread_equal() is a
  17258. ** comparison of two integers and is therefore atomic. But we are
  17259. ** told that HPUX is not such a platform. If so, then these routines
  17260. ** will not always work correctly on HPUX.
  17261. **
  17262. ** On those platforms where pthread_equal() is not atomic, SQLite
  17263. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  17264. ** make sure no assert() statements are evaluated and hence these
  17265. ** routines are never called.
  17266. */
  17267. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  17268. static int pthreadMutexHeld(sqlite3_mutex *p){
  17269. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  17270. }
  17271. static int pthreadMutexNotheld(sqlite3_mutex *p){
  17272. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  17273. }
  17274. #endif
  17275. /*
  17276. ** Initialize and deinitialize the mutex subsystem.
  17277. */
  17278. static int pthreadMutexInit(void){ return SQLITE_OK; }
  17279. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  17280. /*
  17281. ** The sqlite3_mutex_alloc() routine allocates a new
  17282. ** mutex and returns a pointer to it. If it returns NULL
  17283. ** that means that a mutex could not be allocated. SQLite
  17284. ** will unwind its stack and return an error. The argument
  17285. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17286. **
  17287. ** <ul>
  17288. ** <li> SQLITE_MUTEX_FAST
  17289. ** <li> SQLITE_MUTEX_RECURSIVE
  17290. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17291. ** <li> SQLITE_MUTEX_STATIC_MEM
  17292. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17293. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17294. ** <li> SQLITE_MUTEX_STATIC_LRU
  17295. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17296. ** </ul>
  17297. **
  17298. ** The first two constants cause sqlite3_mutex_alloc() to create
  17299. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17300. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17301. ** The mutex implementation does not need to make a distinction
  17302. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17303. ** not want to. But SQLite will only request a recursive mutex in
  17304. ** cases where it really needs one. If a faster non-recursive mutex
  17305. ** implementation is available on the host platform, the mutex subsystem
  17306. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17307. **
  17308. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17309. ** a pointer to a static preexisting mutex. Six static mutexes are
  17310. ** used by the current version of SQLite. Future versions of SQLite
  17311. ** may add additional static mutexes. Static mutexes are for internal
  17312. ** use by SQLite only. Applications that use SQLite mutexes should
  17313. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17314. ** SQLITE_MUTEX_RECURSIVE.
  17315. **
  17316. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17317. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17318. ** returns a different mutex on every call. But for the static
  17319. ** mutex types, the same mutex is returned on every call that has
  17320. ** the same type number.
  17321. */
  17322. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  17323. static sqlite3_mutex staticMutexes[] = {
  17324. SQLITE3_MUTEX_INITIALIZER,
  17325. SQLITE3_MUTEX_INITIALIZER,
  17326. SQLITE3_MUTEX_INITIALIZER,
  17327. SQLITE3_MUTEX_INITIALIZER,
  17328. SQLITE3_MUTEX_INITIALIZER,
  17329. SQLITE3_MUTEX_INITIALIZER
  17330. };
  17331. sqlite3_mutex *p;
  17332. switch( iType ){
  17333. case SQLITE_MUTEX_RECURSIVE: {
  17334. p = sqlite3MallocZero( sizeof(*p) );
  17335. if( p ){
  17336. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17337. /* If recursive mutexes are not available, we will have to
  17338. ** build our own. See below. */
  17339. pthread_mutex_init(&p->mutex, 0);
  17340. #else
  17341. /* Use a recursive mutex if it is available */
  17342. pthread_mutexattr_t recursiveAttr;
  17343. pthread_mutexattr_init(&recursiveAttr);
  17344. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  17345. pthread_mutex_init(&p->mutex, &recursiveAttr);
  17346. pthread_mutexattr_destroy(&recursiveAttr);
  17347. #endif
  17348. #if SQLITE_MUTEX_NREF
  17349. p->id = iType;
  17350. #endif
  17351. }
  17352. break;
  17353. }
  17354. case SQLITE_MUTEX_FAST: {
  17355. p = sqlite3MallocZero( sizeof(*p) );
  17356. if( p ){
  17357. #if SQLITE_MUTEX_NREF
  17358. p->id = iType;
  17359. #endif
  17360. pthread_mutex_init(&p->mutex, 0);
  17361. }
  17362. break;
  17363. }
  17364. default: {
  17365. assert( iType-2 >= 0 );
  17366. assert( iType-2 < ArraySize(staticMutexes) );
  17367. p = &staticMutexes[iType-2];
  17368. #if SQLITE_MUTEX_NREF
  17369. p->id = iType;
  17370. #endif
  17371. break;
  17372. }
  17373. }
  17374. return p;
  17375. }
  17376. /*
  17377. ** This routine deallocates a previously
  17378. ** allocated mutex. SQLite is careful to deallocate every
  17379. ** mutex that it allocates.
  17380. */
  17381. static void pthreadMutexFree(sqlite3_mutex *p){
  17382. assert( p->nRef==0 );
  17383. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17384. pthread_mutex_destroy(&p->mutex);
  17385. sqlite3_free(p);
  17386. }
  17387. /*
  17388. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17389. ** to enter a mutex. If another thread is already within the mutex,
  17390. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17391. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17392. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17393. ** be entered multiple times by the same thread. In such cases the,
  17394. ** mutex must be exited an equal number of times before another thread
  17395. ** can enter. If the same thread tries to enter any other kind of mutex
  17396. ** more than once, the behavior is undefined.
  17397. */
  17398. static void pthreadMutexEnter(sqlite3_mutex *p){
  17399. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17400. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17401. /* If recursive mutexes are not available, then we have to grow
  17402. ** our own. This implementation assumes that pthread_equal()
  17403. ** is atomic - that it cannot be deceived into thinking self
  17404. ** and p->owner are equal if p->owner changes between two values
  17405. ** that are not equal to self while the comparison is taking place.
  17406. ** This implementation also assumes a coherent cache - that
  17407. ** separate processes cannot read different values from the same
  17408. ** address at the same time. If either of these two conditions
  17409. ** are not met, then the mutexes will fail and problems will result.
  17410. */
  17411. {
  17412. pthread_t self = pthread_self();
  17413. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17414. p->nRef++;
  17415. }else{
  17416. pthread_mutex_lock(&p->mutex);
  17417. assert( p->nRef==0 );
  17418. p->owner = self;
  17419. p->nRef = 1;
  17420. }
  17421. }
  17422. #else
  17423. /* Use the built-in recursive mutexes if they are available.
  17424. */
  17425. pthread_mutex_lock(&p->mutex);
  17426. #if SQLITE_MUTEX_NREF
  17427. assert( p->nRef>0 || p->owner==0 );
  17428. p->owner = pthread_self();
  17429. p->nRef++;
  17430. #endif
  17431. #endif
  17432. #ifdef SQLITE_DEBUG
  17433. if( p->trace ){
  17434. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17435. }
  17436. #endif
  17437. }
  17438. static int pthreadMutexTry(sqlite3_mutex *p){
  17439. int rc;
  17440. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17441. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17442. /* If recursive mutexes are not available, then we have to grow
  17443. ** our own. This implementation assumes that pthread_equal()
  17444. ** is atomic - that it cannot be deceived into thinking self
  17445. ** and p->owner are equal if p->owner changes between two values
  17446. ** that are not equal to self while the comparison is taking place.
  17447. ** This implementation also assumes a coherent cache - that
  17448. ** separate processes cannot read different values from the same
  17449. ** address at the same time. If either of these two conditions
  17450. ** are not met, then the mutexes will fail and problems will result.
  17451. */
  17452. {
  17453. pthread_t self = pthread_self();
  17454. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17455. p->nRef++;
  17456. rc = SQLITE_OK;
  17457. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  17458. assert( p->nRef==0 );
  17459. p->owner = self;
  17460. p->nRef = 1;
  17461. rc = SQLITE_OK;
  17462. }else{
  17463. rc = SQLITE_BUSY;
  17464. }
  17465. }
  17466. #else
  17467. /* Use the built-in recursive mutexes if they are available.
  17468. */
  17469. if( pthread_mutex_trylock(&p->mutex)==0 ){
  17470. #if SQLITE_MUTEX_NREF
  17471. p->owner = pthread_self();
  17472. p->nRef++;
  17473. #endif
  17474. rc = SQLITE_OK;
  17475. }else{
  17476. rc = SQLITE_BUSY;
  17477. }
  17478. #endif
  17479. #ifdef SQLITE_DEBUG
  17480. if( rc==SQLITE_OK && p->trace ){
  17481. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17482. }
  17483. #endif
  17484. return rc;
  17485. }
  17486. /*
  17487. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17488. ** previously entered by the same thread. The behavior
  17489. ** is undefined if the mutex is not currently entered or
  17490. ** is not currently allocated. SQLite will never do either.
  17491. */
  17492. static void pthreadMutexLeave(sqlite3_mutex *p){
  17493. assert( pthreadMutexHeld(p) );
  17494. #if SQLITE_MUTEX_NREF
  17495. p->nRef--;
  17496. if( p->nRef==0 ) p->owner = 0;
  17497. #endif
  17498. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17499. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17500. if( p->nRef==0 ){
  17501. pthread_mutex_unlock(&p->mutex);
  17502. }
  17503. #else
  17504. pthread_mutex_unlock(&p->mutex);
  17505. #endif
  17506. #ifdef SQLITE_DEBUG
  17507. if( p->trace ){
  17508. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17509. }
  17510. #endif
  17511. }
  17512. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17513. static const sqlite3_mutex_methods sMutex = {
  17514. pthreadMutexInit,
  17515. pthreadMutexEnd,
  17516. pthreadMutexAlloc,
  17517. pthreadMutexFree,
  17518. pthreadMutexEnter,
  17519. pthreadMutexTry,
  17520. pthreadMutexLeave,
  17521. #ifdef SQLITE_DEBUG
  17522. pthreadMutexHeld,
  17523. pthreadMutexNotheld
  17524. #else
  17525. 0,
  17526. 0
  17527. #endif
  17528. };
  17529. return &sMutex;
  17530. }
  17531. #endif /* SQLITE_MUTEX_PTHREADS */
  17532. /************** End of mutex_unix.c ******************************************/
  17533. /************** Begin file mutex_w32.c ***************************************/
  17534. /*
  17535. ** 2007 August 14
  17536. **
  17537. ** The author disclaims copyright to this source code. In place of
  17538. ** a legal notice, here is a blessing:
  17539. **
  17540. ** May you do good and not evil.
  17541. ** May you find forgiveness for yourself and forgive others.
  17542. ** May you share freely, never taking more than you give.
  17543. **
  17544. *************************************************************************
  17545. ** This file contains the C functions that implement mutexes for win32
  17546. */
  17547. /*
  17548. ** The code in this file is only used if we are compiling multithreaded
  17549. ** on a win32 system.
  17550. */
  17551. #ifdef SQLITE_MUTEX_W32
  17552. /*
  17553. ** Each recursive mutex is an instance of the following structure.
  17554. */
  17555. struct sqlite3_mutex {
  17556. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  17557. int id; /* Mutex type */
  17558. #ifdef SQLITE_DEBUG
  17559. volatile int nRef; /* Number of enterances */
  17560. volatile DWORD owner; /* Thread holding this mutex */
  17561. int trace; /* True to trace changes */
  17562. #endif
  17563. };
  17564. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  17565. #ifdef SQLITE_DEBUG
  17566. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
  17567. #else
  17568. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  17569. #endif
  17570. /*
  17571. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  17572. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  17573. **
  17574. ** Here is an interesting observation: Win95, Win98, and WinME lack
  17575. ** the LockFileEx() API. But we can still statically link against that
  17576. ** API as long as we don't call it win running Win95/98/ME. A call to
  17577. ** this routine is used to determine if the host is Win95/98/ME or
  17578. ** WinNT/2K/XP so that we will know whether or not we can safely call
  17579. ** the LockFileEx() API.
  17580. **
  17581. ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
  17582. ** which is only available if your application was compiled with
  17583. ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
  17584. ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
  17585. ** this out as well.
  17586. */
  17587. #if 0
  17588. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  17589. # define mutexIsNT() (1)
  17590. #else
  17591. static int mutexIsNT(void){
  17592. static int osType = 0;
  17593. if( osType==0 ){
  17594. OSVERSIONINFO sInfo;
  17595. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  17596. GetVersionEx(&sInfo);
  17597. osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  17598. }
  17599. return osType==2;
  17600. }
  17601. #endif /* SQLITE_OS_WINCE || SQLITE_OS_WINRT */
  17602. #endif
  17603. #ifdef SQLITE_DEBUG
  17604. /*
  17605. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17606. ** intended for use only inside assert() statements.
  17607. */
  17608. static int winMutexHeld(sqlite3_mutex *p){
  17609. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  17610. }
  17611. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  17612. return p->nRef==0 || p->owner!=tid;
  17613. }
  17614. static int winMutexNotheld(sqlite3_mutex *p){
  17615. DWORD tid = GetCurrentThreadId();
  17616. return winMutexNotheld2(p, tid);
  17617. }
  17618. #endif
  17619. /*
  17620. ** Initialize and deinitialize the mutex subsystem.
  17621. */
  17622. static sqlite3_mutex winMutex_staticMutexes[6] = {
  17623. SQLITE3_MUTEX_INITIALIZER,
  17624. SQLITE3_MUTEX_INITIALIZER,
  17625. SQLITE3_MUTEX_INITIALIZER,
  17626. SQLITE3_MUTEX_INITIALIZER,
  17627. SQLITE3_MUTEX_INITIALIZER,
  17628. SQLITE3_MUTEX_INITIALIZER
  17629. };
  17630. static int winMutex_isInit = 0;
  17631. /* As winMutexInit() and winMutexEnd() are called as part
  17632. ** of the sqlite3_initialize and sqlite3_shutdown()
  17633. ** processing, the "interlocked" magic is probably not
  17634. ** strictly necessary.
  17635. */
  17636. static LONG winMutex_lock = 0;
  17637. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  17638. static int winMutexInit(void){
  17639. /* The first to increment to 1 does actual initialization */
  17640. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  17641. int i;
  17642. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17643. #if SQLITE_OS_WINRT
  17644. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  17645. #else
  17646. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  17647. #endif
  17648. }
  17649. winMutex_isInit = 1;
  17650. }else{
  17651. /* Someone else is in the process of initing the static mutexes */
  17652. while( !winMutex_isInit ){
  17653. sqlite3_win32_sleep(1);
  17654. }
  17655. }
  17656. return SQLITE_OK;
  17657. }
  17658. static int winMutexEnd(void){
  17659. /* The first to decrement to 0 does actual shutdown
  17660. ** (which should be the last to shutdown.) */
  17661. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  17662. if( winMutex_isInit==1 ){
  17663. int i;
  17664. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17665. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  17666. }
  17667. winMutex_isInit = 0;
  17668. }
  17669. }
  17670. return SQLITE_OK;
  17671. }
  17672. /*
  17673. ** The sqlite3_mutex_alloc() routine allocates a new
  17674. ** mutex and returns a pointer to it. If it returns NULL
  17675. ** that means that a mutex could not be allocated. SQLite
  17676. ** will unwind its stack and return an error. The argument
  17677. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17678. **
  17679. ** <ul>
  17680. ** <li> SQLITE_MUTEX_FAST
  17681. ** <li> SQLITE_MUTEX_RECURSIVE
  17682. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17683. ** <li> SQLITE_MUTEX_STATIC_MEM
  17684. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17685. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17686. ** <li> SQLITE_MUTEX_STATIC_LRU
  17687. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17688. ** </ul>
  17689. **
  17690. ** The first two constants cause sqlite3_mutex_alloc() to create
  17691. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17692. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17693. ** The mutex implementation does not need to make a distinction
  17694. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17695. ** not want to. But SQLite will only request a recursive mutex in
  17696. ** cases where it really needs one. If a faster non-recursive mutex
  17697. ** implementation is available on the host platform, the mutex subsystem
  17698. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17699. **
  17700. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17701. ** a pointer to a static preexisting mutex. Six static mutexes are
  17702. ** used by the current version of SQLite. Future versions of SQLite
  17703. ** may add additional static mutexes. Static mutexes are for internal
  17704. ** use by SQLite only. Applications that use SQLite mutexes should
  17705. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17706. ** SQLITE_MUTEX_RECURSIVE.
  17707. **
  17708. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17709. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17710. ** returns a different mutex on every call. But for the static
  17711. ** mutex types, the same mutex is returned on every call that has
  17712. ** the same type number.
  17713. */
  17714. static sqlite3_mutex *winMutexAlloc(int iType){
  17715. sqlite3_mutex *p;
  17716. switch( iType ){
  17717. case SQLITE_MUTEX_FAST:
  17718. case SQLITE_MUTEX_RECURSIVE: {
  17719. p = sqlite3MallocZero( sizeof(*p) );
  17720. if( p ){
  17721. #ifdef SQLITE_DEBUG
  17722. p->id = iType;
  17723. #endif
  17724. #if SQLITE_OS_WINRT
  17725. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  17726. #else
  17727. InitializeCriticalSection(&p->mutex);
  17728. #endif
  17729. }
  17730. break;
  17731. }
  17732. default: {
  17733. assert( winMutex_isInit==1 );
  17734. assert( iType-2 >= 0 );
  17735. assert( iType-2 < ArraySize(winMutex_staticMutexes) );
  17736. p = &winMutex_staticMutexes[iType-2];
  17737. #ifdef SQLITE_DEBUG
  17738. p->id = iType;
  17739. #endif
  17740. break;
  17741. }
  17742. }
  17743. return p;
  17744. }
  17745. /*
  17746. ** This routine deallocates a previously
  17747. ** allocated mutex. SQLite is careful to deallocate every
  17748. ** mutex that it allocates.
  17749. */
  17750. static void winMutexFree(sqlite3_mutex *p){
  17751. assert( p );
  17752. assert( p->nRef==0 && p->owner==0 );
  17753. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17754. DeleteCriticalSection(&p->mutex);
  17755. sqlite3_free(p);
  17756. }
  17757. /*
  17758. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17759. ** to enter a mutex. If another thread is already within the mutex,
  17760. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17761. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17762. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17763. ** be entered multiple times by the same thread. In such cases the,
  17764. ** mutex must be exited an equal number of times before another thread
  17765. ** can enter. If the same thread tries to enter any other kind of mutex
  17766. ** more than once, the behavior is undefined.
  17767. */
  17768. static void winMutexEnter(sqlite3_mutex *p){
  17769. #ifdef SQLITE_DEBUG
  17770. DWORD tid = GetCurrentThreadId();
  17771. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17772. #endif
  17773. EnterCriticalSection(&p->mutex);
  17774. #ifdef SQLITE_DEBUG
  17775. assert( p->nRef>0 || p->owner==0 );
  17776. p->owner = tid;
  17777. p->nRef++;
  17778. if( p->trace ){
  17779. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17780. }
  17781. #endif
  17782. }
  17783. static int winMutexTry(sqlite3_mutex *p){
  17784. #ifndef NDEBUG
  17785. DWORD tid = GetCurrentThreadId();
  17786. #endif
  17787. int rc = SQLITE_BUSY;
  17788. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17789. /*
  17790. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  17791. ** is used it is merely an optimization. So it is OK for it to always
  17792. ** fail.
  17793. **
  17794. ** The TryEnterCriticalSection() interface is only available on WinNT.
  17795. ** And some windows compilers complain if you try to use it without
  17796. ** first doing some #defines that prevent SQLite from building on Win98.
  17797. ** For that reason, we will omit this optimization for now. See
  17798. ** ticket #2685.
  17799. */
  17800. #if 0
  17801. if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
  17802. p->owner = tid;
  17803. p->nRef++;
  17804. rc = SQLITE_OK;
  17805. }
  17806. #else
  17807. UNUSED_PARAMETER(p);
  17808. #endif
  17809. #ifdef SQLITE_DEBUG
  17810. if( rc==SQLITE_OK && p->trace ){
  17811. printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17812. }
  17813. #endif
  17814. return rc;
  17815. }
  17816. /*
  17817. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17818. ** previously entered by the same thread. The behavior
  17819. ** is undefined if the mutex is not currently entered or
  17820. ** is not currently allocated. SQLite will never do either.
  17821. */
  17822. static void winMutexLeave(sqlite3_mutex *p){
  17823. #ifndef NDEBUG
  17824. DWORD tid = GetCurrentThreadId();
  17825. assert( p->nRef>0 );
  17826. assert( p->owner==tid );
  17827. p->nRef--;
  17828. if( p->nRef==0 ) p->owner = 0;
  17829. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17830. #endif
  17831. LeaveCriticalSection(&p->mutex);
  17832. #ifdef SQLITE_DEBUG
  17833. if( p->trace ){
  17834. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17835. }
  17836. #endif
  17837. }
  17838. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17839. static const sqlite3_mutex_methods sMutex = {
  17840. winMutexInit,
  17841. winMutexEnd,
  17842. winMutexAlloc,
  17843. winMutexFree,
  17844. winMutexEnter,
  17845. winMutexTry,
  17846. winMutexLeave,
  17847. #ifdef SQLITE_DEBUG
  17848. winMutexHeld,
  17849. winMutexNotheld
  17850. #else
  17851. 0,
  17852. 0
  17853. #endif
  17854. };
  17855. return &sMutex;
  17856. }
  17857. #endif /* SQLITE_MUTEX_W32 */
  17858. /************** End of mutex_w32.c *******************************************/
  17859. /************** Begin file malloc.c ******************************************/
  17860. /*
  17861. ** 2001 September 15
  17862. **
  17863. ** The author disclaims copyright to this source code. In place of
  17864. ** a legal notice, here is a blessing:
  17865. **
  17866. ** May you do good and not evil.
  17867. ** May you find forgiveness for yourself and forgive others.
  17868. ** May you share freely, never taking more than you give.
  17869. **
  17870. *************************************************************************
  17871. **
  17872. ** Memory allocation functions used throughout sqlite.
  17873. */
  17874. /* #include <stdarg.h> */
  17875. /*
  17876. ** Attempt to release up to n bytes of non-essential memory currently
  17877. ** held by SQLite. An example of non-essential memory is memory used to
  17878. ** cache database pages that are not currently in use.
  17879. */
  17880. SQLITE_API int sqlite3_release_memory(int n){
  17881. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  17882. return sqlite3PcacheReleaseMemory(n);
  17883. #else
  17884. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  17885. ** is a no-op returning zero if SQLite is not compiled with
  17886. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  17887. UNUSED_PARAMETER(n);
  17888. return 0;
  17889. #endif
  17890. }
  17891. /*
  17892. ** An instance of the following object records the location of
  17893. ** each unused scratch buffer.
  17894. */
  17895. typedef struct ScratchFreeslot {
  17896. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  17897. } ScratchFreeslot;
  17898. /*
  17899. ** State information local to the memory allocation subsystem.
  17900. */
  17901. static SQLITE_WSD struct Mem0Global {
  17902. sqlite3_mutex *mutex; /* Mutex to serialize access */
  17903. /*
  17904. ** The alarm callback and its arguments. The mem0.mutex lock will
  17905. ** be held while the callback is running. Recursive calls into
  17906. ** the memory subsystem are allowed, but no new callbacks will be
  17907. ** issued.
  17908. */
  17909. sqlite3_int64 alarmThreshold;
  17910. void (*alarmCallback)(void*, sqlite3_int64,int);
  17911. void *alarmArg;
  17912. /*
  17913. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  17914. ** (so that a range test can be used to determine if an allocation
  17915. ** being freed came from pScratch) and a pointer to the list of
  17916. ** unused scratch allocations.
  17917. */
  17918. void *pScratchEnd;
  17919. ScratchFreeslot *pScratchFree;
  17920. u32 nScratchFree;
  17921. /*
  17922. ** True if heap is nearly "full" where "full" is defined by the
  17923. ** sqlite3_soft_heap_limit() setting.
  17924. */
  17925. int nearlyFull;
  17926. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  17927. #define mem0 GLOBAL(struct Mem0Global, mem0)
  17928. /*
  17929. ** This routine runs when the memory allocator sees that the
  17930. ** total memory allocation is about to exceed the soft heap
  17931. ** limit.
  17932. */
  17933. static void softHeapLimitEnforcer(
  17934. void *NotUsed,
  17935. sqlite3_int64 NotUsed2,
  17936. int allocSize
  17937. ){
  17938. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  17939. sqlite3_release_memory(allocSize);
  17940. }
  17941. /*
  17942. ** Change the alarm callback
  17943. */
  17944. static int sqlite3MemoryAlarm(
  17945. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  17946. void *pArg,
  17947. sqlite3_int64 iThreshold
  17948. ){
  17949. int nUsed;
  17950. sqlite3_mutex_enter(mem0.mutex);
  17951. mem0.alarmCallback = xCallback;
  17952. mem0.alarmArg = pArg;
  17953. mem0.alarmThreshold = iThreshold;
  17954. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17955. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  17956. sqlite3_mutex_leave(mem0.mutex);
  17957. return SQLITE_OK;
  17958. }
  17959. #ifndef SQLITE_OMIT_DEPRECATED
  17960. /*
  17961. ** Deprecated external interface. Internal/core SQLite code
  17962. ** should call sqlite3MemoryAlarm.
  17963. */
  17964. SQLITE_API int sqlite3_memory_alarm(
  17965. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  17966. void *pArg,
  17967. sqlite3_int64 iThreshold
  17968. ){
  17969. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  17970. }
  17971. #endif
  17972. /*
  17973. ** Set the soft heap-size limit for the library. Passing a zero or
  17974. ** negative value indicates no limit.
  17975. */
  17976. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  17977. sqlite3_int64 priorLimit;
  17978. sqlite3_int64 excess;
  17979. #ifndef SQLITE_OMIT_AUTOINIT
  17980. int rc = sqlite3_initialize();
  17981. if( rc ) return -1;
  17982. #endif
  17983. sqlite3_mutex_enter(mem0.mutex);
  17984. priorLimit = mem0.alarmThreshold;
  17985. sqlite3_mutex_leave(mem0.mutex);
  17986. if( n<0 ) return priorLimit;
  17987. if( n>0 ){
  17988. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  17989. }else{
  17990. sqlite3MemoryAlarm(0, 0, 0);
  17991. }
  17992. excess = sqlite3_memory_used() - n;
  17993. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  17994. return priorLimit;
  17995. }
  17996. SQLITE_API void sqlite3_soft_heap_limit(int n){
  17997. if( n<0 ) n = 0;
  17998. sqlite3_soft_heap_limit64(n);
  17999. }
  18000. /*
  18001. ** Initialize the memory allocation subsystem.
  18002. */
  18003. SQLITE_PRIVATE int sqlite3MallocInit(void){
  18004. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  18005. sqlite3MemSetDefault();
  18006. }
  18007. memset(&mem0, 0, sizeof(mem0));
  18008. if( sqlite3GlobalConfig.bCoreMutex ){
  18009. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  18010. }
  18011. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  18012. && sqlite3GlobalConfig.nScratch>0 ){
  18013. int i, n, sz;
  18014. ScratchFreeslot *pSlot;
  18015. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  18016. sqlite3GlobalConfig.szScratch = sz;
  18017. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  18018. n = sqlite3GlobalConfig.nScratch;
  18019. mem0.pScratchFree = pSlot;
  18020. mem0.nScratchFree = n;
  18021. for(i=0; i<n-1; i++){
  18022. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  18023. pSlot = pSlot->pNext;
  18024. }
  18025. pSlot->pNext = 0;
  18026. mem0.pScratchEnd = (void*)&pSlot[1];
  18027. }else{
  18028. mem0.pScratchEnd = 0;
  18029. sqlite3GlobalConfig.pScratch = 0;
  18030. sqlite3GlobalConfig.szScratch = 0;
  18031. sqlite3GlobalConfig.nScratch = 0;
  18032. }
  18033. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  18034. || sqlite3GlobalConfig.nPage<1 ){
  18035. sqlite3GlobalConfig.pPage = 0;
  18036. sqlite3GlobalConfig.szPage = 0;
  18037. sqlite3GlobalConfig.nPage = 0;
  18038. }
  18039. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  18040. }
  18041. /*
  18042. ** Return true if the heap is currently under memory pressure - in other
  18043. ** words if the amount of heap used is close to the limit set by
  18044. ** sqlite3_soft_heap_limit().
  18045. */
  18046. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  18047. return mem0.nearlyFull;
  18048. }
  18049. /*
  18050. ** Deinitialize the memory allocation subsystem.
  18051. */
  18052. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  18053. if( sqlite3GlobalConfig.m.xShutdown ){
  18054. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  18055. }
  18056. memset(&mem0, 0, sizeof(mem0));
  18057. }
  18058. /*
  18059. ** Return the amount of memory currently checked out.
  18060. */
  18061. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  18062. int n, mx;
  18063. sqlite3_int64 res;
  18064. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  18065. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  18066. return res;
  18067. }
  18068. /*
  18069. ** Return the maximum amount of memory that has ever been
  18070. ** checked out since either the beginning of this process
  18071. ** or since the most recent reset.
  18072. */
  18073. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  18074. int n, mx;
  18075. sqlite3_int64 res;
  18076. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  18077. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  18078. return res;
  18079. }
  18080. /*
  18081. ** Trigger the alarm
  18082. */
  18083. static void sqlite3MallocAlarm(int nByte){
  18084. void (*xCallback)(void*,sqlite3_int64,int);
  18085. sqlite3_int64 nowUsed;
  18086. void *pArg;
  18087. if( mem0.alarmCallback==0 ) return;
  18088. xCallback = mem0.alarmCallback;
  18089. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  18090. pArg = mem0.alarmArg;
  18091. mem0.alarmCallback = 0;
  18092. sqlite3_mutex_leave(mem0.mutex);
  18093. xCallback(pArg, nowUsed, nByte);
  18094. sqlite3_mutex_enter(mem0.mutex);
  18095. mem0.alarmCallback = xCallback;
  18096. mem0.alarmArg = pArg;
  18097. }
  18098. /*
  18099. ** Do a memory allocation with statistics and alarms. Assume the
  18100. ** lock is already held.
  18101. */
  18102. static int mallocWithAlarm(int n, void **pp){
  18103. int nFull;
  18104. void *p;
  18105. assert( sqlite3_mutex_held(mem0.mutex) );
  18106. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  18107. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  18108. if( mem0.alarmCallback!=0 ){
  18109. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  18110. if( nUsed >= mem0.alarmThreshold - nFull ){
  18111. mem0.nearlyFull = 1;
  18112. sqlite3MallocAlarm(nFull);
  18113. }else{
  18114. mem0.nearlyFull = 0;
  18115. }
  18116. }
  18117. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  18118. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  18119. if( p==0 && mem0.alarmCallback ){
  18120. sqlite3MallocAlarm(nFull);
  18121. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  18122. }
  18123. #endif
  18124. if( p ){
  18125. nFull = sqlite3MallocSize(p);
  18126. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  18127. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
  18128. }
  18129. *pp = p;
  18130. return nFull;
  18131. }
  18132. /*
  18133. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  18134. ** assumes the memory subsystem has already been initialized.
  18135. */
  18136. SQLITE_PRIVATE void *sqlite3Malloc(int n){
  18137. void *p;
  18138. if( n<=0 /* IMP: R-65312-04917 */
  18139. || n>=0x7fffff00
  18140. ){
  18141. /* A memory allocation of a number of bytes which is near the maximum
  18142. ** signed integer value might cause an integer overflow inside of the
  18143. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  18144. ** 255 bytes of overhead. SQLite itself will never use anything near
  18145. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  18146. p = 0;
  18147. }else if( sqlite3GlobalConfig.bMemstat ){
  18148. sqlite3_mutex_enter(mem0.mutex);
  18149. mallocWithAlarm(n, &p);
  18150. sqlite3_mutex_leave(mem0.mutex);
  18151. }else{
  18152. p = sqlite3GlobalConfig.m.xMalloc(n);
  18153. }
  18154. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
  18155. return p;
  18156. }
  18157. /*
  18158. ** This version of the memory allocation is for use by the application.
  18159. ** First make sure the memory subsystem is initialized, then do the
  18160. ** allocation.
  18161. */
  18162. SQLITE_API void *sqlite3_malloc(int n){
  18163. #ifndef SQLITE_OMIT_AUTOINIT
  18164. if( sqlite3_initialize() ) return 0;
  18165. #endif
  18166. return sqlite3Malloc(n);
  18167. }
  18168. /*
  18169. ** Each thread may only have a single outstanding allocation from
  18170. ** xScratchMalloc(). We verify this constraint in the single-threaded
  18171. ** case by setting scratchAllocOut to 1 when an allocation
  18172. ** is outstanding clearing it when the allocation is freed.
  18173. */
  18174. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18175. static int scratchAllocOut = 0;
  18176. #endif
  18177. /*
  18178. ** Allocate memory that is to be used and released right away.
  18179. ** This routine is similar to alloca() in that it is not intended
  18180. ** for situations where the memory might be held long-term. This
  18181. ** routine is intended to get memory to old large transient data
  18182. ** structures that would not normally fit on the stack of an
  18183. ** embedded processor.
  18184. */
  18185. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  18186. void *p;
  18187. assert( n>0 );
  18188. sqlite3_mutex_enter(mem0.mutex);
  18189. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  18190. p = mem0.pScratchFree;
  18191. mem0.pScratchFree = mem0.pScratchFree->pNext;
  18192. mem0.nScratchFree--;
  18193. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  18194. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  18195. sqlite3_mutex_leave(mem0.mutex);
  18196. }else{
  18197. if( sqlite3GlobalConfig.bMemstat ){
  18198. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  18199. n = mallocWithAlarm(n, &p);
  18200. if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
  18201. sqlite3_mutex_leave(mem0.mutex);
  18202. }else{
  18203. sqlite3_mutex_leave(mem0.mutex);
  18204. p = sqlite3GlobalConfig.m.xMalloc(n);
  18205. }
  18206. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  18207. }
  18208. assert( sqlite3_mutex_notheld(mem0.mutex) );
  18209. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18210. /* Verify that no more than two scratch allocations per thread
  18211. ** are outstanding at one time. (This is only checked in the
  18212. ** single-threaded case since checking in the multi-threaded case
  18213. ** would be much more complicated.) */
  18214. assert( scratchAllocOut<=1 );
  18215. if( p ) scratchAllocOut++;
  18216. #endif
  18217. return p;
  18218. }
  18219. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  18220. if( p ){
  18221. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18222. /* Verify that no more than two scratch allocation per thread
  18223. ** is outstanding at one time. (This is only checked in the
  18224. ** single-threaded case since checking in the multi-threaded case
  18225. ** would be much more complicated.) */
  18226. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  18227. scratchAllocOut--;
  18228. #endif
  18229. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  18230. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  18231. ScratchFreeslot *pSlot;
  18232. pSlot = (ScratchFreeslot*)p;
  18233. sqlite3_mutex_enter(mem0.mutex);
  18234. pSlot->pNext = mem0.pScratchFree;
  18235. mem0.pScratchFree = pSlot;
  18236. mem0.nScratchFree++;
  18237. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  18238. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  18239. sqlite3_mutex_leave(mem0.mutex);
  18240. }else{
  18241. /* Release memory back to the heap */
  18242. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  18243. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
  18244. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18245. if( sqlite3GlobalConfig.bMemstat ){
  18246. int iSize = sqlite3MallocSize(p);
  18247. sqlite3_mutex_enter(mem0.mutex);
  18248. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  18249. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  18250. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18251. sqlite3GlobalConfig.m.xFree(p);
  18252. sqlite3_mutex_leave(mem0.mutex);
  18253. }else{
  18254. sqlite3GlobalConfig.m.xFree(p);
  18255. }
  18256. }
  18257. }
  18258. }
  18259. /*
  18260. ** TRUE if p is a lookaside memory allocation from db
  18261. */
  18262. #ifndef SQLITE_OMIT_LOOKASIDE
  18263. static int isLookaside(sqlite3 *db, void *p){
  18264. return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  18265. }
  18266. #else
  18267. #define isLookaside(A,B) 0
  18268. #endif
  18269. /*
  18270. ** Return the size of a memory allocation previously obtained from
  18271. ** sqlite3Malloc() or sqlite3_malloc().
  18272. */
  18273. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  18274. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18275. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18276. return sqlite3GlobalConfig.m.xSize(p);
  18277. }
  18278. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  18279. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18280. if( db && isLookaside(db, p) ){
  18281. return db->lookaside.sz;
  18282. }else{
  18283. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18284. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18285. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18286. return sqlite3GlobalConfig.m.xSize(p);
  18287. }
  18288. }
  18289. /*
  18290. ** Free memory previously obtained from sqlite3Malloc().
  18291. */
  18292. SQLITE_API void sqlite3_free(void *p){
  18293. if( p==0 ) return; /* IMP: R-49053-54554 */
  18294. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18295. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18296. if( sqlite3GlobalConfig.bMemstat ){
  18297. sqlite3_mutex_enter(mem0.mutex);
  18298. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  18299. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18300. sqlite3GlobalConfig.m.xFree(p);
  18301. sqlite3_mutex_leave(mem0.mutex);
  18302. }else{
  18303. sqlite3GlobalConfig.m.xFree(p);
  18304. }
  18305. }
  18306. /*
  18307. ** Free memory that might be associated with a particular database
  18308. ** connection.
  18309. */
  18310. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  18311. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18312. if( p==0 ) return;
  18313. if( db ){
  18314. if( db->pnBytesFreed ){
  18315. *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
  18316. return;
  18317. }
  18318. if( isLookaside(db, p) ){
  18319. LookasideSlot *pBuf = (LookasideSlot*)p;
  18320. #if SQLITE_DEBUG
  18321. /* Trash all content in the buffer being freed */
  18322. memset(p, 0xaa, db->lookaside.sz);
  18323. #endif
  18324. pBuf->pNext = db->lookaside.pFree;
  18325. db->lookaside.pFree = pBuf;
  18326. db->lookaside.nOut--;
  18327. return;
  18328. }
  18329. }
  18330. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18331. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18332. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18333. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18334. sqlite3_free(p);
  18335. }
  18336. /*
  18337. ** Change the size of an existing memory allocation
  18338. */
  18339. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
  18340. int nOld, nNew, nDiff;
  18341. void *pNew;
  18342. if( pOld==0 ){
  18343. return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
  18344. }
  18345. if( nBytes<=0 ){
  18346. sqlite3_free(pOld); /* IMP: R-31593-10574 */
  18347. return 0;
  18348. }
  18349. if( nBytes>=0x7fffff00 ){
  18350. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  18351. return 0;
  18352. }
  18353. nOld = sqlite3MallocSize(pOld);
  18354. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  18355. ** argument to xRealloc is always a value returned by a prior call to
  18356. ** xRoundup. */
  18357. nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
  18358. if( nOld==nNew ){
  18359. pNew = pOld;
  18360. }else if( sqlite3GlobalConfig.bMemstat ){
  18361. sqlite3_mutex_enter(mem0.mutex);
  18362. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
  18363. nDiff = nNew - nOld;
  18364. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  18365. mem0.alarmThreshold-nDiff ){
  18366. sqlite3MallocAlarm(nDiff);
  18367. }
  18368. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  18369. assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
  18370. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18371. if( pNew==0 && mem0.alarmCallback ){
  18372. sqlite3MallocAlarm(nBytes);
  18373. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18374. }
  18375. if( pNew ){
  18376. nNew = sqlite3MallocSize(pNew);
  18377. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  18378. }
  18379. sqlite3_mutex_leave(mem0.mutex);
  18380. }else{
  18381. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18382. }
  18383. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  18384. return pNew;
  18385. }
  18386. /*
  18387. ** The public interface to sqlite3Realloc. Make sure that the memory
  18388. ** subsystem is initialized prior to invoking sqliteRealloc.
  18389. */
  18390. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  18391. #ifndef SQLITE_OMIT_AUTOINIT
  18392. if( sqlite3_initialize() ) return 0;
  18393. #endif
  18394. return sqlite3Realloc(pOld, n);
  18395. }
  18396. /*
  18397. ** Allocate and zero memory.
  18398. */
  18399. SQLITE_PRIVATE void *sqlite3MallocZero(int n){
  18400. void *p = sqlite3Malloc(n);
  18401. if( p ){
  18402. memset(p, 0, n);
  18403. }
  18404. return p;
  18405. }
  18406. /*
  18407. ** Allocate and zero memory. If the allocation fails, make
  18408. ** the mallocFailed flag in the connection pointer.
  18409. */
  18410. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
  18411. void *p = sqlite3DbMallocRaw(db, n);
  18412. if( p ){
  18413. memset(p, 0, n);
  18414. }
  18415. return p;
  18416. }
  18417. /*
  18418. ** Allocate and zero memory. If the allocation fails, make
  18419. ** the mallocFailed flag in the connection pointer.
  18420. **
  18421. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  18422. ** failure on the same database connection) then always return 0.
  18423. ** Hence for a particular database connection, once malloc starts
  18424. ** failing, it fails consistently until mallocFailed is reset.
  18425. ** This is an important assumption. There are many places in the
  18426. ** code that do things like this:
  18427. **
  18428. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  18429. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  18430. ** if( b ) a[10] = 9;
  18431. **
  18432. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  18433. ** that all prior mallocs (ex: "a") worked too.
  18434. */
  18435. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
  18436. void *p;
  18437. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18438. assert( db==0 || db->pnBytesFreed==0 );
  18439. #ifndef SQLITE_OMIT_LOOKASIDE
  18440. if( db ){
  18441. LookasideSlot *pBuf;
  18442. if( db->mallocFailed ){
  18443. return 0;
  18444. }
  18445. if( db->lookaside.bEnabled ){
  18446. if( n>db->lookaside.sz ){
  18447. db->lookaside.anStat[1]++;
  18448. }else if( (pBuf = db->lookaside.pFree)==0 ){
  18449. db->lookaside.anStat[2]++;
  18450. }else{
  18451. db->lookaside.pFree = pBuf->pNext;
  18452. db->lookaside.nOut++;
  18453. db->lookaside.anStat[0]++;
  18454. if( db->lookaside.nOut>db->lookaside.mxOut ){
  18455. db->lookaside.mxOut = db->lookaside.nOut;
  18456. }
  18457. return (void*)pBuf;
  18458. }
  18459. }
  18460. }
  18461. #else
  18462. if( db && db->mallocFailed ){
  18463. return 0;
  18464. }
  18465. #endif
  18466. p = sqlite3Malloc(n);
  18467. if( !p && db ){
  18468. db->mallocFailed = 1;
  18469. }
  18470. sqlite3MemdebugSetType(p, MEMTYPE_DB |
  18471. ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18472. return p;
  18473. }
  18474. /*
  18475. ** Resize the block of memory pointed to by p to n bytes. If the
  18476. ** resize fails, set the mallocFailed flag in the connection object.
  18477. */
  18478. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
  18479. void *pNew = 0;
  18480. assert( db!=0 );
  18481. assert( sqlite3_mutex_held(db->mutex) );
  18482. if( db->mallocFailed==0 ){
  18483. if( p==0 ){
  18484. return sqlite3DbMallocRaw(db, n);
  18485. }
  18486. if( isLookaside(db, p) ){
  18487. if( n<=db->lookaside.sz ){
  18488. return p;
  18489. }
  18490. pNew = sqlite3DbMallocRaw(db, n);
  18491. if( pNew ){
  18492. memcpy(pNew, p, db->lookaside.sz);
  18493. sqlite3DbFree(db, p);
  18494. }
  18495. }else{
  18496. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18497. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18498. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18499. pNew = sqlite3_realloc(p, n);
  18500. if( !pNew ){
  18501. sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
  18502. db->mallocFailed = 1;
  18503. }
  18504. sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
  18505. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18506. }
  18507. }
  18508. return pNew;
  18509. }
  18510. /*
  18511. ** Attempt to reallocate p. If the reallocation fails, then free p
  18512. ** and set the mallocFailed flag in the database connection.
  18513. */
  18514. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
  18515. void *pNew;
  18516. pNew = sqlite3DbRealloc(db, p, n);
  18517. if( !pNew ){
  18518. sqlite3DbFree(db, p);
  18519. }
  18520. return pNew;
  18521. }
  18522. /*
  18523. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  18524. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  18525. ** is because when memory debugging is turned on, these two functions are
  18526. ** called via macros that record the current file and line number in the
  18527. ** ThreadData structure.
  18528. */
  18529. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  18530. char *zNew;
  18531. size_t n;
  18532. if( z==0 ){
  18533. return 0;
  18534. }
  18535. n = sqlite3Strlen30(z) + 1;
  18536. assert( (n&0x7fffffff)==n );
  18537. zNew = sqlite3DbMallocRaw(db, (int)n);
  18538. if( zNew ){
  18539. memcpy(zNew, z, n);
  18540. }
  18541. return zNew;
  18542. }
  18543. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
  18544. char *zNew;
  18545. if( z==0 ){
  18546. return 0;
  18547. }
  18548. assert( (n&0x7fffffff)==n );
  18549. zNew = sqlite3DbMallocRaw(db, n+1);
  18550. if( zNew ){
  18551. memcpy(zNew, z, n);
  18552. zNew[n] = 0;
  18553. }
  18554. return zNew;
  18555. }
  18556. /*
  18557. ** Create a string from the zFromat argument and the va_list that follows.
  18558. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  18559. ** point to that string.
  18560. */
  18561. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  18562. va_list ap;
  18563. char *z;
  18564. va_start(ap, zFormat);
  18565. z = sqlite3VMPrintf(db, zFormat, ap);
  18566. va_end(ap);
  18567. sqlite3DbFree(db, *pz);
  18568. *pz = z;
  18569. }
  18570. /*
  18571. ** This function must be called before exiting any API function (i.e.
  18572. ** returning control to the user) that has called sqlite3_malloc or
  18573. ** sqlite3_realloc.
  18574. **
  18575. ** The returned value is normally a copy of the second argument to this
  18576. ** function. However, if a malloc() failure has occurred since the previous
  18577. ** invocation SQLITE_NOMEM is returned instead.
  18578. **
  18579. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  18580. ** then the connection error-code (the value returned by sqlite3_errcode())
  18581. ** is set to SQLITE_NOMEM.
  18582. */
  18583. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  18584. /* If the db handle is not NULL, then we must hold the connection handle
  18585. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  18586. ** is unsafe, as is the call to sqlite3Error().
  18587. */
  18588. assert( !db || sqlite3_mutex_held(db->mutex) );
  18589. if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
  18590. sqlite3Error(db, SQLITE_NOMEM, 0);
  18591. db->mallocFailed = 0;
  18592. rc = SQLITE_NOMEM;
  18593. }
  18594. return rc & (db ? db->errMask : 0xff);
  18595. }
  18596. /************** End of malloc.c **********************************************/
  18597. /************** Begin file printf.c ******************************************/
  18598. /*
  18599. ** The "printf" code that follows dates from the 1980's. It is in
  18600. ** the public domain. The original comments are included here for
  18601. ** completeness. They are very out-of-date but might be useful as
  18602. ** an historical reference. Most of the "enhancements" have been backed
  18603. ** out so that the functionality is now the same as standard printf().
  18604. **
  18605. **************************************************************************
  18606. **
  18607. ** This file contains code for a set of "printf"-like routines. These
  18608. ** routines format strings much like the printf() from the standard C
  18609. ** library, though the implementation here has enhancements to support
  18610. ** SQLlite.
  18611. */
  18612. /*
  18613. ** Conversion types fall into various categories as defined by the
  18614. ** following enumeration.
  18615. */
  18616. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  18617. #define etFLOAT 2 /* Floating point. %f */
  18618. #define etEXP 3 /* Exponentional notation. %e and %E */
  18619. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  18620. #define etSIZE 5 /* Return number of characters processed so far. %n */
  18621. #define etSTRING 6 /* Strings. %s */
  18622. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  18623. #define etPERCENT 8 /* Percent symbol. %% */
  18624. #define etCHARX 9 /* Characters. %c */
  18625. /* The rest are extensions, not normally found in printf() */
  18626. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  18627. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  18628. NULL pointers replaced by SQL NULL. %Q */
  18629. #define etTOKEN 12 /* a pointer to a Token structure */
  18630. #define etSRCLIST 13 /* a pointer to a SrcList */
  18631. #define etPOINTER 14 /* The %p conversion */
  18632. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  18633. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  18634. #define etINVALID 0 /* Any unrecognized conversion type */
  18635. /*
  18636. ** An "etByte" is an 8-bit unsigned value.
  18637. */
  18638. typedef unsigned char etByte;
  18639. /*
  18640. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  18641. ** by an instance of the following structure
  18642. */
  18643. typedef struct et_info { /* Information about each format field */
  18644. char fmttype; /* The format field code letter */
  18645. etByte base; /* The base for radix conversion */
  18646. etByte flags; /* One or more of FLAG_ constants below */
  18647. etByte type; /* Conversion paradigm */
  18648. etByte charset; /* Offset into aDigits[] of the digits string */
  18649. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  18650. } et_info;
  18651. /*
  18652. ** Allowed values for et_info.flags
  18653. */
  18654. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  18655. #define FLAG_INTERN 2 /* True if for internal use only */
  18656. #define FLAG_STRING 4 /* Allow infinity precision */
  18657. /*
  18658. ** The following table is searched linearly, so it is good to put the
  18659. ** most frequently used conversion types first.
  18660. */
  18661. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  18662. static const char aPrefix[] = "-x0\000X0";
  18663. static const et_info fmtinfo[] = {
  18664. { 'd', 10, 1, etRADIX, 0, 0 },
  18665. { 's', 0, 4, etSTRING, 0, 0 },
  18666. { 'g', 0, 1, etGENERIC, 30, 0 },
  18667. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  18668. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  18669. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  18670. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  18671. { 'c', 0, 0, etCHARX, 0, 0 },
  18672. { 'o', 8, 0, etRADIX, 0, 2 },
  18673. { 'u', 10, 0, etRADIX, 0, 0 },
  18674. { 'x', 16, 0, etRADIX, 16, 1 },
  18675. { 'X', 16, 0, etRADIX, 0, 4 },
  18676. #ifndef SQLITE_OMIT_FLOATING_POINT
  18677. { 'f', 0, 1, etFLOAT, 0, 0 },
  18678. { 'e', 0, 1, etEXP, 30, 0 },
  18679. { 'E', 0, 1, etEXP, 14, 0 },
  18680. { 'G', 0, 1, etGENERIC, 14, 0 },
  18681. #endif
  18682. { 'i', 10, 1, etRADIX, 0, 0 },
  18683. { 'n', 0, 0, etSIZE, 0, 0 },
  18684. { '%', 0, 0, etPERCENT, 0, 0 },
  18685. { 'p', 16, 0, etPOINTER, 0, 1 },
  18686. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  18687. ** use only */
  18688. { 'T', 0, 2, etTOKEN, 0, 0 },
  18689. { 'S', 0, 2, etSRCLIST, 0, 0 },
  18690. { 'r', 10, 3, etORDINAL, 0, 0 },
  18691. };
  18692. /*
  18693. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  18694. ** conversions will work.
  18695. */
  18696. #ifndef SQLITE_OMIT_FLOATING_POINT
  18697. /*
  18698. ** "*val" is a double such that 0.1 <= *val < 10.0
  18699. ** Return the ascii code for the leading digit of *val, then
  18700. ** multiply "*val" by 10.0 to renormalize.
  18701. **
  18702. ** Example:
  18703. ** input: *val = 3.14159
  18704. ** output: *val = 1.4159 function return = '3'
  18705. **
  18706. ** The counter *cnt is incremented each time. After counter exceeds
  18707. ** 16 (the number of significant digits in a 64-bit float) '0' is
  18708. ** always returned.
  18709. */
  18710. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  18711. int digit;
  18712. LONGDOUBLE_TYPE d;
  18713. if( (*cnt)<=0 ) return '0';
  18714. (*cnt)--;
  18715. digit = (int)*val;
  18716. d = digit;
  18717. digit += '0';
  18718. *val = (*val - d)*10.0;
  18719. return (char)digit;
  18720. }
  18721. #endif /* SQLITE_OMIT_FLOATING_POINT */
  18722. /*
  18723. ** Append N space characters to the given string buffer.
  18724. */
  18725. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
  18726. static const char zSpaces[] = " ";
  18727. while( N>=(int)sizeof(zSpaces)-1 ){
  18728. sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
  18729. N -= sizeof(zSpaces)-1;
  18730. }
  18731. if( N>0 ){
  18732. sqlite3StrAccumAppend(pAccum, zSpaces, N);
  18733. }
  18734. }
  18735. /*
  18736. ** On machines with a small stack size, you can redefine the
  18737. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  18738. */
  18739. #ifndef SQLITE_PRINT_BUF_SIZE
  18740. # define SQLITE_PRINT_BUF_SIZE 70
  18741. #endif
  18742. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  18743. /*
  18744. ** Render a string given by "fmt" into the StrAccum object.
  18745. */
  18746. SQLITE_PRIVATE void sqlite3VXPrintf(
  18747. StrAccum *pAccum, /* Accumulate results here */
  18748. int useExtended, /* Allow extended %-conversions */
  18749. const char *fmt, /* Format string */
  18750. va_list ap /* arguments */
  18751. ){
  18752. int c; /* Next character in the format string */
  18753. char *bufpt; /* Pointer to the conversion buffer */
  18754. int precision; /* Precision of the current field */
  18755. int length; /* Length of the field */
  18756. int idx; /* A general purpose loop counter */
  18757. int width; /* Width of the current field */
  18758. etByte flag_leftjustify; /* True if "-" flag is present */
  18759. etByte flag_plussign; /* True if "+" flag is present */
  18760. etByte flag_blanksign; /* True if " " flag is present */
  18761. etByte flag_alternateform; /* True if "#" flag is present */
  18762. etByte flag_altform2; /* True if "!" flag is present */
  18763. etByte flag_zeropad; /* True if field width constant starts with zero */
  18764. etByte flag_long; /* True if "l" flag is present */
  18765. etByte flag_longlong; /* True if the "ll" flag is present */
  18766. etByte done; /* Loop termination flag */
  18767. etByte xtype = 0; /* Conversion paradigm */
  18768. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  18769. sqlite_uint64 longvalue; /* Value for integer types */
  18770. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  18771. const et_info *infop; /* Pointer to the appropriate info structure */
  18772. char *zOut; /* Rendering buffer */
  18773. int nOut; /* Size of the rendering buffer */
  18774. char *zExtra; /* Malloced memory used by some conversion */
  18775. #ifndef SQLITE_OMIT_FLOATING_POINT
  18776. int exp, e2; /* exponent of real numbers */
  18777. int nsd; /* Number of significant digits returned */
  18778. double rounder; /* Used for rounding floating point values */
  18779. etByte flag_dp; /* True if decimal point should be shown */
  18780. etByte flag_rtz; /* True if trailing zeros should be removed */
  18781. #endif
  18782. char buf[etBUFSIZE]; /* Conversion buffer */
  18783. bufpt = 0;
  18784. for(; (c=(*fmt))!=0; ++fmt){
  18785. if( c!='%' ){
  18786. int amt;
  18787. bufpt = (char *)fmt;
  18788. amt = 1;
  18789. while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  18790. sqlite3StrAccumAppend(pAccum, bufpt, amt);
  18791. if( c==0 ) break;
  18792. }
  18793. if( (c=(*++fmt))==0 ){
  18794. sqlite3StrAccumAppend(pAccum, "%", 1);
  18795. break;
  18796. }
  18797. /* Find out what flags are present */
  18798. flag_leftjustify = flag_plussign = flag_blanksign =
  18799. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  18800. done = 0;
  18801. do{
  18802. switch( c ){
  18803. case '-': flag_leftjustify = 1; break;
  18804. case '+': flag_plussign = 1; break;
  18805. case ' ': flag_blanksign = 1; break;
  18806. case '#': flag_alternateform = 1; break;
  18807. case '!': flag_altform2 = 1; break;
  18808. case '0': flag_zeropad = 1; break;
  18809. default: done = 1; break;
  18810. }
  18811. }while( !done && (c=(*++fmt))!=0 );
  18812. /* Get the field width */
  18813. width = 0;
  18814. if( c=='*' ){
  18815. width = va_arg(ap,int);
  18816. if( width<0 ){
  18817. flag_leftjustify = 1;
  18818. width = -width;
  18819. }
  18820. c = *++fmt;
  18821. }else{
  18822. while( c>='0' && c<='9' ){
  18823. width = width*10 + c - '0';
  18824. c = *++fmt;
  18825. }
  18826. }
  18827. /* Get the precision */
  18828. if( c=='.' ){
  18829. precision = 0;
  18830. c = *++fmt;
  18831. if( c=='*' ){
  18832. precision = va_arg(ap,int);
  18833. if( precision<0 ) precision = -precision;
  18834. c = *++fmt;
  18835. }else{
  18836. while( c>='0' && c<='9' ){
  18837. precision = precision*10 + c - '0';
  18838. c = *++fmt;
  18839. }
  18840. }
  18841. }else{
  18842. precision = -1;
  18843. }
  18844. /* Get the conversion type modifier */
  18845. if( c=='l' ){
  18846. flag_long = 1;
  18847. c = *++fmt;
  18848. if( c=='l' ){
  18849. flag_longlong = 1;
  18850. c = *++fmt;
  18851. }else{
  18852. flag_longlong = 0;
  18853. }
  18854. }else{
  18855. flag_long = flag_longlong = 0;
  18856. }
  18857. /* Fetch the info entry for the field */
  18858. infop = &fmtinfo[0];
  18859. xtype = etINVALID;
  18860. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  18861. if( c==fmtinfo[idx].fmttype ){
  18862. infop = &fmtinfo[idx];
  18863. if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  18864. xtype = infop->type;
  18865. }else{
  18866. return;
  18867. }
  18868. break;
  18869. }
  18870. }
  18871. zExtra = 0;
  18872. /*
  18873. ** At this point, variables are initialized as follows:
  18874. **
  18875. ** flag_alternateform TRUE if a '#' is present.
  18876. ** flag_altform2 TRUE if a '!' is present.
  18877. ** flag_plussign TRUE if a '+' is present.
  18878. ** flag_leftjustify TRUE if a '-' is present or if the
  18879. ** field width was negative.
  18880. ** flag_zeropad TRUE if the width began with 0.
  18881. ** flag_long TRUE if the letter 'l' (ell) prefixed
  18882. ** the conversion character.
  18883. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  18884. ** the conversion character.
  18885. ** flag_blanksign TRUE if a ' ' is present.
  18886. ** width The specified field width. This is
  18887. ** always non-negative. Zero is the default.
  18888. ** precision The specified precision. The default
  18889. ** is -1.
  18890. ** xtype The class of the conversion.
  18891. ** infop Pointer to the appropriate info struct.
  18892. */
  18893. switch( xtype ){
  18894. case etPOINTER:
  18895. flag_longlong = sizeof(char*)==sizeof(i64);
  18896. flag_long = sizeof(char*)==sizeof(long int);
  18897. /* Fall through into the next case */
  18898. case etORDINAL:
  18899. case etRADIX:
  18900. if( infop->flags & FLAG_SIGNED ){
  18901. i64 v;
  18902. if( flag_longlong ){
  18903. v = va_arg(ap,i64);
  18904. }else if( flag_long ){
  18905. v = va_arg(ap,long int);
  18906. }else{
  18907. v = va_arg(ap,int);
  18908. }
  18909. if( v<0 ){
  18910. if( v==SMALLEST_INT64 ){
  18911. longvalue = ((u64)1)<<63;
  18912. }else{
  18913. longvalue = -v;
  18914. }
  18915. prefix = '-';
  18916. }else{
  18917. longvalue = v;
  18918. if( flag_plussign ) prefix = '+';
  18919. else if( flag_blanksign ) prefix = ' ';
  18920. else prefix = 0;
  18921. }
  18922. }else{
  18923. if( flag_longlong ){
  18924. longvalue = va_arg(ap,u64);
  18925. }else if( flag_long ){
  18926. longvalue = va_arg(ap,unsigned long int);
  18927. }else{
  18928. longvalue = va_arg(ap,unsigned int);
  18929. }
  18930. prefix = 0;
  18931. }
  18932. if( longvalue==0 ) flag_alternateform = 0;
  18933. if( flag_zeropad && precision<width-(prefix!=0) ){
  18934. precision = width-(prefix!=0);
  18935. }
  18936. if( precision<etBUFSIZE-10 ){
  18937. nOut = etBUFSIZE;
  18938. zOut = buf;
  18939. }else{
  18940. nOut = precision + 10;
  18941. zOut = zExtra = sqlite3Malloc( nOut );
  18942. if( zOut==0 ){
  18943. pAccum->accError = STRACCUM_NOMEM;
  18944. return;
  18945. }
  18946. }
  18947. bufpt = &zOut[nOut-1];
  18948. if( xtype==etORDINAL ){
  18949. static const char zOrd[] = "thstndrd";
  18950. int x = (int)(longvalue % 10);
  18951. if( x>=4 || (longvalue/10)%10==1 ){
  18952. x = 0;
  18953. }
  18954. *(--bufpt) = zOrd[x*2+1];
  18955. *(--bufpt) = zOrd[x*2];
  18956. }
  18957. {
  18958. register const char *cset; /* Use registers for speed */
  18959. register int base;
  18960. cset = &aDigits[infop->charset];
  18961. base = infop->base;
  18962. do{ /* Convert to ascii */
  18963. *(--bufpt) = cset[longvalue%base];
  18964. longvalue = longvalue/base;
  18965. }while( longvalue>0 );
  18966. }
  18967. length = (int)(&zOut[nOut-1]-bufpt);
  18968. for(idx=precision-length; idx>0; idx--){
  18969. *(--bufpt) = '0'; /* Zero pad */
  18970. }
  18971. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  18972. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  18973. const char *pre;
  18974. char x;
  18975. pre = &aPrefix[infop->prefix];
  18976. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  18977. }
  18978. length = (int)(&zOut[nOut-1]-bufpt);
  18979. break;
  18980. case etFLOAT:
  18981. case etEXP:
  18982. case etGENERIC:
  18983. realvalue = va_arg(ap,double);
  18984. #ifdef SQLITE_OMIT_FLOATING_POINT
  18985. length = 0;
  18986. #else
  18987. if( precision<0 ) precision = 6; /* Set default precision */
  18988. if( realvalue<0.0 ){
  18989. realvalue = -realvalue;
  18990. prefix = '-';
  18991. }else{
  18992. if( flag_plussign ) prefix = '+';
  18993. else if( flag_blanksign ) prefix = ' ';
  18994. else prefix = 0;
  18995. }
  18996. if( xtype==etGENERIC && precision>0 ) precision--;
  18997. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  18998. if( xtype==etFLOAT ) realvalue += rounder;
  18999. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  19000. exp = 0;
  19001. if( sqlite3IsNaN((double)realvalue) ){
  19002. bufpt = "NaN";
  19003. length = 3;
  19004. break;
  19005. }
  19006. if( realvalue>0.0 ){
  19007. LONGDOUBLE_TYPE scale = 1.0;
  19008. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  19009. while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
  19010. while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
  19011. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  19012. realvalue /= scale;
  19013. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  19014. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  19015. if( exp>350 ){
  19016. if( prefix=='-' ){
  19017. bufpt = "-Inf";
  19018. }else if( prefix=='+' ){
  19019. bufpt = "+Inf";
  19020. }else{
  19021. bufpt = "Inf";
  19022. }
  19023. length = sqlite3Strlen30(bufpt);
  19024. break;
  19025. }
  19026. }
  19027. bufpt = buf;
  19028. /*
  19029. ** If the field type is etGENERIC, then convert to either etEXP
  19030. ** or etFLOAT, as appropriate.
  19031. */
  19032. if( xtype!=etFLOAT ){
  19033. realvalue += rounder;
  19034. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  19035. }
  19036. if( xtype==etGENERIC ){
  19037. flag_rtz = !flag_alternateform;
  19038. if( exp<-4 || exp>precision ){
  19039. xtype = etEXP;
  19040. }else{
  19041. precision = precision - exp;
  19042. xtype = etFLOAT;
  19043. }
  19044. }else{
  19045. flag_rtz = flag_altform2;
  19046. }
  19047. if( xtype==etEXP ){
  19048. e2 = 0;
  19049. }else{
  19050. e2 = exp;
  19051. }
  19052. if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
  19053. bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
  19054. if( bufpt==0 ){
  19055. pAccum->accError = STRACCUM_NOMEM;
  19056. return;
  19057. }
  19058. }
  19059. zOut = bufpt;
  19060. nsd = 16 + flag_altform2*10;
  19061. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  19062. /* The sign in front of the number */
  19063. if( prefix ){
  19064. *(bufpt++) = prefix;
  19065. }
  19066. /* Digits prior to the decimal point */
  19067. if( e2<0 ){
  19068. *(bufpt++) = '0';
  19069. }else{
  19070. for(; e2>=0; e2--){
  19071. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  19072. }
  19073. }
  19074. /* The decimal point */
  19075. if( flag_dp ){
  19076. *(bufpt++) = '.';
  19077. }
  19078. /* "0" digits after the decimal point but before the first
  19079. ** significant digit of the number */
  19080. for(e2++; e2<0; precision--, e2++){
  19081. assert( precision>0 );
  19082. *(bufpt++) = '0';
  19083. }
  19084. /* Significant digits after the decimal point */
  19085. while( (precision--)>0 ){
  19086. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  19087. }
  19088. /* Remove trailing zeros and the "." if no digits follow the "." */
  19089. if( flag_rtz && flag_dp ){
  19090. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  19091. assert( bufpt>zOut );
  19092. if( bufpt[-1]=='.' ){
  19093. if( flag_altform2 ){
  19094. *(bufpt++) = '0';
  19095. }else{
  19096. *(--bufpt) = 0;
  19097. }
  19098. }
  19099. }
  19100. /* Add the "eNNN" suffix */
  19101. if( xtype==etEXP ){
  19102. *(bufpt++) = aDigits[infop->charset];
  19103. if( exp<0 ){
  19104. *(bufpt++) = '-'; exp = -exp;
  19105. }else{
  19106. *(bufpt++) = '+';
  19107. }
  19108. if( exp>=100 ){
  19109. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  19110. exp %= 100;
  19111. }
  19112. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  19113. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  19114. }
  19115. *bufpt = 0;
  19116. /* The converted number is in buf[] and zero terminated. Output it.
  19117. ** Note that the number is in the usual order, not reversed as with
  19118. ** integer conversions. */
  19119. length = (int)(bufpt-zOut);
  19120. bufpt = zOut;
  19121. /* Special case: Add leading zeros if the flag_zeropad flag is
  19122. ** set and we are not left justified */
  19123. if( flag_zeropad && !flag_leftjustify && length < width){
  19124. int i;
  19125. int nPad = width - length;
  19126. for(i=width; i>=nPad; i--){
  19127. bufpt[i] = bufpt[i-nPad];
  19128. }
  19129. i = prefix!=0;
  19130. while( nPad-- ) bufpt[i++] = '0';
  19131. length = width;
  19132. }
  19133. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  19134. break;
  19135. case etSIZE:
  19136. *(va_arg(ap,int*)) = pAccum->nChar;
  19137. length = width = 0;
  19138. break;
  19139. case etPERCENT:
  19140. buf[0] = '%';
  19141. bufpt = buf;
  19142. length = 1;
  19143. break;
  19144. case etCHARX:
  19145. c = va_arg(ap,int);
  19146. buf[0] = (char)c;
  19147. if( precision>=0 ){
  19148. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  19149. length = precision;
  19150. }else{
  19151. length =1;
  19152. }
  19153. bufpt = buf;
  19154. break;
  19155. case etSTRING:
  19156. case etDYNSTRING:
  19157. bufpt = va_arg(ap,char*);
  19158. if( bufpt==0 ){
  19159. bufpt = "";
  19160. }else if( xtype==etDYNSTRING ){
  19161. zExtra = bufpt;
  19162. }
  19163. if( precision>=0 ){
  19164. for(length=0; length<precision && bufpt[length]; length++){}
  19165. }else{
  19166. length = sqlite3Strlen30(bufpt);
  19167. }
  19168. break;
  19169. case etSQLESCAPE:
  19170. case etSQLESCAPE2:
  19171. case etSQLESCAPE3: {
  19172. int i, j, k, n, isnull;
  19173. int needQuote;
  19174. char ch;
  19175. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  19176. char *escarg = va_arg(ap,char*);
  19177. isnull = escarg==0;
  19178. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  19179. k = precision;
  19180. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  19181. if( ch==q ) n++;
  19182. }
  19183. needQuote = !isnull && xtype==etSQLESCAPE2;
  19184. n += i + 1 + needQuote*2;
  19185. if( n>etBUFSIZE ){
  19186. bufpt = zExtra = sqlite3Malloc( n );
  19187. if( bufpt==0 ){
  19188. pAccum->accError = STRACCUM_NOMEM;
  19189. return;
  19190. }
  19191. }else{
  19192. bufpt = buf;
  19193. }
  19194. j = 0;
  19195. if( needQuote ) bufpt[j++] = q;
  19196. k = i;
  19197. for(i=0; i<k; i++){
  19198. bufpt[j++] = ch = escarg[i];
  19199. if( ch==q ) bufpt[j++] = ch;
  19200. }
  19201. if( needQuote ) bufpt[j++] = q;
  19202. bufpt[j] = 0;
  19203. length = j;
  19204. /* The precision in %q and %Q means how many input characters to
  19205. ** consume, not the length of the output...
  19206. ** if( precision>=0 && precision<length ) length = precision; */
  19207. break;
  19208. }
  19209. case etTOKEN: {
  19210. Token *pToken = va_arg(ap, Token*);
  19211. if( pToken ){
  19212. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  19213. }
  19214. length = width = 0;
  19215. break;
  19216. }
  19217. case etSRCLIST: {
  19218. SrcList *pSrc = va_arg(ap, SrcList*);
  19219. int k = va_arg(ap, int);
  19220. struct SrcList_item *pItem = &pSrc->a[k];
  19221. assert( k>=0 && k<pSrc->nSrc );
  19222. if( pItem->zDatabase ){
  19223. sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
  19224. sqlite3StrAccumAppend(pAccum, ".", 1);
  19225. }
  19226. sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
  19227. length = width = 0;
  19228. break;
  19229. }
  19230. default: {
  19231. assert( xtype==etINVALID );
  19232. return;
  19233. }
  19234. }/* End switch over the format type */
  19235. /*
  19236. ** The text of the conversion is pointed to by "bufpt" and is
  19237. ** "length" characters long. The field width is "width". Do
  19238. ** the output.
  19239. */
  19240. if( !flag_leftjustify ){
  19241. register int nspace;
  19242. nspace = width-length;
  19243. if( nspace>0 ){
  19244. sqlite3AppendSpace(pAccum, nspace);
  19245. }
  19246. }
  19247. if( length>0 ){
  19248. sqlite3StrAccumAppend(pAccum, bufpt, length);
  19249. }
  19250. if( flag_leftjustify ){
  19251. register int nspace;
  19252. nspace = width-length;
  19253. if( nspace>0 ){
  19254. sqlite3AppendSpace(pAccum, nspace);
  19255. }
  19256. }
  19257. sqlite3_free(zExtra);
  19258. }/* End for loop over the format string */
  19259. } /* End of function */
  19260. /*
  19261. ** Append N bytes of text from z to the StrAccum object.
  19262. */
  19263. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  19264. assert( z!=0 || N==0 );
  19265. if( p->accError ){
  19266. testcase(p->accError==STRACCUM_TOOBIG);
  19267. testcase(p->accError==STRACCUM_NOMEM);
  19268. return;
  19269. }
  19270. assert( p->zText!=0 || p->nChar==0 );
  19271. if( N<=0 ){
  19272. if( N==0 || z[0]==0 ) return;
  19273. N = sqlite3Strlen30(z);
  19274. }
  19275. if( p->nChar+N >= p->nAlloc ){
  19276. char *zNew;
  19277. if( !p->useMalloc ){
  19278. p->accError = STRACCUM_TOOBIG;
  19279. N = p->nAlloc - p->nChar - 1;
  19280. if( N<=0 ){
  19281. return;
  19282. }
  19283. }else{
  19284. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  19285. i64 szNew = p->nChar;
  19286. szNew += N + 1;
  19287. if( szNew > p->mxAlloc ){
  19288. sqlite3StrAccumReset(p);
  19289. p->accError = STRACCUM_TOOBIG;
  19290. return;
  19291. }else{
  19292. p->nAlloc = (int)szNew;
  19293. }
  19294. if( p->useMalloc==1 ){
  19295. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  19296. }else{
  19297. zNew = sqlite3_realloc(zOld, p->nAlloc);
  19298. }
  19299. if( zNew ){
  19300. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  19301. p->zText = zNew;
  19302. }else{
  19303. p->accError = STRACCUM_NOMEM;
  19304. sqlite3StrAccumReset(p);
  19305. return;
  19306. }
  19307. }
  19308. }
  19309. assert( p->zText );
  19310. memcpy(&p->zText[p->nChar], z, N);
  19311. p->nChar += N;
  19312. }
  19313. /*
  19314. ** Finish off a string by making sure it is zero-terminated.
  19315. ** Return a pointer to the resulting string. Return a NULL
  19316. ** pointer if any kind of error was encountered.
  19317. */
  19318. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  19319. if( p->zText ){
  19320. p->zText[p->nChar] = 0;
  19321. if( p->useMalloc && p->zText==p->zBase ){
  19322. if( p->useMalloc==1 ){
  19323. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  19324. }else{
  19325. p->zText = sqlite3_malloc(p->nChar+1);
  19326. }
  19327. if( p->zText ){
  19328. memcpy(p->zText, p->zBase, p->nChar+1);
  19329. }else{
  19330. p->accError = STRACCUM_NOMEM;
  19331. }
  19332. }
  19333. }
  19334. return p->zText;
  19335. }
  19336. /*
  19337. ** Reset an StrAccum string. Reclaim all malloced memory.
  19338. */
  19339. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  19340. if( p->zText!=p->zBase ){
  19341. if( p->useMalloc==1 ){
  19342. sqlite3DbFree(p->db, p->zText);
  19343. }else{
  19344. sqlite3_free(p->zText);
  19345. }
  19346. }
  19347. p->zText = 0;
  19348. }
  19349. /*
  19350. ** Initialize a string accumulator
  19351. */
  19352. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  19353. p->zText = p->zBase = zBase;
  19354. p->db = 0;
  19355. p->nChar = 0;
  19356. p->nAlloc = n;
  19357. p->mxAlloc = mx;
  19358. p->useMalloc = 1;
  19359. p->accError = 0;
  19360. }
  19361. /*
  19362. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19363. ** %-conversion extensions.
  19364. */
  19365. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  19366. char *z;
  19367. char zBase[SQLITE_PRINT_BUF_SIZE];
  19368. StrAccum acc;
  19369. assert( db!=0 );
  19370. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  19371. db->aLimit[SQLITE_LIMIT_LENGTH]);
  19372. acc.db = db;
  19373. sqlite3VXPrintf(&acc, 1, zFormat, ap);
  19374. z = sqlite3StrAccumFinish(&acc);
  19375. if( acc.accError==STRACCUM_NOMEM ){
  19376. db->mallocFailed = 1;
  19377. }
  19378. return z;
  19379. }
  19380. /*
  19381. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19382. ** %-conversion extensions.
  19383. */
  19384. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  19385. va_list ap;
  19386. char *z;
  19387. va_start(ap, zFormat);
  19388. z = sqlite3VMPrintf(db, zFormat, ap);
  19389. va_end(ap);
  19390. return z;
  19391. }
  19392. /*
  19393. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  19394. ** the string and before returnning. This routine is intended to be used
  19395. ** to modify an existing string. For example:
  19396. **
  19397. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  19398. **
  19399. */
  19400. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  19401. va_list ap;
  19402. char *z;
  19403. va_start(ap, zFormat);
  19404. z = sqlite3VMPrintf(db, zFormat, ap);
  19405. va_end(ap);
  19406. sqlite3DbFree(db, zStr);
  19407. return z;
  19408. }
  19409. /*
  19410. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  19411. ** %-conversion extensions.
  19412. */
  19413. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  19414. char *z;
  19415. char zBase[SQLITE_PRINT_BUF_SIZE];
  19416. StrAccum acc;
  19417. #ifndef SQLITE_OMIT_AUTOINIT
  19418. if( sqlite3_initialize() ) return 0;
  19419. #endif
  19420. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  19421. acc.useMalloc = 2;
  19422. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19423. z = sqlite3StrAccumFinish(&acc);
  19424. return z;
  19425. }
  19426. /*
  19427. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  19428. ** %-conversion extensions.
  19429. */
  19430. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  19431. va_list ap;
  19432. char *z;
  19433. #ifndef SQLITE_OMIT_AUTOINIT
  19434. if( sqlite3_initialize() ) return 0;
  19435. #endif
  19436. va_start(ap, zFormat);
  19437. z = sqlite3_vmprintf(zFormat, ap);
  19438. va_end(ap);
  19439. return z;
  19440. }
  19441. /*
  19442. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  19443. ** current locale settings. This is important for SQLite because we
  19444. ** are not able to use a "," as the decimal point in place of "." as
  19445. ** specified by some locales.
  19446. **
  19447. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  19448. ** from the snprintf() standard. Unfortunately, it is too late to change
  19449. ** this without breaking compatibility, so we just have to live with the
  19450. ** mistake.
  19451. **
  19452. ** sqlite3_vsnprintf() is the varargs version.
  19453. */
  19454. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  19455. StrAccum acc;
  19456. if( n<=0 ) return zBuf;
  19457. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  19458. acc.useMalloc = 0;
  19459. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19460. return sqlite3StrAccumFinish(&acc);
  19461. }
  19462. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  19463. char *z;
  19464. va_list ap;
  19465. va_start(ap,zFormat);
  19466. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  19467. va_end(ap);
  19468. return z;
  19469. }
  19470. /*
  19471. ** This is the routine that actually formats the sqlite3_log() message.
  19472. ** We house it in a separate routine from sqlite3_log() to avoid using
  19473. ** stack space on small-stack systems when logging is disabled.
  19474. **
  19475. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  19476. ** allocate memory because it might be called while the memory allocator
  19477. ** mutex is held.
  19478. */
  19479. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  19480. StrAccum acc; /* String accumulator */
  19481. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  19482. sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  19483. acc.useMalloc = 0;
  19484. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19485. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  19486. sqlite3StrAccumFinish(&acc));
  19487. }
  19488. /*
  19489. ** Format and write a message to the log if logging is enabled.
  19490. */
  19491. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  19492. va_list ap; /* Vararg list */
  19493. if( sqlite3GlobalConfig.xLog ){
  19494. va_start(ap, zFormat);
  19495. renderLogMsg(iErrCode, zFormat, ap);
  19496. va_end(ap);
  19497. }
  19498. }
  19499. #if defined(SQLITE_DEBUG)
  19500. /*
  19501. ** A version of printf() that understands %lld. Used for debugging.
  19502. ** The printf() built into some versions of windows does not understand %lld
  19503. ** and segfaults if you give it a long long int.
  19504. */
  19505. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  19506. va_list ap;
  19507. StrAccum acc;
  19508. char zBuf[500];
  19509. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  19510. acc.useMalloc = 0;
  19511. va_start(ap,zFormat);
  19512. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19513. va_end(ap);
  19514. sqlite3StrAccumFinish(&acc);
  19515. fprintf(stdout,"%s", zBuf);
  19516. fflush(stdout);
  19517. }
  19518. #endif
  19519. #ifndef SQLITE_OMIT_TRACE
  19520. /*
  19521. ** variable-argument wrapper around sqlite3VXPrintf().
  19522. */
  19523. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  19524. va_list ap;
  19525. va_start(ap,zFormat);
  19526. sqlite3VXPrintf(p, 1, zFormat, ap);
  19527. va_end(ap);
  19528. }
  19529. #endif
  19530. /************** End of printf.c **********************************************/
  19531. /************** Begin file random.c ******************************************/
  19532. /*
  19533. ** 2001 September 15
  19534. **
  19535. ** The author disclaims copyright to this source code. In place of
  19536. ** a legal notice, here is a blessing:
  19537. **
  19538. ** May you do good and not evil.
  19539. ** May you find forgiveness for yourself and forgive others.
  19540. ** May you share freely, never taking more than you give.
  19541. **
  19542. *************************************************************************
  19543. ** This file contains code to implement a pseudo-random number
  19544. ** generator (PRNG) for SQLite.
  19545. **
  19546. ** Random numbers are used by some of the database backends in order
  19547. ** to generate random integer keys for tables or random filenames.
  19548. */
  19549. /* All threads share a single random number generator.
  19550. ** This structure is the current state of the generator.
  19551. */
  19552. static SQLITE_WSD struct sqlite3PrngType {
  19553. unsigned char isInit; /* True if initialized */
  19554. unsigned char i, j; /* State variables */
  19555. unsigned char s[256]; /* State variables */
  19556. } sqlite3Prng;
  19557. /*
  19558. ** Return N random bytes.
  19559. */
  19560. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  19561. unsigned char t;
  19562. unsigned char *zBuf = pBuf;
  19563. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  19564. ** state vector. If writable static data is unsupported on the target,
  19565. ** we have to locate the state vector at run-time. In the more common
  19566. ** case where writable static data is supported, wsdPrng can refer directly
  19567. ** to the "sqlite3Prng" state vector declared above.
  19568. */
  19569. #ifdef SQLITE_OMIT_WSD
  19570. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  19571. # define wsdPrng p[0]
  19572. #else
  19573. # define wsdPrng sqlite3Prng
  19574. #endif
  19575. #if SQLITE_THREADSAFE
  19576. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  19577. sqlite3_mutex_enter(mutex);
  19578. #endif
  19579. /* Initialize the state of the random number generator once,
  19580. ** the first time this routine is called. The seed value does
  19581. ** not need to contain a lot of randomness since we are not
  19582. ** trying to do secure encryption or anything like that...
  19583. **
  19584. ** Nothing in this file or anywhere else in SQLite does any kind of
  19585. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  19586. ** number generator) not as an encryption device.
  19587. */
  19588. if( !wsdPrng.isInit ){
  19589. int i;
  19590. char k[256];
  19591. wsdPrng.j = 0;
  19592. wsdPrng.i = 0;
  19593. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  19594. for(i=0; i<256; i++){
  19595. wsdPrng.s[i] = (u8)i;
  19596. }
  19597. for(i=0; i<256; i++){
  19598. wsdPrng.j += wsdPrng.s[i] + k[i];
  19599. t = wsdPrng.s[wsdPrng.j];
  19600. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  19601. wsdPrng.s[i] = t;
  19602. }
  19603. wsdPrng.isInit = 1;
  19604. }
  19605. while( N-- ){
  19606. wsdPrng.i++;
  19607. t = wsdPrng.s[wsdPrng.i];
  19608. wsdPrng.j += t;
  19609. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  19610. wsdPrng.s[wsdPrng.j] = t;
  19611. t += wsdPrng.s[wsdPrng.i];
  19612. *(zBuf++) = wsdPrng.s[t];
  19613. }
  19614. sqlite3_mutex_leave(mutex);
  19615. }
  19616. #ifndef SQLITE_OMIT_BUILTIN_TEST
  19617. /*
  19618. ** For testing purposes, we sometimes want to preserve the state of
  19619. ** PRNG and restore the PRNG to its saved state at a later time, or
  19620. ** to reset the PRNG to its initial state. These routines accomplish
  19621. ** those tasks.
  19622. **
  19623. ** The sqlite3_test_control() interface calls these routines to
  19624. ** control the PRNG.
  19625. */
  19626. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  19627. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  19628. memcpy(
  19629. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19630. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19631. sizeof(sqlite3Prng)
  19632. );
  19633. }
  19634. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  19635. memcpy(
  19636. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19637. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19638. sizeof(sqlite3Prng)
  19639. );
  19640. }
  19641. SQLITE_PRIVATE void sqlite3PrngResetState(void){
  19642. GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
  19643. }
  19644. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  19645. /************** End of random.c **********************************************/
  19646. /************** Begin file utf.c *********************************************/
  19647. /*
  19648. ** 2004 April 13
  19649. **
  19650. ** The author disclaims copyright to this source code. In place of
  19651. ** a legal notice, here is a blessing:
  19652. **
  19653. ** May you do good and not evil.
  19654. ** May you find forgiveness for yourself and forgive others.
  19655. ** May you share freely, never taking more than you give.
  19656. **
  19657. *************************************************************************
  19658. ** This file contains routines used to translate between UTF-8,
  19659. ** UTF-16, UTF-16BE, and UTF-16LE.
  19660. **
  19661. ** Notes on UTF-8:
  19662. **
  19663. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  19664. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  19665. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  19666. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  19667. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  19668. **
  19669. **
  19670. ** Notes on UTF-16: (with wwww+1==uuuuu)
  19671. **
  19672. ** Word-0 Word-1 Value
  19673. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  19674. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  19675. **
  19676. **
  19677. ** BOM or Byte Order Mark:
  19678. ** 0xff 0xfe little-endian utf-16 follows
  19679. ** 0xfe 0xff big-endian utf-16 follows
  19680. **
  19681. */
  19682. /* #include <assert.h> */
  19683. #ifndef SQLITE_AMALGAMATION
  19684. /*
  19685. ** The following constant value is used by the SQLITE_BIGENDIAN and
  19686. ** SQLITE_LITTLEENDIAN macros.
  19687. */
  19688. SQLITE_PRIVATE const int sqlite3one = 1;
  19689. #endif /* SQLITE_AMALGAMATION */
  19690. /*
  19691. ** This lookup table is used to help decode the first byte of
  19692. ** a multi-byte UTF8 character.
  19693. */
  19694. static const unsigned char sqlite3Utf8Trans1[] = {
  19695. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19696. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  19697. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  19698. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  19699. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19700. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  19701. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19702. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  19703. };
  19704. #define WRITE_UTF8(zOut, c) { \
  19705. if( c<0x00080 ){ \
  19706. *zOut++ = (u8)(c&0xFF); \
  19707. } \
  19708. else if( c<0x00800 ){ \
  19709. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  19710. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19711. } \
  19712. else if( c<0x10000 ){ \
  19713. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  19714. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  19715. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19716. }else{ \
  19717. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  19718. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  19719. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  19720. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19721. } \
  19722. }
  19723. #define WRITE_UTF16LE(zOut, c) { \
  19724. if( c<=0xFFFF ){ \
  19725. *zOut++ = (u8)(c&0x00FF); \
  19726. *zOut++ = (u8)((c>>8)&0x00FF); \
  19727. }else{ \
  19728. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  19729. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  19730. *zOut++ = (u8)(c&0x00FF); \
  19731. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  19732. } \
  19733. }
  19734. #define WRITE_UTF16BE(zOut, c) { \
  19735. if( c<=0xFFFF ){ \
  19736. *zOut++ = (u8)((c>>8)&0x00FF); \
  19737. *zOut++ = (u8)(c&0x00FF); \
  19738. }else{ \
  19739. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  19740. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  19741. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  19742. *zOut++ = (u8)(c&0x00FF); \
  19743. } \
  19744. }
  19745. #define READ_UTF16LE(zIn, TERM, c){ \
  19746. c = (*zIn++); \
  19747. c += ((*zIn++)<<8); \
  19748. if( c>=0xD800 && c<0xE000 && TERM ){ \
  19749. int c2 = (*zIn++); \
  19750. c2 += ((*zIn++)<<8); \
  19751. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  19752. } \
  19753. }
  19754. #define READ_UTF16BE(zIn, TERM, c){ \
  19755. c = ((*zIn++)<<8); \
  19756. c += (*zIn++); \
  19757. if( c>=0xD800 && c<0xE000 && TERM ){ \
  19758. int c2 = ((*zIn++)<<8); \
  19759. c2 += (*zIn++); \
  19760. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  19761. } \
  19762. }
  19763. /*
  19764. ** Translate a single UTF-8 character. Return the unicode value.
  19765. **
  19766. ** During translation, assume that the byte that zTerm points
  19767. ** is a 0x00.
  19768. **
  19769. ** Write a pointer to the next unread byte back into *pzNext.
  19770. **
  19771. ** Notes On Invalid UTF-8:
  19772. **
  19773. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  19774. ** be encoded as a multi-byte character. Any multi-byte character that
  19775. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  19776. **
  19777. ** * This routine never allows a UTF16 surrogate value to be encoded.
  19778. ** If a multi-byte character attempts to encode a value between
  19779. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  19780. **
  19781. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  19782. ** byte of a character are interpreted as single-byte characters
  19783. ** and rendered as themselves even though they are technically
  19784. ** invalid characters.
  19785. **
  19786. ** * This routine accepts an infinite number of different UTF8 encodings
  19787. ** for unicode values 0x80 and greater. It do not change over-length
  19788. ** encodings to 0xfffd as some systems recommend.
  19789. */
  19790. #define READ_UTF8(zIn, zTerm, c) \
  19791. c = *(zIn++); \
  19792. if( c>=0xc0 ){ \
  19793. c = sqlite3Utf8Trans1[c-0xc0]; \
  19794. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  19795. c = (c<<6) + (0x3f & *(zIn++)); \
  19796. } \
  19797. if( c<0x80 \
  19798. || (c&0xFFFFF800)==0xD800 \
  19799. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  19800. }
  19801. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  19802. const unsigned char **pz /* Pointer to string from which to read char */
  19803. ){
  19804. unsigned int c;
  19805. /* Same as READ_UTF8() above but without the zTerm parameter.
  19806. ** For this routine, we assume the UTF8 string is always zero-terminated.
  19807. */
  19808. c = *((*pz)++);
  19809. if( c>=0xc0 ){
  19810. c = sqlite3Utf8Trans1[c-0xc0];
  19811. while( (*(*pz) & 0xc0)==0x80 ){
  19812. c = (c<<6) + (0x3f & *((*pz)++));
  19813. }
  19814. if( c<0x80
  19815. || (c&0xFFFFF800)==0xD800
  19816. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  19817. }
  19818. return c;
  19819. }
  19820. /*
  19821. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  19822. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  19823. */
  19824. /* #define TRANSLATE_TRACE 1 */
  19825. #ifndef SQLITE_OMIT_UTF16
  19826. /*
  19827. ** This routine transforms the internal text encoding used by pMem to
  19828. ** desiredEnc. It is an error if the string is already of the desired
  19829. ** encoding, or if *pMem does not contain a string value.
  19830. */
  19831. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  19832. int len; /* Maximum length of output string in bytes */
  19833. unsigned char *zOut; /* Output buffer */
  19834. unsigned char *zIn; /* Input iterator */
  19835. unsigned char *zTerm; /* End of input */
  19836. unsigned char *z; /* Output iterator */
  19837. unsigned int c;
  19838. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  19839. assert( pMem->flags&MEM_Str );
  19840. assert( pMem->enc!=desiredEnc );
  19841. assert( pMem->enc!=0 );
  19842. assert( pMem->n>=0 );
  19843. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  19844. {
  19845. char zBuf[100];
  19846. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  19847. fprintf(stderr, "INPUT: %s\n", zBuf);
  19848. }
  19849. #endif
  19850. /* If the translation is between UTF-16 little and big endian, then
  19851. ** all that is required is to swap the byte order. This case is handled
  19852. ** differently from the others.
  19853. */
  19854. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  19855. u8 temp;
  19856. int rc;
  19857. rc = sqlite3VdbeMemMakeWriteable(pMem);
  19858. if( rc!=SQLITE_OK ){
  19859. assert( rc==SQLITE_NOMEM );
  19860. return SQLITE_NOMEM;
  19861. }
  19862. zIn = (u8*)pMem->z;
  19863. zTerm = &zIn[pMem->n&~1];
  19864. while( zIn<zTerm ){
  19865. temp = *zIn;
  19866. *zIn = *(zIn+1);
  19867. zIn++;
  19868. *zIn++ = temp;
  19869. }
  19870. pMem->enc = desiredEnc;
  19871. goto translate_out;
  19872. }
  19873. /* Set len to the maximum number of bytes required in the output buffer. */
  19874. if( desiredEnc==SQLITE_UTF8 ){
  19875. /* When converting from UTF-16, the maximum growth results from
  19876. ** translating a 2-byte character to a 4-byte UTF-8 character.
  19877. ** A single byte is required for the output string
  19878. ** nul-terminator.
  19879. */
  19880. pMem->n &= ~1;
  19881. len = pMem->n * 2 + 1;
  19882. }else{
  19883. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  19884. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  19885. ** character. Two bytes are required in the output buffer for the
  19886. ** nul-terminator.
  19887. */
  19888. len = pMem->n * 2 + 2;
  19889. }
  19890. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  19891. ** byte past the end.
  19892. **
  19893. ** Variable zOut is set to point at the output buffer, space obtained
  19894. ** from sqlite3_malloc().
  19895. */
  19896. zIn = (u8*)pMem->z;
  19897. zTerm = &zIn[pMem->n];
  19898. zOut = sqlite3DbMallocRaw(pMem->db, len);
  19899. if( !zOut ){
  19900. return SQLITE_NOMEM;
  19901. }
  19902. z = zOut;
  19903. if( pMem->enc==SQLITE_UTF8 ){
  19904. if( desiredEnc==SQLITE_UTF16LE ){
  19905. /* UTF-8 -> UTF-16 Little-endian */
  19906. while( zIn<zTerm ){
  19907. READ_UTF8(zIn, zTerm, c);
  19908. WRITE_UTF16LE(z, c);
  19909. }
  19910. }else{
  19911. assert( desiredEnc==SQLITE_UTF16BE );
  19912. /* UTF-8 -> UTF-16 Big-endian */
  19913. while( zIn<zTerm ){
  19914. READ_UTF8(zIn, zTerm, c);
  19915. WRITE_UTF16BE(z, c);
  19916. }
  19917. }
  19918. pMem->n = (int)(z - zOut);
  19919. *z++ = 0;
  19920. }else{
  19921. assert( desiredEnc==SQLITE_UTF8 );
  19922. if( pMem->enc==SQLITE_UTF16LE ){
  19923. /* UTF-16 Little-endian -> UTF-8 */
  19924. while( zIn<zTerm ){
  19925. READ_UTF16LE(zIn, zIn<zTerm, c);
  19926. WRITE_UTF8(z, c);
  19927. }
  19928. }else{
  19929. /* UTF-16 Big-endian -> UTF-8 */
  19930. while( zIn<zTerm ){
  19931. READ_UTF16BE(zIn, zIn<zTerm, c);
  19932. WRITE_UTF8(z, c);
  19933. }
  19934. }
  19935. pMem->n = (int)(z - zOut);
  19936. }
  19937. *z = 0;
  19938. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  19939. sqlite3VdbeMemRelease(pMem);
  19940. pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
  19941. pMem->enc = desiredEnc;
  19942. pMem->flags |= (MEM_Term|MEM_Dyn);
  19943. pMem->z = (char*)zOut;
  19944. pMem->zMalloc = pMem->z;
  19945. translate_out:
  19946. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  19947. {
  19948. char zBuf[100];
  19949. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  19950. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  19951. }
  19952. #endif
  19953. return SQLITE_OK;
  19954. }
  19955. /*
  19956. ** This routine checks for a byte-order mark at the beginning of the
  19957. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  19958. ** the encoding of the Mem adjusted. This routine does not do any
  19959. ** byte-swapping, it just sets Mem.enc appropriately.
  19960. **
  19961. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  19962. ** changed by this function.
  19963. */
  19964. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  19965. int rc = SQLITE_OK;
  19966. u8 bom = 0;
  19967. assert( pMem->n>=0 );
  19968. if( pMem->n>1 ){
  19969. u8 b1 = *(u8 *)pMem->z;
  19970. u8 b2 = *(((u8 *)pMem->z) + 1);
  19971. if( b1==0xFE && b2==0xFF ){
  19972. bom = SQLITE_UTF16BE;
  19973. }
  19974. if( b1==0xFF && b2==0xFE ){
  19975. bom = SQLITE_UTF16LE;
  19976. }
  19977. }
  19978. if( bom ){
  19979. rc = sqlite3VdbeMemMakeWriteable(pMem);
  19980. if( rc==SQLITE_OK ){
  19981. pMem->n -= 2;
  19982. memmove(pMem->z, &pMem->z[2], pMem->n);
  19983. pMem->z[pMem->n] = '\0';
  19984. pMem->z[pMem->n+1] = '\0';
  19985. pMem->flags |= MEM_Term;
  19986. pMem->enc = bom;
  19987. }
  19988. }
  19989. return rc;
  19990. }
  19991. #endif /* SQLITE_OMIT_UTF16 */
  19992. /*
  19993. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  19994. ** return the number of unicode characters in pZ up to (but not including)
  19995. ** the first 0x00 byte. If nByte is not less than zero, return the
  19996. ** number of unicode characters in the first nByte of pZ (or up to
  19997. ** the first 0x00, whichever comes first).
  19998. */
  19999. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  20000. int r = 0;
  20001. const u8 *z = (const u8*)zIn;
  20002. const u8 *zTerm;
  20003. if( nByte>=0 ){
  20004. zTerm = &z[nByte];
  20005. }else{
  20006. zTerm = (const u8*)(-1);
  20007. }
  20008. assert( z<=zTerm );
  20009. while( *z!=0 && z<zTerm ){
  20010. SQLITE_SKIP_UTF8(z);
  20011. r++;
  20012. }
  20013. return r;
  20014. }
  20015. /* This test function is not currently used by the automated test-suite.
  20016. ** Hence it is only available in debug builds.
  20017. */
  20018. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  20019. /*
  20020. ** Translate UTF-8 to UTF-8.
  20021. **
  20022. ** This has the effect of making sure that the string is well-formed
  20023. ** UTF-8. Miscoded characters are removed.
  20024. **
  20025. ** The translation is done in-place and aborted if the output
  20026. ** overruns the input.
  20027. */
  20028. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  20029. unsigned char *zOut = zIn;
  20030. unsigned char *zStart = zIn;
  20031. u32 c;
  20032. while( zIn[0] && zOut<=zIn ){
  20033. c = sqlite3Utf8Read((const u8**)&zIn);
  20034. if( c!=0xfffd ){
  20035. WRITE_UTF8(zOut, c);
  20036. }
  20037. }
  20038. *zOut = 0;
  20039. return (int)(zOut - zStart);
  20040. }
  20041. #endif
  20042. #ifndef SQLITE_OMIT_UTF16
  20043. /*
  20044. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  20045. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  20046. ** be freed by the calling function.
  20047. **
  20048. ** NULL is returned if there is an allocation error.
  20049. */
  20050. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  20051. Mem m;
  20052. memset(&m, 0, sizeof(m));
  20053. m.db = db;
  20054. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  20055. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  20056. if( db->mallocFailed ){
  20057. sqlite3VdbeMemRelease(&m);
  20058. m.z = 0;
  20059. }
  20060. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  20061. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  20062. assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
  20063. assert( m.z || db->mallocFailed );
  20064. return m.z;
  20065. }
  20066. /*
  20067. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  20068. ** Return the number of bytes in the first nChar unicode characters
  20069. ** in pZ. nChar must be non-negative.
  20070. */
  20071. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  20072. int c;
  20073. unsigned char const *z = zIn;
  20074. int n = 0;
  20075. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  20076. while( n<nChar ){
  20077. READ_UTF16BE(z, 1, c);
  20078. n++;
  20079. }
  20080. }else{
  20081. while( n<nChar ){
  20082. READ_UTF16LE(z, 1, c);
  20083. n++;
  20084. }
  20085. }
  20086. return (int)(z-(unsigned char const *)zIn);
  20087. }
  20088. #if defined(SQLITE_TEST)
  20089. /*
  20090. ** This routine is called from the TCL test function "translate_selftest".
  20091. ** It checks that the primitives for serializing and deserializing
  20092. ** characters in each encoding are inverses of each other.
  20093. */
  20094. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  20095. unsigned int i, t;
  20096. unsigned char zBuf[20];
  20097. unsigned char *z;
  20098. int n;
  20099. unsigned int c;
  20100. for(i=0; i<0x00110000; i++){
  20101. z = zBuf;
  20102. WRITE_UTF8(z, i);
  20103. n = (int)(z-zBuf);
  20104. assert( n>0 && n<=4 );
  20105. z[0] = 0;
  20106. z = zBuf;
  20107. c = sqlite3Utf8Read((const u8**)&z);
  20108. t = i;
  20109. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  20110. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  20111. assert( c==t );
  20112. assert( (z-zBuf)==n );
  20113. }
  20114. for(i=0; i<0x00110000; i++){
  20115. if( i>=0xD800 && i<0xE000 ) continue;
  20116. z = zBuf;
  20117. WRITE_UTF16LE(z, i);
  20118. n = (int)(z-zBuf);
  20119. assert( n>0 && n<=4 );
  20120. z[0] = 0;
  20121. z = zBuf;
  20122. READ_UTF16LE(z, 1, c);
  20123. assert( c==i );
  20124. assert( (z-zBuf)==n );
  20125. }
  20126. for(i=0; i<0x00110000; i++){
  20127. if( i>=0xD800 && i<0xE000 ) continue;
  20128. z = zBuf;
  20129. WRITE_UTF16BE(z, i);
  20130. n = (int)(z-zBuf);
  20131. assert( n>0 && n<=4 );
  20132. z[0] = 0;
  20133. z = zBuf;
  20134. READ_UTF16BE(z, 1, c);
  20135. assert( c==i );
  20136. assert( (z-zBuf)==n );
  20137. }
  20138. }
  20139. #endif /* SQLITE_TEST */
  20140. #endif /* SQLITE_OMIT_UTF16 */
  20141. /************** End of utf.c *************************************************/
  20142. /************** Begin file util.c ********************************************/
  20143. /*
  20144. ** 2001 September 15
  20145. **
  20146. ** The author disclaims copyright to this source code. In place of
  20147. ** a legal notice, here is a blessing:
  20148. **
  20149. ** May you do good and not evil.
  20150. ** May you find forgiveness for yourself and forgive others.
  20151. ** May you share freely, never taking more than you give.
  20152. **
  20153. *************************************************************************
  20154. ** Utility functions used throughout sqlite.
  20155. **
  20156. ** This file contains functions for allocating memory, comparing
  20157. ** strings, and stuff like that.
  20158. **
  20159. */
  20160. /* #include <stdarg.h> */
  20161. #ifdef SQLITE_HAVE_ISNAN
  20162. # include <math.h>
  20163. #endif
  20164. /*
  20165. ** Routine needed to support the testcase() macro.
  20166. */
  20167. #ifdef SQLITE_COVERAGE_TEST
  20168. SQLITE_PRIVATE void sqlite3Coverage(int x){
  20169. static unsigned dummy = 0;
  20170. dummy += (unsigned)x;
  20171. }
  20172. #endif
  20173. #ifndef SQLITE_OMIT_FLOATING_POINT
  20174. /*
  20175. ** Return true if the floating point value is Not a Number (NaN).
  20176. **
  20177. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  20178. ** Otherwise, we have our own implementation that works on most systems.
  20179. */
  20180. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  20181. int rc; /* The value return */
  20182. #if !defined(SQLITE_HAVE_ISNAN)
  20183. /*
  20184. ** Systems that support the isnan() library function should probably
  20185. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  20186. ** found that many systems do not have a working isnan() function so
  20187. ** this implementation is provided as an alternative.
  20188. **
  20189. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  20190. ** On the other hand, the use of -ffast-math comes with the following
  20191. ** warning:
  20192. **
  20193. ** This option [-ffast-math] should never be turned on by any
  20194. ** -O option since it can result in incorrect output for programs
  20195. ** which depend on an exact implementation of IEEE or ISO
  20196. ** rules/specifications for math functions.
  20197. **
  20198. ** Under MSVC, this NaN test may fail if compiled with a floating-
  20199. ** point precision mode other than /fp:precise. From the MSDN
  20200. ** documentation:
  20201. **
  20202. ** The compiler [with /fp:precise] will properly handle comparisons
  20203. ** involving NaN. For example, x != x evaluates to true if x is NaN
  20204. ** ...
  20205. */
  20206. #ifdef __FAST_MATH__
  20207. # error SQLite will not work correctly with the -ffast-math option of GCC.
  20208. #endif
  20209. volatile double y = x;
  20210. volatile double z = y;
  20211. rc = (y!=z);
  20212. #else /* if defined(SQLITE_HAVE_ISNAN) */
  20213. rc = isnan(x);
  20214. #endif /* SQLITE_HAVE_ISNAN */
  20215. testcase( rc );
  20216. return rc;
  20217. }
  20218. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20219. /*
  20220. ** Compute a string length that is limited to what can be stored in
  20221. ** lower 30 bits of a 32-bit signed integer.
  20222. **
  20223. ** The value returned will never be negative. Nor will it ever be greater
  20224. ** than the actual length of the string. For very long strings (greater
  20225. ** than 1GiB) the value returned might be less than the true string length.
  20226. */
  20227. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  20228. const char *z2 = z;
  20229. if( z==0 ) return 0;
  20230. while( *z2 ){ z2++; }
  20231. return 0x3fffffff & (int)(z2 - z);
  20232. }
  20233. /*
  20234. ** Set the most recent error code and error string for the sqlite
  20235. ** handle "db". The error code is set to "err_code".
  20236. **
  20237. ** If it is not NULL, string zFormat specifies the format of the
  20238. ** error string in the style of the printf functions: The following
  20239. ** format characters are allowed:
  20240. **
  20241. ** %s Insert a string
  20242. ** %z A string that should be freed after use
  20243. ** %d Insert an integer
  20244. ** %T Insert a token
  20245. ** %S Insert the first element of a SrcList
  20246. **
  20247. ** zFormat and any string tokens that follow it are assumed to be
  20248. ** encoded in UTF-8.
  20249. **
  20250. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  20251. ** should be called with err_code set to SQLITE_OK and zFormat set
  20252. ** to NULL.
  20253. */
  20254. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  20255. if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
  20256. db->errCode = err_code;
  20257. if( zFormat ){
  20258. char *z;
  20259. va_list ap;
  20260. va_start(ap, zFormat);
  20261. z = sqlite3VMPrintf(db, zFormat, ap);
  20262. va_end(ap);
  20263. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  20264. }else{
  20265. sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
  20266. }
  20267. }
  20268. }
  20269. /*
  20270. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  20271. ** The following formatting characters are allowed:
  20272. **
  20273. ** %s Insert a string
  20274. ** %z A string that should be freed after use
  20275. ** %d Insert an integer
  20276. ** %T Insert a token
  20277. ** %S Insert the first element of a SrcList
  20278. **
  20279. ** This function should be used to report any error that occurs whilst
  20280. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  20281. ** last thing the sqlite3_prepare() function does is copy the error
  20282. ** stored by this function into the database handle using sqlite3Error().
  20283. ** Function sqlite3Error() should be used during statement execution
  20284. ** (sqlite3_step() etc.).
  20285. */
  20286. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  20287. char *zMsg;
  20288. va_list ap;
  20289. sqlite3 *db = pParse->db;
  20290. va_start(ap, zFormat);
  20291. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  20292. va_end(ap);
  20293. if( db->suppressErr ){
  20294. sqlite3DbFree(db, zMsg);
  20295. }else{
  20296. pParse->nErr++;
  20297. sqlite3DbFree(db, pParse->zErrMsg);
  20298. pParse->zErrMsg = zMsg;
  20299. pParse->rc = SQLITE_ERROR;
  20300. }
  20301. }
  20302. /*
  20303. ** Convert an SQL-style quoted string into a normal string by removing
  20304. ** the quote characters. The conversion is done in-place. If the
  20305. ** input does not begin with a quote character, then this routine
  20306. ** is a no-op.
  20307. **
  20308. ** The input string must be zero-terminated. A new zero-terminator
  20309. ** is added to the dequoted string.
  20310. **
  20311. ** The return value is -1 if no dequoting occurs or the length of the
  20312. ** dequoted string, exclusive of the zero terminator, if dequoting does
  20313. ** occur.
  20314. **
  20315. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  20316. ** brackets from around identifers. For example: "[a-b-c]" becomes
  20317. ** "a-b-c".
  20318. */
  20319. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  20320. char quote;
  20321. int i, j;
  20322. if( z==0 ) return -1;
  20323. quote = z[0];
  20324. switch( quote ){
  20325. case '\'': break;
  20326. case '"': break;
  20327. case '`': break; /* For MySQL compatibility */
  20328. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  20329. default: return -1;
  20330. }
  20331. for(i=1, j=0;; i++){
  20332. assert( z[i] );
  20333. if( z[i]==quote ){
  20334. if( z[i+1]==quote ){
  20335. z[j++] = quote;
  20336. i++;
  20337. }else{
  20338. break;
  20339. }
  20340. }else{
  20341. z[j++] = z[i];
  20342. }
  20343. }
  20344. z[j] = 0;
  20345. return j;
  20346. }
  20347. /* Convenient short-hand */
  20348. #define UpperToLower sqlite3UpperToLower
  20349. /*
  20350. ** Some systems have stricmp(). Others have strcasecmp(). Because
  20351. ** there is no consistency, we will define our own.
  20352. **
  20353. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  20354. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  20355. ** the contents of two buffers containing UTF-8 strings in a
  20356. ** case-independent fashion, using the same definition of "case
  20357. ** independence" that SQLite uses internally when comparing identifiers.
  20358. */
  20359. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  20360. register unsigned char *a, *b;
  20361. a = (unsigned char *)zLeft;
  20362. b = (unsigned char *)zRight;
  20363. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20364. return UpperToLower[*a] - UpperToLower[*b];
  20365. }
  20366. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  20367. register unsigned char *a, *b;
  20368. a = (unsigned char *)zLeft;
  20369. b = (unsigned char *)zRight;
  20370. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20371. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  20372. }
  20373. /*
  20374. ** The string z[] is an text representation of a real number.
  20375. ** Convert this string to a double and write it into *pResult.
  20376. **
  20377. ** The string z[] is length bytes in length (bytes, not characters) and
  20378. ** uses the encoding enc. The string is not necessarily zero-terminated.
  20379. **
  20380. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  20381. ** if the string is empty or contains extraneous text. Valid numbers
  20382. ** are in one of these formats:
  20383. **
  20384. ** [+-]digits[E[+-]digits]
  20385. ** [+-]digits.[digits][E[+-]digits]
  20386. ** [+-].digits[E[+-]digits]
  20387. **
  20388. ** Leading and trailing whitespace is ignored for the purpose of determining
  20389. ** validity.
  20390. **
  20391. ** If some prefix of the input string is a valid number, this routine
  20392. ** returns FALSE but it still converts the prefix and writes the result
  20393. ** into *pResult.
  20394. */
  20395. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  20396. #ifndef SQLITE_OMIT_FLOATING_POINT
  20397. int incr;
  20398. const char *zEnd = z + length;
  20399. /* sign * significand * (10 ^ (esign * exponent)) */
  20400. int sign = 1; /* sign of significand */
  20401. i64 s = 0; /* significand */
  20402. int d = 0; /* adjust exponent for shifting decimal point */
  20403. int esign = 1; /* sign of exponent */
  20404. int e = 0; /* exponent */
  20405. int eValid = 1; /* True exponent is either not used or is well-formed */
  20406. double result;
  20407. int nDigits = 0;
  20408. int nonNum = 0;
  20409. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  20410. *pResult = 0.0; /* Default return value, in case of an error */
  20411. if( enc==SQLITE_UTF8 ){
  20412. incr = 1;
  20413. }else{
  20414. int i;
  20415. incr = 2;
  20416. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  20417. for(i=3-enc; i<length && z[i]==0; i+=2){}
  20418. nonNum = i<length;
  20419. zEnd = z+i+enc-3;
  20420. z += (enc&1);
  20421. }
  20422. /* skip leading spaces */
  20423. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20424. if( z>=zEnd ) return 0;
  20425. /* get sign of significand */
  20426. if( *z=='-' ){
  20427. sign = -1;
  20428. z+=incr;
  20429. }else if( *z=='+' ){
  20430. z+=incr;
  20431. }
  20432. /* skip leading zeroes */
  20433. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  20434. /* copy max significant digits to significand */
  20435. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20436. s = s*10 + (*z - '0');
  20437. z+=incr, nDigits++;
  20438. }
  20439. /* skip non-significant significand digits
  20440. ** (increase exponent by d to shift decimal left) */
  20441. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  20442. if( z>=zEnd ) goto do_atof_calc;
  20443. /* if decimal point is present */
  20444. if( *z=='.' ){
  20445. z+=incr;
  20446. /* copy digits from after decimal to significand
  20447. ** (decrease exponent by d to shift decimal right) */
  20448. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20449. s = s*10 + (*z - '0');
  20450. z+=incr, nDigits++, d--;
  20451. }
  20452. /* skip non-significant digits */
  20453. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  20454. }
  20455. if( z>=zEnd ) goto do_atof_calc;
  20456. /* if exponent is present */
  20457. if( *z=='e' || *z=='E' ){
  20458. z+=incr;
  20459. eValid = 0;
  20460. if( z>=zEnd ) goto do_atof_calc;
  20461. /* get sign of exponent */
  20462. if( *z=='-' ){
  20463. esign = -1;
  20464. z+=incr;
  20465. }else if( *z=='+' ){
  20466. z+=incr;
  20467. }
  20468. /* copy digits to exponent */
  20469. while( z<zEnd && sqlite3Isdigit(*z) ){
  20470. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  20471. z+=incr;
  20472. eValid = 1;
  20473. }
  20474. }
  20475. /* skip trailing spaces */
  20476. if( nDigits && eValid ){
  20477. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20478. }
  20479. do_atof_calc:
  20480. /* adjust exponent by d, and update sign */
  20481. e = (e*esign) + d;
  20482. if( e<0 ) {
  20483. esign = -1;
  20484. e *= -1;
  20485. } else {
  20486. esign = 1;
  20487. }
  20488. /* if 0 significand */
  20489. if( !s ) {
  20490. /* In the IEEE 754 standard, zero is signed.
  20491. ** Add the sign if we've seen at least one digit */
  20492. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  20493. } else {
  20494. /* attempt to reduce exponent */
  20495. if( esign>0 ){
  20496. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  20497. }else{
  20498. while( !(s%10) && e>0 ) e--,s/=10;
  20499. }
  20500. /* adjust the sign of significand */
  20501. s = sign<0 ? -s : s;
  20502. /* if exponent, scale significand as appropriate
  20503. ** and store in result. */
  20504. if( e ){
  20505. LONGDOUBLE_TYPE scale = 1.0;
  20506. /* attempt to handle extremely small/large numbers better */
  20507. if( e>307 && e<342 ){
  20508. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  20509. if( esign<0 ){
  20510. result = s / scale;
  20511. result /= 1.0e+308;
  20512. }else{
  20513. result = s * scale;
  20514. result *= 1.0e+308;
  20515. }
  20516. }else if( e>=342 ){
  20517. if( esign<0 ){
  20518. result = 0.0*s;
  20519. }else{
  20520. result = 1e308*1e308*s; /* Infinity */
  20521. }
  20522. }else{
  20523. /* 1.0e+22 is the largest power of 10 than can be
  20524. ** represented exactly. */
  20525. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  20526. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  20527. if( esign<0 ){
  20528. result = s / scale;
  20529. }else{
  20530. result = s * scale;
  20531. }
  20532. }
  20533. } else {
  20534. result = (double)s;
  20535. }
  20536. }
  20537. /* store the result */
  20538. *pResult = result;
  20539. /* return true if number and no extra non-whitespace chracters after */
  20540. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  20541. #else
  20542. return !sqlite3Atoi64(z, pResult, length, enc);
  20543. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20544. }
  20545. /*
  20546. ** Compare the 19-character string zNum against the text representation
  20547. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  20548. ** if zNum is less than, equal to, or greater than the string.
  20549. ** Note that zNum must contain exactly 19 characters.
  20550. **
  20551. ** Unlike memcmp() this routine is guaranteed to return the difference
  20552. ** in the values of the last digit if the only difference is in the
  20553. ** last digit. So, for example,
  20554. **
  20555. ** compare2pow63("9223372036854775800", 1)
  20556. **
  20557. ** will return -8.
  20558. */
  20559. static int compare2pow63(const char *zNum, int incr){
  20560. int c = 0;
  20561. int i;
  20562. /* 012345678901234567 */
  20563. const char *pow63 = "922337203685477580";
  20564. for(i=0; c==0 && i<18; i++){
  20565. c = (zNum[i*incr]-pow63[i])*10;
  20566. }
  20567. if( c==0 ){
  20568. c = zNum[18*incr] - '8';
  20569. testcase( c==(-1) );
  20570. testcase( c==0 );
  20571. testcase( c==(+1) );
  20572. }
  20573. return c;
  20574. }
  20575. /*
  20576. ** Convert zNum to a 64-bit signed integer.
  20577. **
  20578. ** If the zNum value is representable as a 64-bit twos-complement
  20579. ** integer, then write that value into *pNum and return 0.
  20580. **
  20581. ** If zNum is exactly 9223372036854665808, return 2. This special
  20582. ** case is broken out because while 9223372036854665808 cannot be a
  20583. ** signed 64-bit integer, its negative -9223372036854665808 can be.
  20584. **
  20585. ** If zNum is too big for a 64-bit integer and is not
  20586. ** 9223372036854665808 or if zNum contains any non-numeric text,
  20587. ** then return 1.
  20588. **
  20589. ** length is the number of bytes in the string (bytes, not characters).
  20590. ** The string is not necessarily zero-terminated. The encoding is
  20591. ** given by enc.
  20592. */
  20593. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  20594. int incr;
  20595. u64 u = 0;
  20596. int neg = 0; /* assume positive */
  20597. int i;
  20598. int c = 0;
  20599. int nonNum = 0;
  20600. const char *zStart;
  20601. const char *zEnd = zNum + length;
  20602. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  20603. if( enc==SQLITE_UTF8 ){
  20604. incr = 1;
  20605. }else{
  20606. incr = 2;
  20607. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  20608. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  20609. nonNum = i<length;
  20610. zEnd = zNum+i+enc-3;
  20611. zNum += (enc&1);
  20612. }
  20613. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  20614. if( zNum<zEnd ){
  20615. if( *zNum=='-' ){
  20616. neg = 1;
  20617. zNum+=incr;
  20618. }else if( *zNum=='+' ){
  20619. zNum+=incr;
  20620. }
  20621. }
  20622. zStart = zNum;
  20623. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  20624. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  20625. u = u*10 + c - '0';
  20626. }
  20627. if( u>LARGEST_INT64 ){
  20628. *pNum = SMALLEST_INT64;
  20629. }else if( neg ){
  20630. *pNum = -(i64)u;
  20631. }else{
  20632. *pNum = (i64)u;
  20633. }
  20634. testcase( i==18 );
  20635. testcase( i==19 );
  20636. testcase( i==20 );
  20637. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
  20638. /* zNum is empty or contains non-numeric text or is longer
  20639. ** than 19 digits (thus guaranteeing that it is too large) */
  20640. return 1;
  20641. }else if( i<19*incr ){
  20642. /* Less than 19 digits, so we know that it fits in 64 bits */
  20643. assert( u<=LARGEST_INT64 );
  20644. return 0;
  20645. }else{
  20646. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  20647. c = compare2pow63(zNum, incr);
  20648. if( c<0 ){
  20649. /* zNum is less than 9223372036854775808 so it fits */
  20650. assert( u<=LARGEST_INT64 );
  20651. return 0;
  20652. }else if( c>0 ){
  20653. /* zNum is greater than 9223372036854775808 so it overflows */
  20654. return 1;
  20655. }else{
  20656. /* zNum is exactly 9223372036854775808. Fits if negative. The
  20657. ** special case 2 overflow if positive */
  20658. assert( u-1==LARGEST_INT64 );
  20659. assert( (*pNum)==SMALLEST_INT64 );
  20660. return neg ? 0 : 2;
  20661. }
  20662. }
  20663. }
  20664. /*
  20665. ** If zNum represents an integer that will fit in 32-bits, then set
  20666. ** *pValue to that integer and return true. Otherwise return false.
  20667. **
  20668. ** Any non-numeric characters that following zNum are ignored.
  20669. ** This is different from sqlite3Atoi64() which requires the
  20670. ** input number to be zero-terminated.
  20671. */
  20672. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  20673. sqlite_int64 v = 0;
  20674. int i, c;
  20675. int neg = 0;
  20676. if( zNum[0]=='-' ){
  20677. neg = 1;
  20678. zNum++;
  20679. }else if( zNum[0]=='+' ){
  20680. zNum++;
  20681. }
  20682. while( zNum[0]=='0' ) zNum++;
  20683. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  20684. v = v*10 + c;
  20685. }
  20686. /* The longest decimal representation of a 32 bit integer is 10 digits:
  20687. **
  20688. ** 1234567890
  20689. ** 2^31 -> 2147483648
  20690. */
  20691. testcase( i==10 );
  20692. if( i>10 ){
  20693. return 0;
  20694. }
  20695. testcase( v-neg==2147483647 );
  20696. if( v-neg>2147483647 ){
  20697. return 0;
  20698. }
  20699. if( neg ){
  20700. v = -v;
  20701. }
  20702. *pValue = (int)v;
  20703. return 1;
  20704. }
  20705. /*
  20706. ** Return a 32-bit integer value extracted from a string. If the
  20707. ** string is not an integer, just return 0.
  20708. */
  20709. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  20710. int x = 0;
  20711. if( z ) sqlite3GetInt32(z, &x);
  20712. return x;
  20713. }
  20714. /*
  20715. ** The variable-length integer encoding is as follows:
  20716. **
  20717. ** KEY:
  20718. ** A = 0xxxxxxx 7 bits of data and one flag bit
  20719. ** B = 1xxxxxxx 7 bits of data and one flag bit
  20720. ** C = xxxxxxxx 8 bits of data
  20721. **
  20722. ** 7 bits - A
  20723. ** 14 bits - BA
  20724. ** 21 bits - BBA
  20725. ** 28 bits - BBBA
  20726. ** 35 bits - BBBBA
  20727. ** 42 bits - BBBBBA
  20728. ** 49 bits - BBBBBBA
  20729. ** 56 bits - BBBBBBBA
  20730. ** 64 bits - BBBBBBBBC
  20731. */
  20732. /*
  20733. ** Write a 64-bit variable-length integer to memory starting at p[0].
  20734. ** The length of data write will be between 1 and 9 bytes. The number
  20735. ** of bytes written is returned.
  20736. **
  20737. ** A variable-length integer consists of the lower 7 bits of each byte
  20738. ** for all bytes that have the 8th bit set and one byte with the 8th
  20739. ** bit clear. Except, if we get to the 9th byte, it stores the full
  20740. ** 8 bits and is the last byte.
  20741. */
  20742. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  20743. int i, j, n;
  20744. u8 buf[10];
  20745. if( v & (((u64)0xff000000)<<32) ){
  20746. p[8] = (u8)v;
  20747. v >>= 8;
  20748. for(i=7; i>=0; i--){
  20749. p[i] = (u8)((v & 0x7f) | 0x80);
  20750. v >>= 7;
  20751. }
  20752. return 9;
  20753. }
  20754. n = 0;
  20755. do{
  20756. buf[n++] = (u8)((v & 0x7f) | 0x80);
  20757. v >>= 7;
  20758. }while( v!=0 );
  20759. buf[0] &= 0x7f;
  20760. assert( n<=9 );
  20761. for(i=0, j=n-1; j>=0; j--, i++){
  20762. p[i] = buf[j];
  20763. }
  20764. return n;
  20765. }
  20766. /*
  20767. ** This routine is a faster version of sqlite3PutVarint() that only
  20768. ** works for 32-bit positive integers and which is optimized for
  20769. ** the common case of small integers. A MACRO version, putVarint32,
  20770. ** is provided which inlines the single-byte case. All code should use
  20771. ** the MACRO version as this function assumes the single-byte case has
  20772. ** already been handled.
  20773. */
  20774. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
  20775. #ifndef putVarint32
  20776. if( (v & ~0x7f)==0 ){
  20777. p[0] = v;
  20778. return 1;
  20779. }
  20780. #endif
  20781. if( (v & ~0x3fff)==0 ){
  20782. p[0] = (u8)((v>>7) | 0x80);
  20783. p[1] = (u8)(v & 0x7f);
  20784. return 2;
  20785. }
  20786. return sqlite3PutVarint(p, v);
  20787. }
  20788. /*
  20789. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  20790. ** are defined here rather than simply putting the constant expressions
  20791. ** inline in order to work around bugs in the RVT compiler.
  20792. **
  20793. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  20794. **
  20795. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  20796. */
  20797. #define SLOT_2_0 0x001fc07f
  20798. #define SLOT_4_2_0 0xf01fc07f
  20799. /*
  20800. ** Read a 64-bit variable-length integer from memory starting at p[0].
  20801. ** Return the number of bytes read. The value is stored in *v.
  20802. */
  20803. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  20804. u32 a,b,s;
  20805. a = *p;
  20806. /* a: p0 (unmasked) */
  20807. if (!(a&0x80))
  20808. {
  20809. *v = a;
  20810. return 1;
  20811. }
  20812. p++;
  20813. b = *p;
  20814. /* b: p1 (unmasked) */
  20815. if (!(b&0x80))
  20816. {
  20817. a &= 0x7f;
  20818. a = a<<7;
  20819. a |= b;
  20820. *v = a;
  20821. return 2;
  20822. }
  20823. /* Verify that constants are precomputed correctly */
  20824. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  20825. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  20826. p++;
  20827. a = a<<14;
  20828. a |= *p;
  20829. /* a: p0<<14 | p2 (unmasked) */
  20830. if (!(a&0x80))
  20831. {
  20832. a &= SLOT_2_0;
  20833. b &= 0x7f;
  20834. b = b<<7;
  20835. a |= b;
  20836. *v = a;
  20837. return 3;
  20838. }
  20839. /* CSE1 from below */
  20840. a &= SLOT_2_0;
  20841. p++;
  20842. b = b<<14;
  20843. b |= *p;
  20844. /* b: p1<<14 | p3 (unmasked) */
  20845. if (!(b&0x80))
  20846. {
  20847. b &= SLOT_2_0;
  20848. /* moved CSE1 up */
  20849. /* a &= (0x7f<<14)|(0x7f); */
  20850. a = a<<7;
  20851. a |= b;
  20852. *v = a;
  20853. return 4;
  20854. }
  20855. /* a: p0<<14 | p2 (masked) */
  20856. /* b: p1<<14 | p3 (unmasked) */
  20857. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20858. /* moved CSE1 up */
  20859. /* a &= (0x7f<<14)|(0x7f); */
  20860. b &= SLOT_2_0;
  20861. s = a;
  20862. /* s: p0<<14 | p2 (masked) */
  20863. p++;
  20864. a = a<<14;
  20865. a |= *p;
  20866. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  20867. if (!(a&0x80))
  20868. {
  20869. /* we can skip these cause they were (effectively) done above in calc'ing s */
  20870. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  20871. /* b &= (0x7f<<14)|(0x7f); */
  20872. b = b<<7;
  20873. a |= b;
  20874. s = s>>18;
  20875. *v = ((u64)s)<<32 | a;
  20876. return 5;
  20877. }
  20878. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20879. s = s<<7;
  20880. s |= b;
  20881. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20882. p++;
  20883. b = b<<14;
  20884. b |= *p;
  20885. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  20886. if (!(b&0x80))
  20887. {
  20888. /* we can skip this cause it was (effectively) done above in calc'ing s */
  20889. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  20890. a &= SLOT_2_0;
  20891. a = a<<7;
  20892. a |= b;
  20893. s = s>>18;
  20894. *v = ((u64)s)<<32 | a;
  20895. return 6;
  20896. }
  20897. p++;
  20898. a = a<<14;
  20899. a |= *p;
  20900. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  20901. if (!(a&0x80))
  20902. {
  20903. a &= SLOT_4_2_0;
  20904. b &= SLOT_2_0;
  20905. b = b<<7;
  20906. a |= b;
  20907. s = s>>11;
  20908. *v = ((u64)s)<<32 | a;
  20909. return 7;
  20910. }
  20911. /* CSE2 from below */
  20912. a &= SLOT_2_0;
  20913. p++;
  20914. b = b<<14;
  20915. b |= *p;
  20916. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  20917. if (!(b&0x80))
  20918. {
  20919. b &= SLOT_4_2_0;
  20920. /* moved CSE2 up */
  20921. /* a &= (0x7f<<14)|(0x7f); */
  20922. a = a<<7;
  20923. a |= b;
  20924. s = s>>4;
  20925. *v = ((u64)s)<<32 | a;
  20926. return 8;
  20927. }
  20928. p++;
  20929. a = a<<15;
  20930. a |= *p;
  20931. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  20932. /* moved CSE2 up */
  20933. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  20934. b &= SLOT_2_0;
  20935. b = b<<8;
  20936. a |= b;
  20937. s = s<<4;
  20938. b = p[-4];
  20939. b &= 0x7f;
  20940. b = b>>3;
  20941. s |= b;
  20942. *v = ((u64)s)<<32 | a;
  20943. return 9;
  20944. }
  20945. /*
  20946. ** Read a 32-bit variable-length integer from memory starting at p[0].
  20947. ** Return the number of bytes read. The value is stored in *v.
  20948. **
  20949. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  20950. ** integer, then set *v to 0xffffffff.
  20951. **
  20952. ** A MACRO version, getVarint32, is provided which inlines the
  20953. ** single-byte case. All code should use the MACRO version as
  20954. ** this function assumes the single-byte case has already been handled.
  20955. */
  20956. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  20957. u32 a,b;
  20958. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  20959. ** by the getVarin32() macro */
  20960. a = *p;
  20961. /* a: p0 (unmasked) */
  20962. #ifndef getVarint32
  20963. if (!(a&0x80))
  20964. {
  20965. /* Values between 0 and 127 */
  20966. *v = a;
  20967. return 1;
  20968. }
  20969. #endif
  20970. /* The 2-byte case */
  20971. p++;
  20972. b = *p;
  20973. /* b: p1 (unmasked) */
  20974. if (!(b&0x80))
  20975. {
  20976. /* Values between 128 and 16383 */
  20977. a &= 0x7f;
  20978. a = a<<7;
  20979. *v = a | b;
  20980. return 2;
  20981. }
  20982. /* The 3-byte case */
  20983. p++;
  20984. a = a<<14;
  20985. a |= *p;
  20986. /* a: p0<<14 | p2 (unmasked) */
  20987. if (!(a&0x80))
  20988. {
  20989. /* Values between 16384 and 2097151 */
  20990. a &= (0x7f<<14)|(0x7f);
  20991. b &= 0x7f;
  20992. b = b<<7;
  20993. *v = a | b;
  20994. return 3;
  20995. }
  20996. /* A 32-bit varint is used to store size information in btrees.
  20997. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  20998. ** A 3-byte varint is sufficient, for example, to record the size
  20999. ** of a 1048569-byte BLOB or string.
  21000. **
  21001. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  21002. ** rare larger cases can be handled by the slower 64-bit varint
  21003. ** routine.
  21004. */
  21005. #if 1
  21006. {
  21007. u64 v64;
  21008. u8 n;
  21009. p -= 2;
  21010. n = sqlite3GetVarint(p, &v64);
  21011. assert( n>3 && n<=9 );
  21012. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  21013. *v = 0xffffffff;
  21014. }else{
  21015. *v = (u32)v64;
  21016. }
  21017. return n;
  21018. }
  21019. #else
  21020. /* For following code (kept for historical record only) shows an
  21021. ** unrolling for the 3- and 4-byte varint cases. This code is
  21022. ** slightly faster, but it is also larger and much harder to test.
  21023. */
  21024. p++;
  21025. b = b<<14;
  21026. b |= *p;
  21027. /* b: p1<<14 | p3 (unmasked) */
  21028. if (!(b&0x80))
  21029. {
  21030. /* Values between 2097152 and 268435455 */
  21031. b &= (0x7f<<14)|(0x7f);
  21032. a &= (0x7f<<14)|(0x7f);
  21033. a = a<<7;
  21034. *v = a | b;
  21035. return 4;
  21036. }
  21037. p++;
  21038. a = a<<14;
  21039. a |= *p;
  21040. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  21041. if (!(a&0x80))
  21042. {
  21043. /* Values between 268435456 and 34359738367 */
  21044. a &= SLOT_4_2_0;
  21045. b &= SLOT_4_2_0;
  21046. b = b<<7;
  21047. *v = a | b;
  21048. return 5;
  21049. }
  21050. /* We can only reach this point when reading a corrupt database
  21051. ** file. In that case we are not in any hurry. Use the (relatively
  21052. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  21053. ** value. */
  21054. {
  21055. u64 v64;
  21056. u8 n;
  21057. p -= 4;
  21058. n = sqlite3GetVarint(p, &v64);
  21059. assert( n>5 && n<=9 );
  21060. *v = (u32)v64;
  21061. return n;
  21062. }
  21063. #endif
  21064. }
  21065. /*
  21066. ** Return the number of bytes that will be needed to store the given
  21067. ** 64-bit integer.
  21068. */
  21069. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  21070. int i = 0;
  21071. do{
  21072. i++;
  21073. v >>= 7;
  21074. }while( v!=0 && ALWAYS(i<9) );
  21075. return i;
  21076. }
  21077. /*
  21078. ** Read or write a four-byte big-endian integer value.
  21079. */
  21080. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  21081. return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  21082. }
  21083. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  21084. p[0] = (u8)(v>>24);
  21085. p[1] = (u8)(v>>16);
  21086. p[2] = (u8)(v>>8);
  21087. p[3] = (u8)v;
  21088. }
  21089. /*
  21090. ** Translate a single byte of Hex into an integer.
  21091. ** This routine only works if h really is a valid hexadecimal
  21092. ** character: 0..9a..fA..F
  21093. */
  21094. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  21095. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  21096. #ifdef SQLITE_ASCII
  21097. h += 9*(1&(h>>6));
  21098. #endif
  21099. #ifdef SQLITE_EBCDIC
  21100. h += 9*(1&~(h>>4));
  21101. #endif
  21102. return (u8)(h & 0xf);
  21103. }
  21104. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  21105. /*
  21106. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  21107. ** value. Return a pointer to its binary value. Space to hold the
  21108. ** binary value has been obtained from malloc and must be freed by
  21109. ** the calling routine.
  21110. */
  21111. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  21112. char *zBlob;
  21113. int i;
  21114. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  21115. n--;
  21116. if( zBlob ){
  21117. for(i=0; i<n; i+=2){
  21118. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  21119. }
  21120. zBlob[i/2] = 0;
  21121. }
  21122. return zBlob;
  21123. }
  21124. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  21125. /*
  21126. ** Log an error that is an API call on a connection pointer that should
  21127. ** not have been used. The "type" of connection pointer is given as the
  21128. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  21129. */
  21130. static void logBadConnection(const char *zType){
  21131. sqlite3_log(SQLITE_MISUSE,
  21132. "API call with %s database connection pointer",
  21133. zType
  21134. );
  21135. }
  21136. /*
  21137. ** Check to make sure we have a valid db pointer. This test is not
  21138. ** foolproof but it does provide some measure of protection against
  21139. ** misuse of the interface such as passing in db pointers that are
  21140. ** NULL or which have been previously closed. If this routine returns
  21141. ** 1 it means that the db pointer is valid and 0 if it should not be
  21142. ** dereferenced for any reason. The calling function should invoke
  21143. ** SQLITE_MISUSE immediately.
  21144. **
  21145. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  21146. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  21147. ** open properly and is not fit for general use but which can be
  21148. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  21149. */
  21150. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  21151. u32 magic;
  21152. if( db==0 ){
  21153. logBadConnection("NULL");
  21154. return 0;
  21155. }
  21156. magic = db->magic;
  21157. if( magic!=SQLITE_MAGIC_OPEN ){
  21158. if( sqlite3SafetyCheckSickOrOk(db) ){
  21159. testcase( sqlite3GlobalConfig.xLog!=0 );
  21160. logBadConnection("unopened");
  21161. }
  21162. return 0;
  21163. }else{
  21164. return 1;
  21165. }
  21166. }
  21167. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  21168. u32 magic;
  21169. magic = db->magic;
  21170. if( magic!=SQLITE_MAGIC_SICK &&
  21171. magic!=SQLITE_MAGIC_OPEN &&
  21172. magic!=SQLITE_MAGIC_BUSY ){
  21173. testcase( sqlite3GlobalConfig.xLog!=0 );
  21174. logBadConnection("invalid");
  21175. return 0;
  21176. }else{
  21177. return 1;
  21178. }
  21179. }
  21180. /*
  21181. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  21182. ** the other 64-bit signed integer at *pA and store the result in *pA.
  21183. ** Return 0 on success. Or if the operation would have resulted in an
  21184. ** overflow, leave *pA unchanged and return 1.
  21185. */
  21186. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  21187. i64 iA = *pA;
  21188. testcase( iA==0 ); testcase( iA==1 );
  21189. testcase( iB==-1 ); testcase( iB==0 );
  21190. if( iB>=0 ){
  21191. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  21192. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  21193. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  21194. *pA += iB;
  21195. }else{
  21196. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  21197. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  21198. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  21199. *pA += iB;
  21200. }
  21201. return 0;
  21202. }
  21203. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  21204. testcase( iB==SMALLEST_INT64+1 );
  21205. if( iB==SMALLEST_INT64 ){
  21206. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  21207. if( (*pA)>=0 ) return 1;
  21208. *pA -= iB;
  21209. return 0;
  21210. }else{
  21211. return sqlite3AddInt64(pA, -iB);
  21212. }
  21213. }
  21214. #define TWOPOWER32 (((i64)1)<<32)
  21215. #define TWOPOWER31 (((i64)1)<<31)
  21216. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  21217. i64 iA = *pA;
  21218. i64 iA1, iA0, iB1, iB0, r;
  21219. iA1 = iA/TWOPOWER32;
  21220. iA0 = iA % TWOPOWER32;
  21221. iB1 = iB/TWOPOWER32;
  21222. iB0 = iB % TWOPOWER32;
  21223. if( iA1*iB1 != 0 ) return 1;
  21224. assert( iA1*iB0==0 || iA0*iB1==0 );
  21225. r = iA1*iB0 + iA0*iB1;
  21226. testcase( r==(-TWOPOWER31)-1 );
  21227. testcase( r==(-TWOPOWER31) );
  21228. testcase( r==TWOPOWER31 );
  21229. testcase( r==TWOPOWER31-1 );
  21230. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  21231. r *= TWOPOWER32;
  21232. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  21233. *pA = r;
  21234. return 0;
  21235. }
  21236. /*
  21237. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  21238. ** if the integer has a value of -2147483648, return +2147483647
  21239. */
  21240. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  21241. if( x>=0 ) return x;
  21242. if( x==(int)0x80000000 ) return 0x7fffffff;
  21243. return -x;
  21244. }
  21245. #ifdef SQLITE_ENABLE_8_3_NAMES
  21246. /*
  21247. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  21248. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  21249. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  21250. ** three characters, then shorten the suffix on z[] to be the last three
  21251. ** characters of the original suffix.
  21252. **
  21253. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  21254. ** do the suffix shortening regardless of URI parameter.
  21255. **
  21256. ** Examples:
  21257. **
  21258. ** test.db-journal => test.nal
  21259. ** test.db-wal => test.wal
  21260. ** test.db-shm => test.shm
  21261. ** test.db-mj7f3319fa => test.9fa
  21262. */
  21263. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  21264. #if SQLITE_ENABLE_8_3_NAMES<2
  21265. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  21266. #endif
  21267. {
  21268. int i, sz;
  21269. sz = sqlite3Strlen30(z);
  21270. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  21271. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  21272. }
  21273. }
  21274. #endif
  21275. /*
  21276. ** Find (an approximate) sum of two LogEst values. This computation is
  21277. ** not a simple "+" operator because LogEst is stored as a logarithmic
  21278. ** value.
  21279. **
  21280. */
  21281. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  21282. static const unsigned char x[] = {
  21283. 10, 10, /* 0,1 */
  21284. 9, 9, /* 2,3 */
  21285. 8, 8, /* 4,5 */
  21286. 7, 7, 7, /* 6,7,8 */
  21287. 6, 6, 6, /* 9,10,11 */
  21288. 5, 5, 5, /* 12-14 */
  21289. 4, 4, 4, 4, /* 15-18 */
  21290. 3, 3, 3, 3, 3, 3, /* 19-24 */
  21291. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  21292. };
  21293. if( a>=b ){
  21294. if( a>b+49 ) return a;
  21295. if( a>b+31 ) return a+1;
  21296. return a+x[a-b];
  21297. }else{
  21298. if( b>a+49 ) return b;
  21299. if( b>a+31 ) return b+1;
  21300. return b+x[b-a];
  21301. }
  21302. }
  21303. /*
  21304. ** Convert an integer into a LogEst. In other words, compute a
  21305. ** good approximatation for 10*log2(x).
  21306. */
  21307. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  21308. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  21309. LogEst y = 40;
  21310. if( x<8 ){
  21311. if( x<2 ) return 0;
  21312. while( x<8 ){ y -= 10; x <<= 1; }
  21313. }else{
  21314. while( x>255 ){ y += 40; x >>= 4; }
  21315. while( x>15 ){ y += 10; x >>= 1; }
  21316. }
  21317. return a[x&7] + y - 10;
  21318. }
  21319. #ifndef SQLITE_OMIT_VIRTUALTABLE
  21320. /*
  21321. ** Convert a double into a LogEst
  21322. ** In other words, compute an approximation for 10*log2(x).
  21323. */
  21324. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  21325. u64 a;
  21326. LogEst e;
  21327. assert( sizeof(x)==8 && sizeof(a)==8 );
  21328. if( x<=1 ) return 0;
  21329. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  21330. memcpy(&a, &x, 8);
  21331. e = (a>>52) - 1022;
  21332. return e*10;
  21333. }
  21334. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  21335. /*
  21336. ** Convert a LogEst into an integer.
  21337. */
  21338. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  21339. u64 n;
  21340. if( x<10 ) return 1;
  21341. n = x%10;
  21342. x /= 10;
  21343. if( n>=5 ) n -= 2;
  21344. else if( n>=1 ) n -= 1;
  21345. if( x>=3 ) return (n+8)<<(x-3);
  21346. return (n+8)>>(3-x);
  21347. }
  21348. /************** End of util.c ************************************************/
  21349. /************** Begin file hash.c ********************************************/
  21350. /*
  21351. ** 2001 September 22
  21352. **
  21353. ** The author disclaims copyright to this source code. In place of
  21354. ** a legal notice, here is a blessing:
  21355. **
  21356. ** May you do good and not evil.
  21357. ** May you find forgiveness for yourself and forgive others.
  21358. ** May you share freely, never taking more than you give.
  21359. **
  21360. *************************************************************************
  21361. ** This is the implementation of generic hash-tables
  21362. ** used in SQLite.
  21363. */
  21364. /* #include <assert.h> */
  21365. /* Turn bulk memory into a hash table object by initializing the
  21366. ** fields of the Hash structure.
  21367. **
  21368. ** "pNew" is a pointer to the hash table that is to be initialized.
  21369. */
  21370. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  21371. assert( pNew!=0 );
  21372. pNew->first = 0;
  21373. pNew->count = 0;
  21374. pNew->htsize = 0;
  21375. pNew->ht = 0;
  21376. }
  21377. /* Remove all entries from a hash table. Reclaim all memory.
  21378. ** Call this routine to delete a hash table or to reset a hash table
  21379. ** to the empty state.
  21380. */
  21381. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  21382. HashElem *elem; /* For looping over all elements of the table */
  21383. assert( pH!=0 );
  21384. elem = pH->first;
  21385. pH->first = 0;
  21386. sqlite3_free(pH->ht);
  21387. pH->ht = 0;
  21388. pH->htsize = 0;
  21389. while( elem ){
  21390. HashElem *next_elem = elem->next;
  21391. sqlite3_free(elem);
  21392. elem = next_elem;
  21393. }
  21394. pH->count = 0;
  21395. }
  21396. /*
  21397. ** The hashing function.
  21398. */
  21399. static unsigned int strHash(const char *z, int nKey){
  21400. int h = 0;
  21401. assert( nKey>=0 );
  21402. while( nKey > 0 ){
  21403. h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
  21404. nKey--;
  21405. }
  21406. return h;
  21407. }
  21408. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  21409. ** insert pNew into the pEntry hash bucket.
  21410. */
  21411. static void insertElement(
  21412. Hash *pH, /* The complete hash table */
  21413. struct _ht *pEntry, /* The entry into which pNew is inserted */
  21414. HashElem *pNew /* The element to be inserted */
  21415. ){
  21416. HashElem *pHead; /* First element already in pEntry */
  21417. if( pEntry ){
  21418. pHead = pEntry->count ? pEntry->chain : 0;
  21419. pEntry->count++;
  21420. pEntry->chain = pNew;
  21421. }else{
  21422. pHead = 0;
  21423. }
  21424. if( pHead ){
  21425. pNew->next = pHead;
  21426. pNew->prev = pHead->prev;
  21427. if( pHead->prev ){ pHead->prev->next = pNew; }
  21428. else { pH->first = pNew; }
  21429. pHead->prev = pNew;
  21430. }else{
  21431. pNew->next = pH->first;
  21432. if( pH->first ){ pH->first->prev = pNew; }
  21433. pNew->prev = 0;
  21434. pH->first = pNew;
  21435. }
  21436. }
  21437. /* Resize the hash table so that it cantains "new_size" buckets.
  21438. **
  21439. ** The hash table might fail to resize if sqlite3_malloc() fails or
  21440. ** if the new size is the same as the prior size.
  21441. ** Return TRUE if the resize occurs and false if not.
  21442. */
  21443. static int rehash(Hash *pH, unsigned int new_size){
  21444. struct _ht *new_ht; /* The new hash table */
  21445. HashElem *elem, *next_elem; /* For looping over existing elements */
  21446. #if SQLITE_MALLOC_SOFT_LIMIT>0
  21447. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  21448. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  21449. }
  21450. if( new_size==pH->htsize ) return 0;
  21451. #endif
  21452. /* The inability to allocates space for a larger hash table is
  21453. ** a performance hit but it is not a fatal error. So mark the
  21454. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  21455. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  21456. ** only zeroes the requested number of bytes whereas this module will
  21457. ** use the actual amount of space allocated for the hash table (which
  21458. ** may be larger than the requested amount).
  21459. */
  21460. sqlite3BeginBenignMalloc();
  21461. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  21462. sqlite3EndBenignMalloc();
  21463. if( new_ht==0 ) return 0;
  21464. sqlite3_free(pH->ht);
  21465. pH->ht = new_ht;
  21466. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  21467. memset(new_ht, 0, new_size*sizeof(struct _ht));
  21468. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  21469. unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
  21470. next_elem = elem->next;
  21471. insertElement(pH, &new_ht[h], elem);
  21472. }
  21473. return 1;
  21474. }
  21475. /* This function (for internal use only) locates an element in an
  21476. ** hash table that matches the given key. The hash for this key has
  21477. ** already been computed and is passed as the 4th parameter.
  21478. */
  21479. static HashElem *findElementGivenHash(
  21480. const Hash *pH, /* The pH to be searched */
  21481. const char *pKey, /* The key we are searching for */
  21482. int nKey, /* Bytes in key (not counting zero terminator) */
  21483. unsigned int h /* The hash for this key. */
  21484. ){
  21485. HashElem *elem; /* Used to loop thru the element list */
  21486. int count; /* Number of elements left to test */
  21487. if( pH->ht ){
  21488. struct _ht *pEntry = &pH->ht[h];
  21489. elem = pEntry->chain;
  21490. count = pEntry->count;
  21491. }else{
  21492. elem = pH->first;
  21493. count = pH->count;
  21494. }
  21495. while( count-- && ALWAYS(elem) ){
  21496. if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
  21497. return elem;
  21498. }
  21499. elem = elem->next;
  21500. }
  21501. return 0;
  21502. }
  21503. /* Remove a single entry from the hash table given a pointer to that
  21504. ** element and a hash on the element's key.
  21505. */
  21506. static void removeElementGivenHash(
  21507. Hash *pH, /* The pH containing "elem" */
  21508. HashElem* elem, /* The element to be removed from the pH */
  21509. unsigned int h /* Hash value for the element */
  21510. ){
  21511. struct _ht *pEntry;
  21512. if( elem->prev ){
  21513. elem->prev->next = elem->next;
  21514. }else{
  21515. pH->first = elem->next;
  21516. }
  21517. if( elem->next ){
  21518. elem->next->prev = elem->prev;
  21519. }
  21520. if( pH->ht ){
  21521. pEntry = &pH->ht[h];
  21522. if( pEntry->chain==elem ){
  21523. pEntry->chain = elem->next;
  21524. }
  21525. pEntry->count--;
  21526. assert( pEntry->count>=0 );
  21527. }
  21528. sqlite3_free( elem );
  21529. pH->count--;
  21530. if( pH->count==0 ){
  21531. assert( pH->first==0 );
  21532. assert( pH->count==0 );
  21533. sqlite3HashClear(pH);
  21534. }
  21535. }
  21536. /* Attempt to locate an element of the hash table pH with a key
  21537. ** that matches pKey,nKey. Return the data for this element if it is
  21538. ** found, or NULL if there is no match.
  21539. */
  21540. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
  21541. HashElem *elem; /* The element that matches key */
  21542. unsigned int h; /* A hash on key */
  21543. assert( pH!=0 );
  21544. assert( pKey!=0 );
  21545. assert( nKey>=0 );
  21546. if( pH->ht ){
  21547. h = strHash(pKey, nKey) % pH->htsize;
  21548. }else{
  21549. h = 0;
  21550. }
  21551. elem = findElementGivenHash(pH, pKey, nKey, h);
  21552. return elem ? elem->data : 0;
  21553. }
  21554. /* Insert an element into the hash table pH. The key is pKey,nKey
  21555. ** and the data is "data".
  21556. **
  21557. ** If no element exists with a matching key, then a new
  21558. ** element is created and NULL is returned.
  21559. **
  21560. ** If another element already exists with the same key, then the
  21561. ** new data replaces the old data and the old data is returned.
  21562. ** The key is not copied in this instance. If a malloc fails, then
  21563. ** the new data is returned and the hash table is unchanged.
  21564. **
  21565. ** If the "data" parameter to this function is NULL, then the
  21566. ** element corresponding to "key" is removed from the hash table.
  21567. */
  21568. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
  21569. unsigned int h; /* the hash of the key modulo hash table size */
  21570. HashElem *elem; /* Used to loop thru the element list */
  21571. HashElem *new_elem; /* New element added to the pH */
  21572. assert( pH!=0 );
  21573. assert( pKey!=0 );
  21574. assert( nKey>=0 );
  21575. if( pH->htsize ){
  21576. h = strHash(pKey, nKey) % pH->htsize;
  21577. }else{
  21578. h = 0;
  21579. }
  21580. elem = findElementGivenHash(pH,pKey,nKey,h);
  21581. if( elem ){
  21582. void *old_data = elem->data;
  21583. if( data==0 ){
  21584. removeElementGivenHash(pH,elem,h);
  21585. }else{
  21586. elem->data = data;
  21587. elem->pKey = pKey;
  21588. assert(nKey==elem->nKey);
  21589. }
  21590. return old_data;
  21591. }
  21592. if( data==0 ) return 0;
  21593. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  21594. if( new_elem==0 ) return data;
  21595. new_elem->pKey = pKey;
  21596. new_elem->nKey = nKey;
  21597. new_elem->data = data;
  21598. pH->count++;
  21599. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  21600. if( rehash(pH, pH->count*2) ){
  21601. assert( pH->htsize>0 );
  21602. h = strHash(pKey, nKey) % pH->htsize;
  21603. }
  21604. }
  21605. if( pH->ht ){
  21606. insertElement(pH, &pH->ht[h], new_elem);
  21607. }else{
  21608. insertElement(pH, 0, new_elem);
  21609. }
  21610. return 0;
  21611. }
  21612. /************** End of hash.c ************************************************/
  21613. /************** Begin file opcodes.c *****************************************/
  21614. /* Automatically generated. Do not edit */
  21615. /* See the mkopcodec.awk script for details. */
  21616. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  21617. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  21618. static const char *const azName[] = { "?",
  21619. /* 1 */ "Function",
  21620. /* 2 */ "Savepoint",
  21621. /* 3 */ "AutoCommit",
  21622. /* 4 */ "Transaction",
  21623. /* 5 */ "SorterNext",
  21624. /* 6 */ "Prev",
  21625. /* 7 */ "Next",
  21626. /* 8 */ "AggStep",
  21627. /* 9 */ "Checkpoint",
  21628. /* 10 */ "JournalMode",
  21629. /* 11 */ "Vacuum",
  21630. /* 12 */ "VFilter",
  21631. /* 13 */ "VUpdate",
  21632. /* 14 */ "Goto",
  21633. /* 15 */ "Gosub",
  21634. /* 16 */ "Return",
  21635. /* 17 */ "Yield",
  21636. /* 18 */ "HaltIfNull",
  21637. /* 19 */ "Not",
  21638. /* 20 */ "Halt",
  21639. /* 21 */ "Integer",
  21640. /* 22 */ "Int64",
  21641. /* 23 */ "String",
  21642. /* 24 */ "Null",
  21643. /* 25 */ "Blob",
  21644. /* 26 */ "Variable",
  21645. /* 27 */ "Move",
  21646. /* 28 */ "Copy",
  21647. /* 29 */ "SCopy",
  21648. /* 30 */ "ResultRow",
  21649. /* 31 */ "CollSeq",
  21650. /* 32 */ "AddImm",
  21651. /* 33 */ "MustBeInt",
  21652. /* 34 */ "RealAffinity",
  21653. /* 35 */ "Permutation",
  21654. /* 36 */ "Compare",
  21655. /* 37 */ "Jump",
  21656. /* 38 */ "Once",
  21657. /* 39 */ "If",
  21658. /* 40 */ "IfNot",
  21659. /* 41 */ "Column",
  21660. /* 42 */ "Affinity",
  21661. /* 43 */ "MakeRecord",
  21662. /* 44 */ "Count",
  21663. /* 45 */ "ReadCookie",
  21664. /* 46 */ "SetCookie",
  21665. /* 47 */ "VerifyCookie",
  21666. /* 48 */ "OpenRead",
  21667. /* 49 */ "OpenWrite",
  21668. /* 50 */ "OpenAutoindex",
  21669. /* 51 */ "OpenEphemeral",
  21670. /* 52 */ "SorterOpen",
  21671. /* 53 */ "OpenPseudo",
  21672. /* 54 */ "Close",
  21673. /* 55 */ "SeekLt",
  21674. /* 56 */ "SeekLe",
  21675. /* 57 */ "SeekGe",
  21676. /* 58 */ "SeekGt",
  21677. /* 59 */ "Seek",
  21678. /* 60 */ "NotFound",
  21679. /* 61 */ "Found",
  21680. /* 62 */ "IsUnique",
  21681. /* 63 */ "NotExists",
  21682. /* 64 */ "Sequence",
  21683. /* 65 */ "NewRowid",
  21684. /* 66 */ "Insert",
  21685. /* 67 */ "InsertInt",
  21686. /* 68 */ "Or",
  21687. /* 69 */ "And",
  21688. /* 70 */ "Delete",
  21689. /* 71 */ "ResetCount",
  21690. /* 72 */ "SorterCompare",
  21691. /* 73 */ "IsNull",
  21692. /* 74 */ "NotNull",
  21693. /* 75 */ "Ne",
  21694. /* 76 */ "Eq",
  21695. /* 77 */ "Gt",
  21696. /* 78 */ "Le",
  21697. /* 79 */ "Lt",
  21698. /* 80 */ "Ge",
  21699. /* 81 */ "SorterData",
  21700. /* 82 */ "BitAnd",
  21701. /* 83 */ "BitOr",
  21702. /* 84 */ "ShiftLeft",
  21703. /* 85 */ "ShiftRight",
  21704. /* 86 */ "Add",
  21705. /* 87 */ "Subtract",
  21706. /* 88 */ "Multiply",
  21707. /* 89 */ "Divide",
  21708. /* 90 */ "Remainder",
  21709. /* 91 */ "Concat",
  21710. /* 92 */ "RowKey",
  21711. /* 93 */ "BitNot",
  21712. /* 94 */ "String8",
  21713. /* 95 */ "RowData",
  21714. /* 96 */ "Rowid",
  21715. /* 97 */ "NullRow",
  21716. /* 98 */ "Last",
  21717. /* 99 */ "SorterSort",
  21718. /* 100 */ "Sort",
  21719. /* 101 */ "Rewind",
  21720. /* 102 */ "SorterInsert",
  21721. /* 103 */ "IdxInsert",
  21722. /* 104 */ "IdxDelete",
  21723. /* 105 */ "IdxRowid",
  21724. /* 106 */ "IdxLT",
  21725. /* 107 */ "IdxGE",
  21726. /* 108 */ "Destroy",
  21727. /* 109 */ "Clear",
  21728. /* 110 */ "CreateIndex",
  21729. /* 111 */ "CreateTable",
  21730. /* 112 */ "ParseSchema",
  21731. /* 113 */ "LoadAnalysis",
  21732. /* 114 */ "DropTable",
  21733. /* 115 */ "DropIndex",
  21734. /* 116 */ "DropTrigger",
  21735. /* 117 */ "IntegrityCk",
  21736. /* 118 */ "RowSetAdd",
  21737. /* 119 */ "RowSetRead",
  21738. /* 120 */ "RowSetTest",
  21739. /* 121 */ "Program",
  21740. /* 122 */ "Param",
  21741. /* 123 */ "FkCounter",
  21742. /* 124 */ "FkIfZero",
  21743. /* 125 */ "MemMax",
  21744. /* 126 */ "IfPos",
  21745. /* 127 */ "IfNeg",
  21746. /* 128 */ "IfZero",
  21747. /* 129 */ "AggFinal",
  21748. /* 130 */ "Real",
  21749. /* 131 */ "IncrVacuum",
  21750. /* 132 */ "Expire",
  21751. /* 133 */ "TableLock",
  21752. /* 134 */ "VBegin",
  21753. /* 135 */ "VCreate",
  21754. /* 136 */ "VDestroy",
  21755. /* 137 */ "VOpen",
  21756. /* 138 */ "VColumn",
  21757. /* 139 */ "VNext",
  21758. /* 140 */ "VRename",
  21759. /* 141 */ "ToText",
  21760. /* 142 */ "ToBlob",
  21761. /* 143 */ "ToNumeric",
  21762. /* 144 */ "ToInt",
  21763. /* 145 */ "ToReal",
  21764. /* 146 */ "Pagecount",
  21765. /* 147 */ "MaxPgcnt",
  21766. /* 148 */ "Trace",
  21767. /* 149 */ "Noop",
  21768. /* 150 */ "Explain",
  21769. };
  21770. return azName[i];
  21771. }
  21772. #endif
  21773. /************** End of opcodes.c *********************************************/
  21774. /************** Begin file os_unix.c *****************************************/
  21775. /*
  21776. ** 2004 May 22
  21777. **
  21778. ** The author disclaims copyright to this source code. In place of
  21779. ** a legal notice, here is a blessing:
  21780. **
  21781. ** May you do good and not evil.
  21782. ** May you find forgiveness for yourself and forgive others.
  21783. ** May you share freely, never taking more than you give.
  21784. **
  21785. ******************************************************************************
  21786. **
  21787. ** This file contains the VFS implementation for unix-like operating systems
  21788. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  21789. **
  21790. ** There are actually several different VFS implementations in this file.
  21791. ** The differences are in the way that file locking is done. The default
  21792. ** implementation uses Posix Advisory Locks. Alternative implementations
  21793. ** use flock(), dot-files, various proprietary locking schemas, or simply
  21794. ** skip locking all together.
  21795. **
  21796. ** This source file is organized into divisions where the logic for various
  21797. ** subfunctions is contained within the appropriate division. PLEASE
  21798. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  21799. ** in the correct division and should be clearly labeled.
  21800. **
  21801. ** The layout of divisions is as follows:
  21802. **
  21803. ** * General-purpose declarations and utility functions.
  21804. ** * Unique file ID logic used by VxWorks.
  21805. ** * Various locking primitive implementations (all except proxy locking):
  21806. ** + for Posix Advisory Locks
  21807. ** + for no-op locks
  21808. ** + for dot-file locks
  21809. ** + for flock() locking
  21810. ** + for named semaphore locks (VxWorks only)
  21811. ** + for AFP filesystem locks (MacOSX only)
  21812. ** * sqlite3_file methods not associated with locking.
  21813. ** * Definitions of sqlite3_io_methods objects for all locking
  21814. ** methods plus "finder" functions for each locking method.
  21815. ** * sqlite3_vfs method implementations.
  21816. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  21817. ** * Definitions of sqlite3_vfs objects for all locking methods
  21818. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  21819. */
  21820. #if SQLITE_OS_UNIX /* This file is used on unix only */
  21821. /*
  21822. ** There are various methods for file locking used for concurrency
  21823. ** control:
  21824. **
  21825. ** 1. POSIX locking (the default),
  21826. ** 2. No locking,
  21827. ** 3. Dot-file locking,
  21828. ** 4. flock() locking,
  21829. ** 5. AFP locking (OSX only),
  21830. ** 6. Named POSIX semaphores (VXWorks only),
  21831. ** 7. proxy locking. (OSX only)
  21832. **
  21833. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  21834. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  21835. ** selection of the appropriate locking style based on the filesystem
  21836. ** where the database is located.
  21837. */
  21838. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  21839. # if defined(__APPLE__)
  21840. # define SQLITE_ENABLE_LOCKING_STYLE 1
  21841. # else
  21842. # define SQLITE_ENABLE_LOCKING_STYLE 0
  21843. # endif
  21844. #endif
  21845. /*
  21846. ** Define the OS_VXWORKS pre-processor macro to 1 if building on
  21847. ** vxworks, or 0 otherwise.
  21848. */
  21849. #ifndef OS_VXWORKS
  21850. # if defined(__RTP__) || defined(_WRS_KERNEL)
  21851. # define OS_VXWORKS 1
  21852. # else
  21853. # define OS_VXWORKS 0
  21854. # endif
  21855. #endif
  21856. /*
  21857. ** These #defines should enable >2GB file support on Posix if the
  21858. ** underlying operating system supports it. If the OS lacks
  21859. ** large file support, these should be no-ops.
  21860. **
  21861. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  21862. ** on the compiler command line. This is necessary if you are compiling
  21863. ** on a recent machine (ex: RedHat 7.2) but you want your code to work
  21864. ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
  21865. ** without this option, LFS is enable. But LFS does not exist in the kernel
  21866. ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
  21867. ** portability you should omit LFS.
  21868. **
  21869. ** The previous paragraph was written in 2005. (This paragraph is written
  21870. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  21871. ** you should probably leave LFS enabled. But some embedded platforms might
  21872. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  21873. */
  21874. #ifndef SQLITE_DISABLE_LFS
  21875. # define _LARGE_FILE 1
  21876. # ifndef _FILE_OFFSET_BITS
  21877. # define _FILE_OFFSET_BITS 64
  21878. # endif
  21879. # define _LARGEFILE_SOURCE 1
  21880. #endif
  21881. /*
  21882. ** standard include files.
  21883. */
  21884. #include <sys/types.h>
  21885. #include <sys/stat.h>
  21886. #include <fcntl.h>
  21887. #include <unistd.h>
  21888. /* #include <time.h> */
  21889. #include <sys/time.h>
  21890. #include <errno.h>
  21891. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  21892. #include <sys/mman.h>
  21893. #endif
  21894. #if SQLITE_ENABLE_LOCKING_STYLE
  21895. # include <sys/ioctl.h>
  21896. # if OS_VXWORKS
  21897. # include <semaphore.h>
  21898. # include <limits.h>
  21899. # else
  21900. # include <sys/file.h>
  21901. # include <sys/param.h>
  21902. # endif
  21903. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  21904. #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  21905. # include <sys/mount.h>
  21906. #endif
  21907. #ifdef HAVE_UTIME
  21908. # include <utime.h>
  21909. #endif
  21910. /*
  21911. ** Allowed values of unixFile.fsFlags
  21912. */
  21913. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  21914. /*
  21915. ** If we are to be thread-safe, include the pthreads header and define
  21916. ** the SQLITE_UNIX_THREADS macro.
  21917. */
  21918. #if SQLITE_THREADSAFE
  21919. /* # include <pthread.h> */
  21920. # define SQLITE_UNIX_THREADS 1
  21921. #endif
  21922. /*
  21923. ** Default permissions when creating a new file
  21924. */
  21925. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  21926. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  21927. #endif
  21928. /*
  21929. ** Default permissions when creating auto proxy dir
  21930. */
  21931. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  21932. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  21933. #endif
  21934. /*
  21935. ** Maximum supported path-length.
  21936. */
  21937. #define MAX_PATHNAME 512
  21938. /*
  21939. ** Only set the lastErrno if the error code is a real error and not
  21940. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  21941. */
  21942. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  21943. /* Forward references */
  21944. typedef struct unixShm unixShm; /* Connection shared memory */
  21945. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  21946. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  21947. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  21948. /*
  21949. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  21950. ** cannot be closed immediately. In these cases, instances of the following
  21951. ** structure are used to store the file descriptor while waiting for an
  21952. ** opportunity to either close or reuse it.
  21953. */
  21954. struct UnixUnusedFd {
  21955. int fd; /* File descriptor to close */
  21956. int flags; /* Flags this file descriptor was opened with */
  21957. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  21958. };
  21959. /*
  21960. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  21961. ** VFS implementations.
  21962. */
  21963. typedef struct unixFile unixFile;
  21964. struct unixFile {
  21965. sqlite3_io_methods const *pMethod; /* Always the first entry */
  21966. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  21967. unixInodeInfo *pInode; /* Info about locks on this inode */
  21968. int h; /* The file descriptor */
  21969. unsigned char eFileLock; /* The type of lock held on this fd */
  21970. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  21971. int lastErrno; /* The unix errno from last I/O error */
  21972. void *lockingContext; /* Locking style specific state */
  21973. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  21974. const char *zPath; /* Name of the file */
  21975. unixShm *pShm; /* Shared memory segment information */
  21976. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  21977. #if SQLITE_MAX_MMAP_SIZE>0
  21978. int nFetchOut; /* Number of outstanding xFetch refs */
  21979. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  21980. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  21981. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  21982. void *pMapRegion; /* Memory mapped region */
  21983. #endif
  21984. #ifdef __QNXNTO__
  21985. int sectorSize; /* Device sector size */
  21986. int deviceCharacteristics; /* Precomputed device characteristics */
  21987. #endif
  21988. #if SQLITE_ENABLE_LOCKING_STYLE
  21989. int openFlags; /* The flags specified at open() */
  21990. #endif
  21991. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  21992. unsigned fsFlags; /* cached details from statfs() */
  21993. #endif
  21994. #if OS_VXWORKS
  21995. struct vxworksFileId *pId; /* Unique file ID */
  21996. #endif
  21997. #ifdef SQLITE_DEBUG
  21998. /* The next group of variables are used to track whether or not the
  21999. ** transaction counter in bytes 24-27 of database files are updated
  22000. ** whenever any part of the database changes. An assertion fault will
  22001. ** occur if a file is updated without also updating the transaction
  22002. ** counter. This test is made to avoid new problems similar to the
  22003. ** one described by ticket #3584.
  22004. */
  22005. unsigned char transCntrChng; /* True if the transaction counter changed */
  22006. unsigned char dbUpdate; /* True if any part of database file changed */
  22007. unsigned char inNormalWrite; /* True if in a normal write operation */
  22008. #endif
  22009. #ifdef SQLITE_TEST
  22010. /* In test mode, increase the size of this structure a bit so that
  22011. ** it is larger than the struct CrashFile defined in test6.c.
  22012. */
  22013. char aPadding[32];
  22014. #endif
  22015. };
  22016. /*
  22017. ** Allowed values for the unixFile.ctrlFlags bitmask:
  22018. */
  22019. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  22020. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  22021. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  22022. #ifndef SQLITE_DISABLE_DIRSYNC
  22023. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  22024. #else
  22025. # define UNIXFILE_DIRSYNC 0x00
  22026. #endif
  22027. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  22028. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  22029. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  22030. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  22031. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
  22032. /*
  22033. ** Include code that is common to all os_*.c files
  22034. */
  22035. /************** Include os_common.h in the middle of os_unix.c ***************/
  22036. /************** Begin file os_common.h ***************************************/
  22037. /*
  22038. ** 2004 May 22
  22039. **
  22040. ** The author disclaims copyright to this source code. In place of
  22041. ** a legal notice, here is a blessing:
  22042. **
  22043. ** May you do good and not evil.
  22044. ** May you find forgiveness for yourself and forgive others.
  22045. ** May you share freely, never taking more than you give.
  22046. **
  22047. ******************************************************************************
  22048. **
  22049. ** This file contains macros and a little bit of code that is common to
  22050. ** all of the platform-specific files (os_*.c) and is #included into those
  22051. ** files.
  22052. **
  22053. ** This file should be #included by the os_*.c files only. It is not a
  22054. ** general purpose header file.
  22055. */
  22056. #ifndef _OS_COMMON_H_
  22057. #define _OS_COMMON_H_
  22058. /*
  22059. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  22060. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  22061. ** switch. The following code should catch this problem at compile-time.
  22062. */
  22063. #ifdef MEMORY_DEBUG
  22064. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  22065. #endif
  22066. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22067. # ifndef SQLITE_DEBUG_OS_TRACE
  22068. # define SQLITE_DEBUG_OS_TRACE 0
  22069. # endif
  22070. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  22071. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  22072. #else
  22073. # define OSTRACE(X)
  22074. #endif
  22075. /*
  22076. ** Macros for performance tracing. Normally turned off. Only works
  22077. ** on i486 hardware.
  22078. */
  22079. #ifdef SQLITE_PERFORMANCE_TRACE
  22080. /*
  22081. ** hwtime.h contains inline assembler code for implementing
  22082. ** high-performance timing routines.
  22083. */
  22084. /************** Include hwtime.h in the middle of os_common.h ****************/
  22085. /************** Begin file hwtime.h ******************************************/
  22086. /*
  22087. ** 2008 May 27
  22088. **
  22089. ** The author disclaims copyright to this source code. In place of
  22090. ** a legal notice, here is a blessing:
  22091. **
  22092. ** May you do good and not evil.
  22093. ** May you find forgiveness for yourself and forgive others.
  22094. ** May you share freely, never taking more than you give.
  22095. **
  22096. ******************************************************************************
  22097. **
  22098. ** This file contains inline asm code for retrieving "high-performance"
  22099. ** counters for x86 class CPUs.
  22100. */
  22101. #ifndef _HWTIME_H_
  22102. #define _HWTIME_H_
  22103. /*
  22104. ** The following routine only works on pentium-class (or newer) processors.
  22105. ** It uses the RDTSC opcode to read the cycle count value out of the
  22106. ** processor and returns that value. This can be used for high-res
  22107. ** profiling.
  22108. */
  22109. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  22110. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  22111. #if defined(__GNUC__)
  22112. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22113. unsigned int lo, hi;
  22114. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  22115. return (sqlite_uint64)hi << 32 | lo;
  22116. }
  22117. #elif defined(_MSC_VER)
  22118. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  22119. __asm {
  22120. rdtsc
  22121. ret ; return value at EDX:EAX
  22122. }
  22123. }
  22124. #endif
  22125. #elif (defined(__GNUC__) && defined(__x86_64__))
  22126. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22127. unsigned long val;
  22128. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  22129. return val;
  22130. }
  22131. #elif (defined(__GNUC__) && defined(__ppc__))
  22132. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22133. unsigned long long retval;
  22134. unsigned long junk;
  22135. __asm__ __volatile__ ("\n\
  22136. 1: mftbu %1\n\
  22137. mftb %L0\n\
  22138. mftbu %0\n\
  22139. cmpw %0,%1\n\
  22140. bne 1b"
  22141. : "=r" (retval), "=r" (junk));
  22142. return retval;
  22143. }
  22144. #else
  22145. #error Need implementation of sqlite3Hwtime() for your platform.
  22146. /*
  22147. ** To compile without implementing sqlite3Hwtime() for your platform,
  22148. ** you can remove the above #error and use the following
  22149. ** stub function. You will lose timing support for many
  22150. ** of the debugging and testing utilities, but it should at
  22151. ** least compile and run.
  22152. */
  22153. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  22154. #endif
  22155. #endif /* !defined(_HWTIME_H_) */
  22156. /************** End of hwtime.h **********************************************/
  22157. /************** Continuing where we left off in os_common.h ******************/
  22158. static sqlite_uint64 g_start;
  22159. static sqlite_uint64 g_elapsed;
  22160. #define TIMER_START g_start=sqlite3Hwtime()
  22161. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  22162. #define TIMER_ELAPSED g_elapsed
  22163. #else
  22164. #define TIMER_START
  22165. #define TIMER_END
  22166. #define TIMER_ELAPSED ((sqlite_uint64)0)
  22167. #endif
  22168. /*
  22169. ** If we compile with the SQLITE_TEST macro set, then the following block
  22170. ** of code will give us the ability to simulate a disk I/O error. This
  22171. ** is used for testing the I/O recovery logic.
  22172. */
  22173. #ifdef SQLITE_TEST
  22174. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  22175. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  22176. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  22177. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  22178. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  22179. SQLITE_API int sqlite3_diskfull_pending = 0;
  22180. SQLITE_API int sqlite3_diskfull = 0;
  22181. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  22182. #define SimulateIOError(CODE) \
  22183. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  22184. || sqlite3_io_error_pending-- == 1 ) \
  22185. { local_ioerr(); CODE; }
  22186. static void local_ioerr(){
  22187. IOTRACE(("IOERR\n"));
  22188. sqlite3_io_error_hit++;
  22189. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  22190. }
  22191. #define SimulateDiskfullError(CODE) \
  22192. if( sqlite3_diskfull_pending ){ \
  22193. if( sqlite3_diskfull_pending == 1 ){ \
  22194. local_ioerr(); \
  22195. sqlite3_diskfull = 1; \
  22196. sqlite3_io_error_hit = 1; \
  22197. CODE; \
  22198. }else{ \
  22199. sqlite3_diskfull_pending--; \
  22200. } \
  22201. }
  22202. #else
  22203. #define SimulateIOErrorBenign(X)
  22204. #define SimulateIOError(A)
  22205. #define SimulateDiskfullError(A)
  22206. #endif
  22207. /*
  22208. ** When testing, keep a count of the number of open files.
  22209. */
  22210. #ifdef SQLITE_TEST
  22211. SQLITE_API int sqlite3_open_file_count = 0;
  22212. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  22213. #else
  22214. #define OpenCounter(X)
  22215. #endif
  22216. #endif /* !defined(_OS_COMMON_H_) */
  22217. /************** End of os_common.h *******************************************/
  22218. /************** Continuing where we left off in os_unix.c ********************/
  22219. /*
  22220. ** Define various macros that are missing from some systems.
  22221. */
  22222. #ifndef O_LARGEFILE
  22223. # define O_LARGEFILE 0
  22224. #endif
  22225. #ifdef SQLITE_DISABLE_LFS
  22226. # undef O_LARGEFILE
  22227. # define O_LARGEFILE 0
  22228. #endif
  22229. #ifndef O_NOFOLLOW
  22230. # define O_NOFOLLOW 0
  22231. #endif
  22232. #ifndef O_BINARY
  22233. # define O_BINARY 0
  22234. #endif
  22235. /*
  22236. ** The threadid macro resolves to the thread-id or to 0. Used for
  22237. ** testing and debugging only.
  22238. */
  22239. #if SQLITE_THREADSAFE
  22240. #define threadid pthread_self()
  22241. #else
  22242. #define threadid 0
  22243. #endif
  22244. /*
  22245. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  22246. */
  22247. #if !defined(HAVE_MREMAP)
  22248. # if defined(__linux__) && defined(_GNU_SOURCE)
  22249. # define HAVE_MREMAP 1
  22250. # else
  22251. # define HAVE_MREMAP 0
  22252. # endif
  22253. #endif
  22254. /*
  22255. ** Different Unix systems declare open() in different ways. Same use
  22256. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  22257. ** The difference is important when using a pointer to the function.
  22258. **
  22259. ** The safest way to deal with the problem is to always use this wrapper
  22260. ** which always has the same well-defined interface.
  22261. */
  22262. static int posixOpen(const char *zFile, int flags, int mode){
  22263. return open(zFile, flags, mode);
  22264. }
  22265. /*
  22266. ** On some systems, calls to fchown() will trigger a message in a security
  22267. ** log if they come from non-root processes. So avoid calling fchown() if
  22268. ** we are not running as root.
  22269. */
  22270. static int posixFchown(int fd, uid_t uid, gid_t gid){
  22271. return geteuid() ? 0 : fchown(fd,uid,gid);
  22272. }
  22273. /* Forward reference */
  22274. static int openDirectory(const char*, int*);
  22275. /*
  22276. ** Many system calls are accessed through pointer-to-functions so that
  22277. ** they may be overridden at runtime to facilitate fault injection during
  22278. ** testing and sandboxing. The following array holds the names and pointers
  22279. ** to all overrideable system calls.
  22280. */
  22281. static struct unix_syscall {
  22282. const char *zName; /* Name of the system call */
  22283. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  22284. sqlite3_syscall_ptr pDefault; /* Default value */
  22285. } aSyscall[] = {
  22286. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  22287. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  22288. { "close", (sqlite3_syscall_ptr)close, 0 },
  22289. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  22290. { "access", (sqlite3_syscall_ptr)access, 0 },
  22291. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  22292. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  22293. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  22294. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  22295. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  22296. /*
  22297. ** The DJGPP compiler environment looks mostly like Unix, but it
  22298. ** lacks the fcntl() system call. So redefine fcntl() to be something
  22299. ** that always succeeds. This means that locking does not occur under
  22300. ** DJGPP. But it is DOS - what did you expect?
  22301. */
  22302. #ifdef __DJGPP__
  22303. { "fstat", 0, 0 },
  22304. #define osFstat(a,b,c) 0
  22305. #else
  22306. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  22307. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  22308. #endif
  22309. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  22310. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  22311. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  22312. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  22313. { "read", (sqlite3_syscall_ptr)read, 0 },
  22314. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  22315. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  22316. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  22317. #else
  22318. { "pread", (sqlite3_syscall_ptr)0, 0 },
  22319. #endif
  22320. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  22321. #if defined(USE_PREAD64)
  22322. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  22323. #else
  22324. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  22325. #endif
  22326. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  22327. { "write", (sqlite3_syscall_ptr)write, 0 },
  22328. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  22329. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  22330. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  22331. #else
  22332. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  22333. #endif
  22334. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  22335. aSyscall[12].pCurrent)
  22336. #if defined(USE_PREAD64)
  22337. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  22338. #else
  22339. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  22340. #endif
  22341. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  22342. aSyscall[13].pCurrent)
  22343. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  22344. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  22345. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  22346. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  22347. #else
  22348. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  22349. #endif
  22350. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  22351. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  22352. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  22353. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  22354. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  22355. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  22356. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  22357. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  22358. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  22359. { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
  22360. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  22361. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  22362. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  22363. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
  22364. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  22365. #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
  22366. #if HAVE_MREMAP
  22367. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  22368. #else
  22369. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  22370. #endif
  22371. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
  22372. #endif
  22373. }; /* End of the overrideable system calls */
  22374. /*
  22375. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  22376. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  22377. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  22378. ** system call named zName.
  22379. */
  22380. static int unixSetSystemCall(
  22381. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  22382. const char *zName, /* Name of system call to override */
  22383. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  22384. ){
  22385. unsigned int i;
  22386. int rc = SQLITE_NOTFOUND;
  22387. UNUSED_PARAMETER(pNotUsed);
  22388. if( zName==0 ){
  22389. /* If no zName is given, restore all system calls to their default
  22390. ** settings and return NULL
  22391. */
  22392. rc = SQLITE_OK;
  22393. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22394. if( aSyscall[i].pDefault ){
  22395. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  22396. }
  22397. }
  22398. }else{
  22399. /* If zName is specified, operate on only the one system call
  22400. ** specified.
  22401. */
  22402. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22403. if( strcmp(zName, aSyscall[i].zName)==0 ){
  22404. if( aSyscall[i].pDefault==0 ){
  22405. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  22406. }
  22407. rc = SQLITE_OK;
  22408. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  22409. aSyscall[i].pCurrent = pNewFunc;
  22410. break;
  22411. }
  22412. }
  22413. }
  22414. return rc;
  22415. }
  22416. /*
  22417. ** Return the value of a system call. Return NULL if zName is not a
  22418. ** recognized system call name. NULL is also returned if the system call
  22419. ** is currently undefined.
  22420. */
  22421. static sqlite3_syscall_ptr unixGetSystemCall(
  22422. sqlite3_vfs *pNotUsed,
  22423. const char *zName
  22424. ){
  22425. unsigned int i;
  22426. UNUSED_PARAMETER(pNotUsed);
  22427. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22428. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  22429. }
  22430. return 0;
  22431. }
  22432. /*
  22433. ** Return the name of the first system call after zName. If zName==NULL
  22434. ** then return the name of the first system call. Return NULL if zName
  22435. ** is the last system call or if zName is not the name of a valid
  22436. ** system call.
  22437. */
  22438. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  22439. int i = -1;
  22440. UNUSED_PARAMETER(p);
  22441. if( zName ){
  22442. for(i=0; i<ArraySize(aSyscall)-1; i++){
  22443. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  22444. }
  22445. }
  22446. for(i++; i<ArraySize(aSyscall); i++){
  22447. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  22448. }
  22449. return 0;
  22450. }
  22451. /*
  22452. ** Do not accept any file descriptor less than this value, in order to avoid
  22453. ** opening database file using file descriptors that are commonly used for
  22454. ** standard input, output, and error.
  22455. */
  22456. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  22457. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  22458. #endif
  22459. /*
  22460. ** Invoke open(). Do so multiple times, until it either succeeds or
  22461. ** fails for some reason other than EINTR.
  22462. **
  22463. ** If the file creation mode "m" is 0 then set it to the default for
  22464. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  22465. ** 0644) as modified by the system umask. If m is not 0, then
  22466. ** make the file creation mode be exactly m ignoring the umask.
  22467. **
  22468. ** The m parameter will be non-zero only when creating -wal, -journal,
  22469. ** and -shm files. We want those files to have *exactly* the same
  22470. ** permissions as their original database, unadulterated by the umask.
  22471. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  22472. ** transaction crashes and leaves behind hot journals, then any
  22473. ** process that is able to write to the database will also be able to
  22474. ** recover the hot journals.
  22475. */
  22476. static int robust_open(const char *z, int f, mode_t m){
  22477. int fd;
  22478. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  22479. while(1){
  22480. #if defined(O_CLOEXEC)
  22481. fd = osOpen(z,f|O_CLOEXEC,m2);
  22482. #else
  22483. fd = osOpen(z,f,m2);
  22484. #endif
  22485. if( fd<0 ){
  22486. if( errno==EINTR ) continue;
  22487. break;
  22488. }
  22489. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  22490. osClose(fd);
  22491. sqlite3_log(SQLITE_WARNING,
  22492. "attempt to open \"%s\" as file descriptor %d", z, fd);
  22493. fd = -1;
  22494. if( osOpen("/dev/null", f, m)<0 ) break;
  22495. }
  22496. if( fd>=0 ){
  22497. if( m!=0 ){
  22498. struct stat statbuf;
  22499. if( osFstat(fd, &statbuf)==0
  22500. && statbuf.st_size==0
  22501. && (statbuf.st_mode&0777)!=m
  22502. ){
  22503. osFchmod(fd, m);
  22504. }
  22505. }
  22506. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  22507. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  22508. #endif
  22509. }
  22510. return fd;
  22511. }
  22512. /*
  22513. ** Helper functions to obtain and relinquish the global mutex. The
  22514. ** global mutex is used to protect the unixInodeInfo and
  22515. ** vxworksFileId objects used by this file, all of which may be
  22516. ** shared by multiple threads.
  22517. **
  22518. ** Function unixMutexHeld() is used to assert() that the global mutex
  22519. ** is held when required. This function is only used as part of assert()
  22520. ** statements. e.g.
  22521. **
  22522. ** unixEnterMutex()
  22523. ** assert( unixMutexHeld() );
  22524. ** unixEnterLeave()
  22525. */
  22526. static void unixEnterMutex(void){
  22527. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22528. }
  22529. static void unixLeaveMutex(void){
  22530. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22531. }
  22532. #ifdef SQLITE_DEBUG
  22533. static int unixMutexHeld(void) {
  22534. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22535. }
  22536. #endif
  22537. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22538. /*
  22539. ** Helper function for printing out trace information from debugging
  22540. ** binaries. This returns the string represetation of the supplied
  22541. ** integer lock-type.
  22542. */
  22543. static const char *azFileLock(int eFileLock){
  22544. switch( eFileLock ){
  22545. case NO_LOCK: return "NONE";
  22546. case SHARED_LOCK: return "SHARED";
  22547. case RESERVED_LOCK: return "RESERVED";
  22548. case PENDING_LOCK: return "PENDING";
  22549. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  22550. }
  22551. return "ERROR";
  22552. }
  22553. #endif
  22554. #ifdef SQLITE_LOCK_TRACE
  22555. /*
  22556. ** Print out information about all locking operations.
  22557. **
  22558. ** This routine is used for troubleshooting locks on multithreaded
  22559. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  22560. ** command-line option on the compiler. This code is normally
  22561. ** turned off.
  22562. */
  22563. static int lockTrace(int fd, int op, struct flock *p){
  22564. char *zOpName, *zType;
  22565. int s;
  22566. int savedErrno;
  22567. if( op==F_GETLK ){
  22568. zOpName = "GETLK";
  22569. }else if( op==F_SETLK ){
  22570. zOpName = "SETLK";
  22571. }else{
  22572. s = osFcntl(fd, op, p);
  22573. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  22574. return s;
  22575. }
  22576. if( p->l_type==F_RDLCK ){
  22577. zType = "RDLCK";
  22578. }else if( p->l_type==F_WRLCK ){
  22579. zType = "WRLCK";
  22580. }else if( p->l_type==F_UNLCK ){
  22581. zType = "UNLCK";
  22582. }else{
  22583. assert( 0 );
  22584. }
  22585. assert( p->l_whence==SEEK_SET );
  22586. s = osFcntl(fd, op, p);
  22587. savedErrno = errno;
  22588. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  22589. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  22590. (int)p->l_pid, s);
  22591. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  22592. struct flock l2;
  22593. l2 = *p;
  22594. osFcntl(fd, F_GETLK, &l2);
  22595. if( l2.l_type==F_RDLCK ){
  22596. zType = "RDLCK";
  22597. }else if( l2.l_type==F_WRLCK ){
  22598. zType = "WRLCK";
  22599. }else if( l2.l_type==F_UNLCK ){
  22600. zType = "UNLCK";
  22601. }else{
  22602. assert( 0 );
  22603. }
  22604. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  22605. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  22606. }
  22607. errno = savedErrno;
  22608. return s;
  22609. }
  22610. #undef osFcntl
  22611. #define osFcntl lockTrace
  22612. #endif /* SQLITE_LOCK_TRACE */
  22613. /*
  22614. ** Retry ftruncate() calls that fail due to EINTR
  22615. */
  22616. static int robust_ftruncate(int h, sqlite3_int64 sz){
  22617. int rc;
  22618. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  22619. return rc;
  22620. }
  22621. /*
  22622. ** This routine translates a standard POSIX errno code into something
  22623. ** useful to the clients of the sqlite3 functions. Specifically, it is
  22624. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  22625. ** and a variety of "please close the file descriptor NOW" errors into
  22626. ** SQLITE_IOERR
  22627. **
  22628. ** Errors during initialization of locks, or file system support for locks,
  22629. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  22630. */
  22631. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  22632. switch (posixError) {
  22633. #if 0
  22634. /* At one point this code was not commented out. In theory, this branch
  22635. ** should never be hit, as this function should only be called after
  22636. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  22637. ** the value of errno as the first argument. Since a system call has failed,
  22638. ** errno should be non-zero.
  22639. **
  22640. ** Despite this, if errno really is zero, we still don't want to return
  22641. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  22642. ** propagated back to the caller. Commenting this branch out means errno==0
  22643. ** will be handled by the "default:" case below.
  22644. */
  22645. case 0:
  22646. return SQLITE_OK;
  22647. #endif
  22648. case EAGAIN:
  22649. case ETIMEDOUT:
  22650. case EBUSY:
  22651. case EINTR:
  22652. case ENOLCK:
  22653. /* random NFS retry error, unless during file system support
  22654. * introspection, in which it actually means what it says */
  22655. return SQLITE_BUSY;
  22656. case EACCES:
  22657. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  22658. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  22659. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  22660. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  22661. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  22662. return SQLITE_BUSY;
  22663. }
  22664. /* else fall through */
  22665. case EPERM:
  22666. return SQLITE_PERM;
  22667. /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
  22668. ** this module never makes such a call. And the code in SQLite itself
  22669. ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
  22670. ** this case is also commented out. If the system does set errno to EDEADLK,
  22671. ** the default SQLITE_IOERR_XXX code will be returned. */
  22672. #if 0
  22673. case EDEADLK:
  22674. return SQLITE_IOERR_BLOCKED;
  22675. #endif
  22676. #if EOPNOTSUPP!=ENOTSUP
  22677. case EOPNOTSUPP:
  22678. /* something went terribly awry, unless during file system support
  22679. * introspection, in which it actually means what it says */
  22680. #endif
  22681. #ifdef ENOTSUP
  22682. case ENOTSUP:
  22683. /* invalid fd, unless during file system support introspection, in which
  22684. * it actually means what it says */
  22685. #endif
  22686. case EIO:
  22687. case EBADF:
  22688. case EINVAL:
  22689. case ENOTCONN:
  22690. case ENODEV:
  22691. case ENXIO:
  22692. case ENOENT:
  22693. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  22694. case ESTALE:
  22695. #endif
  22696. case ENOSYS:
  22697. /* these should force the client to close the file and reconnect */
  22698. default:
  22699. return sqliteIOErr;
  22700. }
  22701. }
  22702. /******************************************************************************
  22703. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  22704. **
  22705. ** On most versions of unix, we can get a unique ID for a file by concatenating
  22706. ** the device number and the inode number. But this does not work on VxWorks.
  22707. ** On VxWorks, a unique file id must be based on the canonical filename.
  22708. **
  22709. ** A pointer to an instance of the following structure can be used as a
  22710. ** unique file ID in VxWorks. Each instance of this structure contains
  22711. ** a copy of the canonical filename. There is also a reference count.
  22712. ** The structure is reclaimed when the number of pointers to it drops to
  22713. ** zero.
  22714. **
  22715. ** There are never very many files open at one time and lookups are not
  22716. ** a performance-critical path, so it is sufficient to put these
  22717. ** structures on a linked list.
  22718. */
  22719. struct vxworksFileId {
  22720. struct vxworksFileId *pNext; /* Next in a list of them all */
  22721. int nRef; /* Number of references to this one */
  22722. int nName; /* Length of the zCanonicalName[] string */
  22723. char *zCanonicalName; /* Canonical filename */
  22724. };
  22725. #if OS_VXWORKS
  22726. /*
  22727. ** All unique filenames are held on a linked list headed by this
  22728. ** variable:
  22729. */
  22730. static struct vxworksFileId *vxworksFileList = 0;
  22731. /*
  22732. ** Simplify a filename into its canonical form
  22733. ** by making the following changes:
  22734. **
  22735. ** * removing any trailing and duplicate /
  22736. ** * convert /./ into just /
  22737. ** * convert /A/../ where A is any simple name into just /
  22738. **
  22739. ** Changes are made in-place. Return the new name length.
  22740. **
  22741. ** The original filename is in z[0..n-1]. Return the number of
  22742. ** characters in the simplified name.
  22743. */
  22744. static int vxworksSimplifyName(char *z, int n){
  22745. int i, j;
  22746. while( n>1 && z[n-1]=='/' ){ n--; }
  22747. for(i=j=0; i<n; i++){
  22748. if( z[i]=='/' ){
  22749. if( z[i+1]=='/' ) continue;
  22750. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  22751. i += 1;
  22752. continue;
  22753. }
  22754. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  22755. while( j>0 && z[j-1]!='/' ){ j--; }
  22756. if( j>0 ){ j--; }
  22757. i += 2;
  22758. continue;
  22759. }
  22760. }
  22761. z[j++] = z[i];
  22762. }
  22763. z[j] = 0;
  22764. return j;
  22765. }
  22766. /*
  22767. ** Find a unique file ID for the given absolute pathname. Return
  22768. ** a pointer to the vxworksFileId object. This pointer is the unique
  22769. ** file ID.
  22770. **
  22771. ** The nRef field of the vxworksFileId object is incremented before
  22772. ** the object is returned. A new vxworksFileId object is created
  22773. ** and added to the global list if necessary.
  22774. **
  22775. ** If a memory allocation error occurs, return NULL.
  22776. */
  22777. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  22778. struct vxworksFileId *pNew; /* search key and new file ID */
  22779. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  22780. int n; /* Length of zAbsoluteName string */
  22781. assert( zAbsoluteName[0]=='/' );
  22782. n = (int)strlen(zAbsoluteName);
  22783. pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  22784. if( pNew==0 ) return 0;
  22785. pNew->zCanonicalName = (char*)&pNew[1];
  22786. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  22787. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  22788. /* Search for an existing entry that matching the canonical name.
  22789. ** If found, increment the reference count and return a pointer to
  22790. ** the existing file ID.
  22791. */
  22792. unixEnterMutex();
  22793. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  22794. if( pCandidate->nName==n
  22795. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  22796. ){
  22797. sqlite3_free(pNew);
  22798. pCandidate->nRef++;
  22799. unixLeaveMutex();
  22800. return pCandidate;
  22801. }
  22802. }
  22803. /* No match was found. We will make a new file ID */
  22804. pNew->nRef = 1;
  22805. pNew->nName = n;
  22806. pNew->pNext = vxworksFileList;
  22807. vxworksFileList = pNew;
  22808. unixLeaveMutex();
  22809. return pNew;
  22810. }
  22811. /*
  22812. ** Decrement the reference count on a vxworksFileId object. Free
  22813. ** the object when the reference count reaches zero.
  22814. */
  22815. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  22816. unixEnterMutex();
  22817. assert( pId->nRef>0 );
  22818. pId->nRef--;
  22819. if( pId->nRef==0 ){
  22820. struct vxworksFileId **pp;
  22821. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  22822. assert( *pp==pId );
  22823. *pp = pId->pNext;
  22824. sqlite3_free(pId);
  22825. }
  22826. unixLeaveMutex();
  22827. }
  22828. #endif /* OS_VXWORKS */
  22829. /*************** End of Unique File ID Utility Used By VxWorks ****************
  22830. ******************************************************************************/
  22831. /******************************************************************************
  22832. *************************** Posix Advisory Locking ****************************
  22833. **
  22834. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  22835. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  22836. ** sets or clears a lock, that operation overrides any prior locks set
  22837. ** by the same process. It does not explicitly say so, but this implies
  22838. ** that it overrides locks set by the same process using a different
  22839. ** file descriptor. Consider this test case:
  22840. **
  22841. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  22842. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  22843. **
  22844. ** Suppose ./file1 and ./file2 are really the same file (because
  22845. ** one is a hard or symbolic link to the other) then if you set
  22846. ** an exclusive lock on fd1, then try to get an exclusive lock
  22847. ** on fd2, it works. I would have expected the second lock to
  22848. ** fail since there was already a lock on the file due to fd1.
  22849. ** But not so. Since both locks came from the same process, the
  22850. ** second overrides the first, even though they were on different
  22851. ** file descriptors opened on different file names.
  22852. **
  22853. ** This means that we cannot use POSIX locks to synchronize file access
  22854. ** among competing threads of the same process. POSIX locks will work fine
  22855. ** to synchronize access for threads in separate processes, but not
  22856. ** threads within the same process.
  22857. **
  22858. ** To work around the problem, SQLite has to manage file locks internally
  22859. ** on its own. Whenever a new database is opened, we have to find the
  22860. ** specific inode of the database file (the inode is determined by the
  22861. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  22862. ** and check for locks already existing on that inode. When locks are
  22863. ** created or removed, we have to look at our own internal record of the
  22864. ** locks to see if another thread has previously set a lock on that same
  22865. ** inode.
  22866. **
  22867. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  22868. ** For VxWorks, we have to use the alternative unique ID system based on
  22869. ** canonical filename and implemented in the previous division.)
  22870. **
  22871. ** The sqlite3_file structure for POSIX is no longer just an integer file
  22872. ** descriptor. It is now a structure that holds the integer file
  22873. ** descriptor and a pointer to a structure that describes the internal
  22874. ** locks on the corresponding inode. There is one locking structure
  22875. ** per inode, so if the same inode is opened twice, both unixFile structures
  22876. ** point to the same locking structure. The locking structure keeps
  22877. ** a reference count (so we will know when to delete it) and a "cnt"
  22878. ** field that tells us its internal lock status. cnt==0 means the
  22879. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  22880. ** cnt>0 means there are cnt shared locks on the file.
  22881. **
  22882. ** Any attempt to lock or unlock a file first checks the locking
  22883. ** structure. The fcntl() system call is only invoked to set a
  22884. ** POSIX lock if the internal lock structure transitions between
  22885. ** a locked and an unlocked state.
  22886. **
  22887. ** But wait: there are yet more problems with POSIX advisory locks.
  22888. **
  22889. ** If you close a file descriptor that points to a file that has locks,
  22890. ** all locks on that file that are owned by the current process are
  22891. ** released. To work around this problem, each unixInodeInfo object
  22892. ** maintains a count of the number of pending locks on tha inode.
  22893. ** When an attempt is made to close an unixFile, if there are
  22894. ** other unixFile open on the same inode that are holding locks, the call
  22895. ** to close() the file descriptor is deferred until all of the locks clear.
  22896. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  22897. ** be closed and that list is walked (and cleared) when the last lock
  22898. ** clears.
  22899. **
  22900. ** Yet another problem: LinuxThreads do not play well with posix locks.
  22901. **
  22902. ** Many older versions of linux use the LinuxThreads library which is
  22903. ** not posix compliant. Under LinuxThreads, a lock created by thread
  22904. ** A cannot be modified or overridden by a different thread B.
  22905. ** Only thread A can modify the lock. Locking behavior is correct
  22906. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  22907. ** on linux - with NPTL a lock created by thread A can override locks
  22908. ** in thread B. But there is no way to know at compile-time which
  22909. ** threading library is being used. So there is no way to know at
  22910. ** compile-time whether or not thread A can override locks on thread B.
  22911. ** One has to do a run-time check to discover the behavior of the
  22912. ** current process.
  22913. **
  22914. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  22915. ** was dropped beginning with version 3.7.0. SQLite will still work with
  22916. ** LinuxThreads provided that (1) there is no more than one connection
  22917. ** per database file in the same process and (2) database connections
  22918. ** do not move across threads.
  22919. */
  22920. /*
  22921. ** An instance of the following structure serves as the key used
  22922. ** to locate a particular unixInodeInfo object.
  22923. */
  22924. struct unixFileId {
  22925. dev_t dev; /* Device number */
  22926. #if OS_VXWORKS
  22927. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  22928. #else
  22929. ino_t ino; /* Inode number */
  22930. #endif
  22931. };
  22932. /*
  22933. ** An instance of the following structure is allocated for each open
  22934. ** inode. Or, on LinuxThreads, there is one of these structures for
  22935. ** each inode opened by each thread.
  22936. **
  22937. ** A single inode can have multiple file descriptors, so each unixFile
  22938. ** structure contains a pointer to an instance of this object and this
  22939. ** object keeps a count of the number of unixFile pointing to it.
  22940. */
  22941. struct unixInodeInfo {
  22942. struct unixFileId fileId; /* The lookup key */
  22943. int nShared; /* Number of SHARED locks held */
  22944. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  22945. unsigned char bProcessLock; /* An exclusive process lock is held */
  22946. int nRef; /* Number of pointers to this structure */
  22947. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  22948. int nLock; /* Number of outstanding file locks */
  22949. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  22950. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  22951. unixInodeInfo *pPrev; /* .... doubly linked */
  22952. #if SQLITE_ENABLE_LOCKING_STYLE
  22953. unsigned long long sharedByte; /* for AFP simulated shared lock */
  22954. #endif
  22955. #if OS_VXWORKS
  22956. sem_t *pSem; /* Named POSIX semaphore */
  22957. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  22958. #endif
  22959. };
  22960. /*
  22961. ** A lists of all unixInodeInfo objects.
  22962. */
  22963. static unixInodeInfo *inodeList = 0;
  22964. /*
  22965. **
  22966. ** This function - unixLogError_x(), is only ever called via the macro
  22967. ** unixLogError().
  22968. **
  22969. ** It is invoked after an error occurs in an OS function and errno has been
  22970. ** set. It logs a message using sqlite3_log() containing the current value of
  22971. ** errno and, if possible, the human-readable equivalent from strerror() or
  22972. ** strerror_r().
  22973. **
  22974. ** The first argument passed to the macro should be the error code that
  22975. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  22976. ** The two subsequent arguments should be the name of the OS function that
  22977. ** failed (e.g. "unlink", "open") and the associated file-system path,
  22978. ** if any.
  22979. */
  22980. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  22981. static int unixLogErrorAtLine(
  22982. int errcode, /* SQLite error code */
  22983. const char *zFunc, /* Name of OS function that failed */
  22984. const char *zPath, /* File path associated with error */
  22985. int iLine /* Source line number where error occurred */
  22986. ){
  22987. char *zErr; /* Message from strerror() or equivalent */
  22988. int iErrno = errno; /* Saved syscall error number */
  22989. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  22990. ** the strerror() function to obtain the human-readable error message
  22991. ** equivalent to errno. Otherwise, use strerror_r().
  22992. */
  22993. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  22994. char aErr[80];
  22995. memset(aErr, 0, sizeof(aErr));
  22996. zErr = aErr;
  22997. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  22998. ** assume that the system provides the GNU version of strerror_r() that
  22999. ** returns a pointer to a buffer containing the error message. That pointer
  23000. ** may point to aErr[], or it may point to some static storage somewhere.
  23001. ** Otherwise, assume that the system provides the POSIX version of
  23002. ** strerror_r(), which always writes an error message into aErr[].
  23003. **
  23004. ** If the code incorrectly assumes that it is the POSIX version that is
  23005. ** available, the error message will often be an empty string. Not a
  23006. ** huge problem. Incorrectly concluding that the GNU version is available
  23007. ** could lead to a segfault though.
  23008. */
  23009. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  23010. zErr =
  23011. # endif
  23012. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  23013. #elif SQLITE_THREADSAFE
  23014. /* This is a threadsafe build, but strerror_r() is not available. */
  23015. zErr = "";
  23016. #else
  23017. /* Non-threadsafe build, use strerror(). */
  23018. zErr = strerror(iErrno);
  23019. #endif
  23020. if( zPath==0 ) zPath = "";
  23021. sqlite3_log(errcode,
  23022. "os_unix.c:%d: (%d) %s(%s) - %s",
  23023. iLine, iErrno, zFunc, zPath, zErr
  23024. );
  23025. return errcode;
  23026. }
  23027. /*
  23028. ** Close a file descriptor.
  23029. **
  23030. ** We assume that close() almost always works, since it is only in a
  23031. ** very sick application or on a very sick platform that it might fail.
  23032. ** If it does fail, simply leak the file descriptor, but do log the
  23033. ** error.
  23034. **
  23035. ** Note that it is not safe to retry close() after EINTR since the
  23036. ** file descriptor might have already been reused by another thread.
  23037. ** So we don't even try to recover from an EINTR. Just log the error
  23038. ** and move on.
  23039. */
  23040. static void robust_close(unixFile *pFile, int h, int lineno){
  23041. if( osClose(h) ){
  23042. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  23043. pFile ? pFile->zPath : 0, lineno);
  23044. }
  23045. }
  23046. /*
  23047. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  23048. */
  23049. static void closePendingFds(unixFile *pFile){
  23050. unixInodeInfo *pInode = pFile->pInode;
  23051. UnixUnusedFd *p;
  23052. UnixUnusedFd *pNext;
  23053. for(p=pInode->pUnused; p; p=pNext){
  23054. pNext = p->pNext;
  23055. robust_close(pFile, p->fd, __LINE__);
  23056. sqlite3_free(p);
  23057. }
  23058. pInode->pUnused = 0;
  23059. }
  23060. /*
  23061. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  23062. **
  23063. ** The mutex entered using the unixEnterMutex() function must be held
  23064. ** when this function is called.
  23065. */
  23066. static void releaseInodeInfo(unixFile *pFile){
  23067. unixInodeInfo *pInode = pFile->pInode;
  23068. assert( unixMutexHeld() );
  23069. if( ALWAYS(pInode) ){
  23070. pInode->nRef--;
  23071. if( pInode->nRef==0 ){
  23072. assert( pInode->pShmNode==0 );
  23073. closePendingFds(pFile);
  23074. if( pInode->pPrev ){
  23075. assert( pInode->pPrev->pNext==pInode );
  23076. pInode->pPrev->pNext = pInode->pNext;
  23077. }else{
  23078. assert( inodeList==pInode );
  23079. inodeList = pInode->pNext;
  23080. }
  23081. if( pInode->pNext ){
  23082. assert( pInode->pNext->pPrev==pInode );
  23083. pInode->pNext->pPrev = pInode->pPrev;
  23084. }
  23085. sqlite3_free(pInode);
  23086. }
  23087. }
  23088. }
  23089. /*
  23090. ** Given a file descriptor, locate the unixInodeInfo object that
  23091. ** describes that file descriptor. Create a new one if necessary. The
  23092. ** return value might be uninitialized if an error occurs.
  23093. **
  23094. ** The mutex entered using the unixEnterMutex() function must be held
  23095. ** when this function is called.
  23096. **
  23097. ** Return an appropriate error code.
  23098. */
  23099. static int findInodeInfo(
  23100. unixFile *pFile, /* Unix file with file desc used in the key */
  23101. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  23102. ){
  23103. int rc; /* System call return code */
  23104. int fd; /* The file descriptor for pFile */
  23105. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  23106. struct stat statbuf; /* Low-level file information */
  23107. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  23108. assert( unixMutexHeld() );
  23109. /* Get low-level information about the file that we can used to
  23110. ** create a unique name for the file.
  23111. */
  23112. fd = pFile->h;
  23113. rc = osFstat(fd, &statbuf);
  23114. if( rc!=0 ){
  23115. pFile->lastErrno = errno;
  23116. #ifdef EOVERFLOW
  23117. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  23118. #endif
  23119. return SQLITE_IOERR;
  23120. }
  23121. #ifdef __APPLE__
  23122. /* On OS X on an msdos filesystem, the inode number is reported
  23123. ** incorrectly for zero-size files. See ticket #3260. To work
  23124. ** around this problem (we consider it a bug in OS X, not SQLite)
  23125. ** we always increase the file size to 1 by writing a single byte
  23126. ** prior to accessing the inode number. The one byte written is
  23127. ** an ASCII 'S' character which also happens to be the first byte
  23128. ** in the header of every SQLite database. In this way, if there
  23129. ** is a race condition such that another thread has already populated
  23130. ** the first page of the database, no damage is done.
  23131. */
  23132. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  23133. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  23134. if( rc!=1 ){
  23135. pFile->lastErrno = errno;
  23136. return SQLITE_IOERR;
  23137. }
  23138. rc = osFstat(fd, &statbuf);
  23139. if( rc!=0 ){
  23140. pFile->lastErrno = errno;
  23141. return SQLITE_IOERR;
  23142. }
  23143. }
  23144. #endif
  23145. memset(&fileId, 0, sizeof(fileId));
  23146. fileId.dev = statbuf.st_dev;
  23147. #if OS_VXWORKS
  23148. fileId.pId = pFile->pId;
  23149. #else
  23150. fileId.ino = statbuf.st_ino;
  23151. #endif
  23152. pInode = inodeList;
  23153. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  23154. pInode = pInode->pNext;
  23155. }
  23156. if( pInode==0 ){
  23157. pInode = sqlite3_malloc( sizeof(*pInode) );
  23158. if( pInode==0 ){
  23159. return SQLITE_NOMEM;
  23160. }
  23161. memset(pInode, 0, sizeof(*pInode));
  23162. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  23163. pInode->nRef = 1;
  23164. pInode->pNext = inodeList;
  23165. pInode->pPrev = 0;
  23166. if( inodeList ) inodeList->pPrev = pInode;
  23167. inodeList = pInode;
  23168. }else{
  23169. pInode->nRef++;
  23170. }
  23171. *ppInode = pInode;
  23172. return SQLITE_OK;
  23173. }
  23174. /*
  23175. ** Check a unixFile that is a database. Verify the following:
  23176. **
  23177. ** (1) There is exactly one hard link on the file
  23178. ** (2) The file is not a symbolic link
  23179. ** (3) The file has not been renamed or unlinked
  23180. **
  23181. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  23182. */
  23183. static void verifyDbFile(unixFile *pFile){
  23184. struct stat buf;
  23185. int rc;
  23186. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  23187. /* One or more of the following warnings have already been issued. Do not
  23188. ** repeat them so as not to clutter the error log */
  23189. return;
  23190. }
  23191. rc = osFstat(pFile->h, &buf);
  23192. if( rc!=0 ){
  23193. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  23194. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23195. return;
  23196. }
  23197. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  23198. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  23199. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23200. return;
  23201. }
  23202. if( buf.st_nlink>1 ){
  23203. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  23204. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23205. return;
  23206. }
  23207. if( pFile->pInode!=0
  23208. && ((rc = osStat(pFile->zPath, &buf))!=0
  23209. || buf.st_ino!=pFile->pInode->fileId.ino)
  23210. ){
  23211. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  23212. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23213. return;
  23214. }
  23215. }
  23216. /*
  23217. ** This routine checks if there is a RESERVED lock held on the specified
  23218. ** file by this or any other process. If such a lock is held, set *pResOut
  23219. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  23220. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  23221. */
  23222. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  23223. int rc = SQLITE_OK;
  23224. int reserved = 0;
  23225. unixFile *pFile = (unixFile*)id;
  23226. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  23227. assert( pFile );
  23228. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  23229. /* Check if a thread in this process holds such a lock */
  23230. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  23231. reserved = 1;
  23232. }
  23233. /* Otherwise see if some other process holds it.
  23234. */
  23235. #ifndef __DJGPP__
  23236. if( !reserved && !pFile->pInode->bProcessLock ){
  23237. struct flock lock;
  23238. lock.l_whence = SEEK_SET;
  23239. lock.l_start = RESERVED_BYTE;
  23240. lock.l_len = 1;
  23241. lock.l_type = F_WRLCK;
  23242. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  23243. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  23244. pFile->lastErrno = errno;
  23245. } else if( lock.l_type!=F_UNLCK ){
  23246. reserved = 1;
  23247. }
  23248. }
  23249. #endif
  23250. unixLeaveMutex();
  23251. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  23252. *pResOut = reserved;
  23253. return rc;
  23254. }
  23255. /*
  23256. ** Attempt to set a system-lock on the file pFile. The lock is
  23257. ** described by pLock.
  23258. **
  23259. ** If the pFile was opened read/write from unix-excl, then the only lock
  23260. ** ever obtained is an exclusive lock, and it is obtained exactly once
  23261. ** the first time any lock is attempted. All subsequent system locking
  23262. ** operations become no-ops. Locking operations still happen internally,
  23263. ** in order to coordinate access between separate database connections
  23264. ** within this process, but all of that is handled in memory and the
  23265. ** operating system does not participate.
  23266. **
  23267. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  23268. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  23269. ** and is read-only.
  23270. **
  23271. ** Zero is returned if the call completes successfully, or -1 if a call
  23272. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  23273. */
  23274. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  23275. int rc;
  23276. unixInodeInfo *pInode = pFile->pInode;
  23277. assert( unixMutexHeld() );
  23278. assert( pInode!=0 );
  23279. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  23280. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  23281. ){
  23282. if( pInode->bProcessLock==0 ){
  23283. struct flock lock;
  23284. assert( pInode->nLock==0 );
  23285. lock.l_whence = SEEK_SET;
  23286. lock.l_start = SHARED_FIRST;
  23287. lock.l_len = SHARED_SIZE;
  23288. lock.l_type = F_WRLCK;
  23289. rc = osFcntl(pFile->h, F_SETLK, &lock);
  23290. if( rc<0 ) return rc;
  23291. pInode->bProcessLock = 1;
  23292. pInode->nLock++;
  23293. }else{
  23294. rc = 0;
  23295. }
  23296. }else{
  23297. rc = osFcntl(pFile->h, F_SETLK, pLock);
  23298. }
  23299. return rc;
  23300. }
  23301. /*
  23302. ** Lock the file with the lock specified by parameter eFileLock - one
  23303. ** of the following:
  23304. **
  23305. ** (1) SHARED_LOCK
  23306. ** (2) RESERVED_LOCK
  23307. ** (3) PENDING_LOCK
  23308. ** (4) EXCLUSIVE_LOCK
  23309. **
  23310. ** Sometimes when requesting one lock state, additional lock states
  23311. ** are inserted in between. The locking might fail on one of the later
  23312. ** transitions leaving the lock state different from what it started but
  23313. ** still short of its goal. The following chart shows the allowed
  23314. ** transitions and the inserted intermediate states:
  23315. **
  23316. ** UNLOCKED -> SHARED
  23317. ** SHARED -> RESERVED
  23318. ** SHARED -> (PENDING) -> EXCLUSIVE
  23319. ** RESERVED -> (PENDING) -> EXCLUSIVE
  23320. ** PENDING -> EXCLUSIVE
  23321. **
  23322. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  23323. ** routine to lower a locking level.
  23324. */
  23325. static int unixLock(sqlite3_file *id, int eFileLock){
  23326. /* The following describes the implementation of the various locks and
  23327. ** lock transitions in terms of the POSIX advisory shared and exclusive
  23328. ** lock primitives (called read-locks and write-locks below, to avoid
  23329. ** confusion with SQLite lock names). The algorithms are complicated
  23330. ** slightly in order to be compatible with windows systems simultaneously
  23331. ** accessing the same database file, in case that is ever required.
  23332. **
  23333. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  23334. ** byte', each single bytes at well known offsets, and the 'shared byte
  23335. ** range', a range of 510 bytes at a well known offset.
  23336. **
  23337. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  23338. ** byte'. If this is successful, a random byte from the 'shared byte
  23339. ** range' is read-locked and the lock on the 'pending byte' released.
  23340. **
  23341. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  23342. ** A RESERVED lock is implemented by grabbing a write-lock on the
  23343. ** 'reserved byte'.
  23344. **
  23345. ** A process may only obtain a PENDING lock after it has obtained a
  23346. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  23347. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  23348. ** obtained, but existing SHARED locks are allowed to persist. A process
  23349. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  23350. ** This property is used by the algorithm for rolling back a journal file
  23351. ** after a crash.
  23352. **
  23353. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  23354. ** implemented by obtaining a write-lock on the entire 'shared byte
  23355. ** range'. Since all other locks require a read-lock on one of the bytes
  23356. ** within this range, this ensures that no other locks are held on the
  23357. ** database.
  23358. **
  23359. ** The reason a single byte cannot be used instead of the 'shared byte
  23360. ** range' is that some versions of windows do not support read-locks. By
  23361. ** locking a random byte from a range, concurrent SHARED locks may exist
  23362. ** even if the locking primitive used is always a write-lock.
  23363. */
  23364. int rc = SQLITE_OK;
  23365. unixFile *pFile = (unixFile*)id;
  23366. unixInodeInfo *pInode;
  23367. struct flock lock;
  23368. int tErrno = 0;
  23369. assert( pFile );
  23370. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  23371. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  23372. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
  23373. /* If there is already a lock of this type or more restrictive on the
  23374. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  23375. ** unixEnterMutex() hasn't been called yet.
  23376. */
  23377. if( pFile->eFileLock>=eFileLock ){
  23378. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  23379. azFileLock(eFileLock)));
  23380. return SQLITE_OK;
  23381. }
  23382. /* Make sure the locking sequence is correct.
  23383. ** (1) We never move from unlocked to anything higher than shared lock.
  23384. ** (2) SQLite never explicitly requests a pendig lock.
  23385. ** (3) A shared lock is always held when a reserve lock is requested.
  23386. */
  23387. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  23388. assert( eFileLock!=PENDING_LOCK );
  23389. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  23390. /* This mutex is needed because pFile->pInode is shared across threads
  23391. */
  23392. unixEnterMutex();
  23393. pInode = pFile->pInode;
  23394. /* If some thread using this PID has a lock via a different unixFile*
  23395. ** handle that precludes the requested lock, return BUSY.
  23396. */
  23397. if( (pFile->eFileLock!=pInode->eFileLock &&
  23398. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  23399. ){
  23400. rc = SQLITE_BUSY;
  23401. goto end_lock;
  23402. }
  23403. /* If a SHARED lock is requested, and some thread using this PID already
  23404. ** has a SHARED or RESERVED lock, then increment reference counts and
  23405. ** return SQLITE_OK.
  23406. */
  23407. if( eFileLock==SHARED_LOCK &&
  23408. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  23409. assert( eFileLock==SHARED_LOCK );
  23410. assert( pFile->eFileLock==0 );
  23411. assert( pInode->nShared>0 );
  23412. pFile->eFileLock = SHARED_LOCK;
  23413. pInode->nShared++;
  23414. pInode->nLock++;
  23415. goto end_lock;
  23416. }
  23417. /* A PENDING lock is needed before acquiring a SHARED lock and before
  23418. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  23419. ** be released.
  23420. */
  23421. lock.l_len = 1L;
  23422. lock.l_whence = SEEK_SET;
  23423. if( eFileLock==SHARED_LOCK
  23424. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  23425. ){
  23426. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  23427. lock.l_start = PENDING_BYTE;
  23428. if( unixFileLock(pFile, &lock) ){
  23429. tErrno = errno;
  23430. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23431. if( rc!=SQLITE_BUSY ){
  23432. pFile->lastErrno = tErrno;
  23433. }
  23434. goto end_lock;
  23435. }
  23436. }
  23437. /* If control gets to this point, then actually go ahead and make
  23438. ** operating system calls for the specified lock.
  23439. */
  23440. if( eFileLock==SHARED_LOCK ){
  23441. assert( pInode->nShared==0 );
  23442. assert( pInode->eFileLock==0 );
  23443. assert( rc==SQLITE_OK );
  23444. /* Now get the read-lock */
  23445. lock.l_start = SHARED_FIRST;
  23446. lock.l_len = SHARED_SIZE;
  23447. if( unixFileLock(pFile, &lock) ){
  23448. tErrno = errno;
  23449. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23450. }
  23451. /* Drop the temporary PENDING lock */
  23452. lock.l_start = PENDING_BYTE;
  23453. lock.l_len = 1L;
  23454. lock.l_type = F_UNLCK;
  23455. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  23456. /* This could happen with a network mount */
  23457. tErrno = errno;
  23458. rc = SQLITE_IOERR_UNLOCK;
  23459. }
  23460. if( rc ){
  23461. if( rc!=SQLITE_BUSY ){
  23462. pFile->lastErrno = tErrno;
  23463. }
  23464. goto end_lock;
  23465. }else{
  23466. pFile->eFileLock = SHARED_LOCK;
  23467. pInode->nLock++;
  23468. pInode->nShared = 1;
  23469. }
  23470. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  23471. /* We are trying for an exclusive lock but another thread in this
  23472. ** same process is still holding a shared lock. */
  23473. rc = SQLITE_BUSY;
  23474. }else{
  23475. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  23476. ** assumed that there is a SHARED or greater lock on the file
  23477. ** already.
  23478. */
  23479. assert( 0!=pFile->eFileLock );
  23480. lock.l_type = F_WRLCK;
  23481. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  23482. if( eFileLock==RESERVED_LOCK ){
  23483. lock.l_start = RESERVED_BYTE;
  23484. lock.l_len = 1L;
  23485. }else{
  23486. lock.l_start = SHARED_FIRST;
  23487. lock.l_len = SHARED_SIZE;
  23488. }
  23489. if( unixFileLock(pFile, &lock) ){
  23490. tErrno = errno;
  23491. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23492. if( rc!=SQLITE_BUSY ){
  23493. pFile->lastErrno = tErrno;
  23494. }
  23495. }
  23496. }
  23497. #ifdef SQLITE_DEBUG
  23498. /* Set up the transaction-counter change checking flags when
  23499. ** transitioning from a SHARED to a RESERVED lock. The change
  23500. ** from SHARED to RESERVED marks the beginning of a normal
  23501. ** write operation (not a hot journal rollback).
  23502. */
  23503. if( rc==SQLITE_OK
  23504. && pFile->eFileLock<=SHARED_LOCK
  23505. && eFileLock==RESERVED_LOCK
  23506. ){
  23507. pFile->transCntrChng = 0;
  23508. pFile->dbUpdate = 0;
  23509. pFile->inNormalWrite = 1;
  23510. }
  23511. #endif
  23512. if( rc==SQLITE_OK ){
  23513. pFile->eFileLock = eFileLock;
  23514. pInode->eFileLock = eFileLock;
  23515. }else if( eFileLock==EXCLUSIVE_LOCK ){
  23516. pFile->eFileLock = PENDING_LOCK;
  23517. pInode->eFileLock = PENDING_LOCK;
  23518. }
  23519. end_lock:
  23520. unixLeaveMutex();
  23521. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  23522. rc==SQLITE_OK ? "ok" : "failed"));
  23523. return rc;
  23524. }
  23525. /*
  23526. ** Add the file descriptor used by file handle pFile to the corresponding
  23527. ** pUnused list.
  23528. */
  23529. static void setPendingFd(unixFile *pFile){
  23530. unixInodeInfo *pInode = pFile->pInode;
  23531. UnixUnusedFd *p = pFile->pUnused;
  23532. p->pNext = pInode->pUnused;
  23533. pInode->pUnused = p;
  23534. pFile->h = -1;
  23535. pFile->pUnused = 0;
  23536. }
  23537. /*
  23538. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23539. ** must be either NO_LOCK or SHARED_LOCK.
  23540. **
  23541. ** If the locking level of the file descriptor is already at or below
  23542. ** the requested locking level, this routine is a no-op.
  23543. **
  23544. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  23545. ** the byte range is divided into 2 parts and the first part is unlocked then
  23546. ** set to a read lock, then the other part is simply unlocked. This works
  23547. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  23548. ** remove the write lock on a region when a read lock is set.
  23549. */
  23550. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  23551. unixFile *pFile = (unixFile*)id;
  23552. unixInodeInfo *pInode;
  23553. struct flock lock;
  23554. int rc = SQLITE_OK;
  23555. assert( pFile );
  23556. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  23557. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  23558. getpid()));
  23559. assert( eFileLock<=SHARED_LOCK );
  23560. if( pFile->eFileLock<=eFileLock ){
  23561. return SQLITE_OK;
  23562. }
  23563. unixEnterMutex();
  23564. pInode = pFile->pInode;
  23565. assert( pInode->nShared!=0 );
  23566. if( pFile->eFileLock>SHARED_LOCK ){
  23567. assert( pInode->eFileLock==pFile->eFileLock );
  23568. #ifdef SQLITE_DEBUG
  23569. /* When reducing a lock such that other processes can start
  23570. ** reading the database file again, make sure that the
  23571. ** transaction counter was updated if any part of the database
  23572. ** file changed. If the transaction counter is not updated,
  23573. ** other connections to the same file might not realize that
  23574. ** the file has changed and hence might not know to flush their
  23575. ** cache. The use of a stale cache can lead to database corruption.
  23576. */
  23577. pFile->inNormalWrite = 0;
  23578. #endif
  23579. /* downgrading to a shared lock on NFS involves clearing the write lock
  23580. ** before establishing the readlock - to avoid a race condition we downgrade
  23581. ** the lock in 2 blocks, so that part of the range will be covered by a
  23582. ** write lock until the rest is covered by a read lock:
  23583. ** 1: [WWWWW]
  23584. ** 2: [....W]
  23585. ** 3: [RRRRW]
  23586. ** 4: [RRRR.]
  23587. */
  23588. if( eFileLock==SHARED_LOCK ){
  23589. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  23590. (void)handleNFSUnlock;
  23591. assert( handleNFSUnlock==0 );
  23592. #endif
  23593. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  23594. if( handleNFSUnlock ){
  23595. int tErrno; /* Error code from system call errors */
  23596. off_t divSize = SHARED_SIZE - 1;
  23597. lock.l_type = F_UNLCK;
  23598. lock.l_whence = SEEK_SET;
  23599. lock.l_start = SHARED_FIRST;
  23600. lock.l_len = divSize;
  23601. if( unixFileLock(pFile, &lock)==(-1) ){
  23602. tErrno = errno;
  23603. rc = SQLITE_IOERR_UNLOCK;
  23604. if( IS_LOCK_ERROR(rc) ){
  23605. pFile->lastErrno = tErrno;
  23606. }
  23607. goto end_unlock;
  23608. }
  23609. lock.l_type = F_RDLCK;
  23610. lock.l_whence = SEEK_SET;
  23611. lock.l_start = SHARED_FIRST;
  23612. lock.l_len = divSize;
  23613. if( unixFileLock(pFile, &lock)==(-1) ){
  23614. tErrno = errno;
  23615. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  23616. if( IS_LOCK_ERROR(rc) ){
  23617. pFile->lastErrno = tErrno;
  23618. }
  23619. goto end_unlock;
  23620. }
  23621. lock.l_type = F_UNLCK;
  23622. lock.l_whence = SEEK_SET;
  23623. lock.l_start = SHARED_FIRST+divSize;
  23624. lock.l_len = SHARED_SIZE-divSize;
  23625. if( unixFileLock(pFile, &lock)==(-1) ){
  23626. tErrno = errno;
  23627. rc = SQLITE_IOERR_UNLOCK;
  23628. if( IS_LOCK_ERROR(rc) ){
  23629. pFile->lastErrno = tErrno;
  23630. }
  23631. goto end_unlock;
  23632. }
  23633. }else
  23634. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  23635. {
  23636. lock.l_type = F_RDLCK;
  23637. lock.l_whence = SEEK_SET;
  23638. lock.l_start = SHARED_FIRST;
  23639. lock.l_len = SHARED_SIZE;
  23640. if( unixFileLock(pFile, &lock) ){
  23641. /* In theory, the call to unixFileLock() cannot fail because another
  23642. ** process is holding an incompatible lock. If it does, this
  23643. ** indicates that the other process is not following the locking
  23644. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  23645. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  23646. ** an assert to fail). */
  23647. rc = SQLITE_IOERR_RDLOCK;
  23648. pFile->lastErrno = errno;
  23649. goto end_unlock;
  23650. }
  23651. }
  23652. }
  23653. lock.l_type = F_UNLCK;
  23654. lock.l_whence = SEEK_SET;
  23655. lock.l_start = PENDING_BYTE;
  23656. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  23657. if( unixFileLock(pFile, &lock)==0 ){
  23658. pInode->eFileLock = SHARED_LOCK;
  23659. }else{
  23660. rc = SQLITE_IOERR_UNLOCK;
  23661. pFile->lastErrno = errno;
  23662. goto end_unlock;
  23663. }
  23664. }
  23665. if( eFileLock==NO_LOCK ){
  23666. /* Decrement the shared lock counter. Release the lock using an
  23667. ** OS call only when all threads in this same process have released
  23668. ** the lock.
  23669. */
  23670. pInode->nShared--;
  23671. if( pInode->nShared==0 ){
  23672. lock.l_type = F_UNLCK;
  23673. lock.l_whence = SEEK_SET;
  23674. lock.l_start = lock.l_len = 0L;
  23675. if( unixFileLock(pFile, &lock)==0 ){
  23676. pInode->eFileLock = NO_LOCK;
  23677. }else{
  23678. rc = SQLITE_IOERR_UNLOCK;
  23679. pFile->lastErrno = errno;
  23680. pInode->eFileLock = NO_LOCK;
  23681. pFile->eFileLock = NO_LOCK;
  23682. }
  23683. }
  23684. /* Decrement the count of locks against this same file. When the
  23685. ** count reaches zero, close any other file descriptors whose close
  23686. ** was deferred because of outstanding locks.
  23687. */
  23688. pInode->nLock--;
  23689. assert( pInode->nLock>=0 );
  23690. if( pInode->nLock==0 ){
  23691. closePendingFds(pFile);
  23692. }
  23693. }
  23694. end_unlock:
  23695. unixLeaveMutex();
  23696. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  23697. return rc;
  23698. }
  23699. /*
  23700. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23701. ** must be either NO_LOCK or SHARED_LOCK.
  23702. **
  23703. ** If the locking level of the file descriptor is already at or below
  23704. ** the requested locking level, this routine is a no-op.
  23705. */
  23706. static int unixUnlock(sqlite3_file *id, int eFileLock){
  23707. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  23708. return posixUnlock(id, eFileLock, 0);
  23709. }
  23710. #if SQLITE_MAX_MMAP_SIZE>0
  23711. static int unixMapfile(unixFile *pFd, i64 nByte);
  23712. static void unixUnmapfile(unixFile *pFd);
  23713. #endif
  23714. /*
  23715. ** This function performs the parts of the "close file" operation
  23716. ** common to all locking schemes. It closes the directory and file
  23717. ** handles, if they are valid, and sets all fields of the unixFile
  23718. ** structure to 0.
  23719. **
  23720. ** It is *not* necessary to hold the mutex when this routine is called,
  23721. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  23722. ** vxworksReleaseFileId() routine.
  23723. */
  23724. static int closeUnixFile(sqlite3_file *id){
  23725. unixFile *pFile = (unixFile*)id;
  23726. #if SQLITE_MAX_MMAP_SIZE>0
  23727. unixUnmapfile(pFile);
  23728. #endif
  23729. if( pFile->h>=0 ){
  23730. robust_close(pFile, pFile->h, __LINE__);
  23731. pFile->h = -1;
  23732. }
  23733. #if OS_VXWORKS
  23734. if( pFile->pId ){
  23735. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  23736. osUnlink(pFile->pId->zCanonicalName);
  23737. }
  23738. vxworksReleaseFileId(pFile->pId);
  23739. pFile->pId = 0;
  23740. }
  23741. #endif
  23742. OSTRACE(("CLOSE %-3d\n", pFile->h));
  23743. OpenCounter(-1);
  23744. sqlite3_free(pFile->pUnused);
  23745. memset(pFile, 0, sizeof(unixFile));
  23746. return SQLITE_OK;
  23747. }
  23748. /*
  23749. ** Close a file.
  23750. */
  23751. static int unixClose(sqlite3_file *id){
  23752. int rc = SQLITE_OK;
  23753. unixFile *pFile = (unixFile *)id;
  23754. verifyDbFile(pFile);
  23755. unixUnlock(id, NO_LOCK);
  23756. unixEnterMutex();
  23757. /* unixFile.pInode is always valid here. Otherwise, a different close
  23758. ** routine (e.g. nolockClose()) would be called instead.
  23759. */
  23760. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  23761. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  23762. /* If there are outstanding locks, do not actually close the file just
  23763. ** yet because that would clear those locks. Instead, add the file
  23764. ** descriptor to pInode->pUnused list. It will be automatically closed
  23765. ** when the last lock is cleared.
  23766. */
  23767. setPendingFd(pFile);
  23768. }
  23769. releaseInodeInfo(pFile);
  23770. rc = closeUnixFile(id);
  23771. unixLeaveMutex();
  23772. return rc;
  23773. }
  23774. /************** End of the posix advisory lock implementation *****************
  23775. ******************************************************************************/
  23776. /******************************************************************************
  23777. ****************************** No-op Locking **********************************
  23778. **
  23779. ** Of the various locking implementations available, this is by far the
  23780. ** simplest: locking is ignored. No attempt is made to lock the database
  23781. ** file for reading or writing.
  23782. **
  23783. ** This locking mode is appropriate for use on read-only databases
  23784. ** (ex: databases that are burned into CD-ROM, for example.) It can
  23785. ** also be used if the application employs some external mechanism to
  23786. ** prevent simultaneous access of the same database by two or more
  23787. ** database connections. But there is a serious risk of database
  23788. ** corruption if this locking mode is used in situations where multiple
  23789. ** database connections are accessing the same database file at the same
  23790. ** time and one or more of those connections are writing.
  23791. */
  23792. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  23793. UNUSED_PARAMETER(NotUsed);
  23794. *pResOut = 0;
  23795. return SQLITE_OK;
  23796. }
  23797. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  23798. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  23799. return SQLITE_OK;
  23800. }
  23801. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  23802. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  23803. return SQLITE_OK;
  23804. }
  23805. /*
  23806. ** Close the file.
  23807. */
  23808. static int nolockClose(sqlite3_file *id) {
  23809. return closeUnixFile(id);
  23810. }
  23811. /******************* End of the no-op lock implementation *********************
  23812. ******************************************************************************/
  23813. /******************************************************************************
  23814. ************************* Begin dot-file Locking ******************************
  23815. **
  23816. ** The dotfile locking implementation uses the existence of separate lock
  23817. ** files (really a directory) to control access to the database. This works
  23818. ** on just about every filesystem imaginable. But there are serious downsides:
  23819. **
  23820. ** (1) There is zero concurrency. A single reader blocks all other
  23821. ** connections from reading or writing the database.
  23822. **
  23823. ** (2) An application crash or power loss can leave stale lock files
  23824. ** sitting around that need to be cleared manually.
  23825. **
  23826. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  23827. ** other locking strategy is available.
  23828. **
  23829. ** Dotfile locking works by creating a subdirectory in the same directory as
  23830. ** the database and with the same name but with a ".lock" extension added.
  23831. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  23832. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  23833. */
  23834. /*
  23835. ** The file suffix added to the data base filename in order to create the
  23836. ** lock directory.
  23837. */
  23838. #define DOTLOCK_SUFFIX ".lock"
  23839. /*
  23840. ** This routine checks if there is a RESERVED lock held on the specified
  23841. ** file by this or any other process. If such a lock is held, set *pResOut
  23842. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  23843. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  23844. **
  23845. ** In dotfile locking, either a lock exists or it does not. So in this
  23846. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  23847. ** is held on the file and false if the file is unlocked.
  23848. */
  23849. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  23850. int rc = SQLITE_OK;
  23851. int reserved = 0;
  23852. unixFile *pFile = (unixFile*)id;
  23853. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  23854. assert( pFile );
  23855. /* Check if a thread in this process holds such a lock */
  23856. if( pFile->eFileLock>SHARED_LOCK ){
  23857. /* Either this connection or some other connection in the same process
  23858. ** holds a lock on the file. No need to check further. */
  23859. reserved = 1;
  23860. }else{
  23861. /* The lock is held if and only if the lockfile exists */
  23862. const char *zLockFile = (const char*)pFile->lockingContext;
  23863. reserved = osAccess(zLockFile, 0)==0;
  23864. }
  23865. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  23866. *pResOut = reserved;
  23867. return rc;
  23868. }
  23869. /*
  23870. ** Lock the file with the lock specified by parameter eFileLock - one
  23871. ** of the following:
  23872. **
  23873. ** (1) SHARED_LOCK
  23874. ** (2) RESERVED_LOCK
  23875. ** (3) PENDING_LOCK
  23876. ** (4) EXCLUSIVE_LOCK
  23877. **
  23878. ** Sometimes when requesting one lock state, additional lock states
  23879. ** are inserted in between. The locking might fail on one of the later
  23880. ** transitions leaving the lock state different from what it started but
  23881. ** still short of its goal. The following chart shows the allowed
  23882. ** transitions and the inserted intermediate states:
  23883. **
  23884. ** UNLOCKED -> SHARED
  23885. ** SHARED -> RESERVED
  23886. ** SHARED -> (PENDING) -> EXCLUSIVE
  23887. ** RESERVED -> (PENDING) -> EXCLUSIVE
  23888. ** PENDING -> EXCLUSIVE
  23889. **
  23890. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  23891. ** routine to lower a locking level.
  23892. **
  23893. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  23894. ** But we track the other locking levels internally.
  23895. */
  23896. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  23897. unixFile *pFile = (unixFile*)id;
  23898. char *zLockFile = (char *)pFile->lockingContext;
  23899. int rc = SQLITE_OK;
  23900. /* If we have any lock, then the lock file already exists. All we have
  23901. ** to do is adjust our internal record of the lock level.
  23902. */
  23903. if( pFile->eFileLock > NO_LOCK ){
  23904. pFile->eFileLock = eFileLock;
  23905. /* Always update the timestamp on the old file */
  23906. #ifdef HAVE_UTIME
  23907. utime(zLockFile, NULL);
  23908. #else
  23909. utimes(zLockFile, NULL);
  23910. #endif
  23911. return SQLITE_OK;
  23912. }
  23913. /* grab an exclusive lock */
  23914. rc = osMkdir(zLockFile, 0777);
  23915. if( rc<0 ){
  23916. /* failed to open/create the lock directory */
  23917. int tErrno = errno;
  23918. if( EEXIST == tErrno ){
  23919. rc = SQLITE_BUSY;
  23920. } else {
  23921. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23922. if( IS_LOCK_ERROR(rc) ){
  23923. pFile->lastErrno = tErrno;
  23924. }
  23925. }
  23926. return rc;
  23927. }
  23928. /* got it, set the type and return ok */
  23929. pFile->eFileLock = eFileLock;
  23930. return rc;
  23931. }
  23932. /*
  23933. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23934. ** must be either NO_LOCK or SHARED_LOCK.
  23935. **
  23936. ** If the locking level of the file descriptor is already at or below
  23937. ** the requested locking level, this routine is a no-op.
  23938. **
  23939. ** When the locking level reaches NO_LOCK, delete the lock file.
  23940. */
  23941. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  23942. unixFile *pFile = (unixFile*)id;
  23943. char *zLockFile = (char *)pFile->lockingContext;
  23944. int rc;
  23945. assert( pFile );
  23946. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  23947. pFile->eFileLock, getpid()));
  23948. assert( eFileLock<=SHARED_LOCK );
  23949. /* no-op if possible */
  23950. if( pFile->eFileLock==eFileLock ){
  23951. return SQLITE_OK;
  23952. }
  23953. /* To downgrade to shared, simply update our internal notion of the
  23954. ** lock state. No need to mess with the file on disk.
  23955. */
  23956. if( eFileLock==SHARED_LOCK ){
  23957. pFile->eFileLock = SHARED_LOCK;
  23958. return SQLITE_OK;
  23959. }
  23960. /* To fully unlock the database, delete the lock file */
  23961. assert( eFileLock==NO_LOCK );
  23962. rc = osRmdir(zLockFile);
  23963. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  23964. if( rc<0 ){
  23965. int tErrno = errno;
  23966. rc = 0;
  23967. if( ENOENT != tErrno ){
  23968. rc = SQLITE_IOERR_UNLOCK;
  23969. }
  23970. if( IS_LOCK_ERROR(rc) ){
  23971. pFile->lastErrno = tErrno;
  23972. }
  23973. return rc;
  23974. }
  23975. pFile->eFileLock = NO_LOCK;
  23976. return SQLITE_OK;
  23977. }
  23978. /*
  23979. ** Close a file. Make sure the lock has been released before closing.
  23980. */
  23981. static int dotlockClose(sqlite3_file *id) {
  23982. int rc = SQLITE_OK;
  23983. if( id ){
  23984. unixFile *pFile = (unixFile*)id;
  23985. dotlockUnlock(id, NO_LOCK);
  23986. sqlite3_free(pFile->lockingContext);
  23987. rc = closeUnixFile(id);
  23988. }
  23989. return rc;
  23990. }
  23991. /****************** End of the dot-file lock implementation *******************
  23992. ******************************************************************************/
  23993. /******************************************************************************
  23994. ************************** Begin flock Locking ********************************
  23995. **
  23996. ** Use the flock() system call to do file locking.
  23997. **
  23998. ** flock() locking is like dot-file locking in that the various
  23999. ** fine-grain locking levels supported by SQLite are collapsed into
  24000. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  24001. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  24002. ** still works when you do this, but concurrency is reduced since
  24003. ** only a single process can be reading the database at a time.
  24004. **
  24005. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  24006. ** compiling for VXWORKS.
  24007. */
  24008. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  24009. /*
  24010. ** Retry flock() calls that fail with EINTR
  24011. */
  24012. #ifdef EINTR
  24013. static int robust_flock(int fd, int op){
  24014. int rc;
  24015. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  24016. return rc;
  24017. }
  24018. #else
  24019. # define robust_flock(a,b) flock(a,b)
  24020. #endif
  24021. /*
  24022. ** This routine checks if there is a RESERVED lock held on the specified
  24023. ** file by this or any other process. If such a lock is held, set *pResOut
  24024. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24025. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24026. */
  24027. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  24028. int rc = SQLITE_OK;
  24029. int reserved = 0;
  24030. unixFile *pFile = (unixFile*)id;
  24031. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24032. assert( pFile );
  24033. /* Check if a thread in this process holds such a lock */
  24034. if( pFile->eFileLock>SHARED_LOCK ){
  24035. reserved = 1;
  24036. }
  24037. /* Otherwise see if some other process holds it. */
  24038. if( !reserved ){
  24039. /* attempt to get the lock */
  24040. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  24041. if( !lrc ){
  24042. /* got the lock, unlock it */
  24043. lrc = robust_flock(pFile->h, LOCK_UN);
  24044. if ( lrc ) {
  24045. int tErrno = errno;
  24046. /* unlock failed with an error */
  24047. lrc = SQLITE_IOERR_UNLOCK;
  24048. if( IS_LOCK_ERROR(lrc) ){
  24049. pFile->lastErrno = tErrno;
  24050. rc = lrc;
  24051. }
  24052. }
  24053. } else {
  24054. int tErrno = errno;
  24055. reserved = 1;
  24056. /* someone else might have it reserved */
  24057. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24058. if( IS_LOCK_ERROR(lrc) ){
  24059. pFile->lastErrno = tErrno;
  24060. rc = lrc;
  24061. }
  24062. }
  24063. }
  24064. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  24065. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24066. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  24067. rc = SQLITE_OK;
  24068. reserved=1;
  24069. }
  24070. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24071. *pResOut = reserved;
  24072. return rc;
  24073. }
  24074. /*
  24075. ** Lock the file with the lock specified by parameter eFileLock - one
  24076. ** of the following:
  24077. **
  24078. ** (1) SHARED_LOCK
  24079. ** (2) RESERVED_LOCK
  24080. ** (3) PENDING_LOCK
  24081. ** (4) EXCLUSIVE_LOCK
  24082. **
  24083. ** Sometimes when requesting one lock state, additional lock states
  24084. ** are inserted in between. The locking might fail on one of the later
  24085. ** transitions leaving the lock state different from what it started but
  24086. ** still short of its goal. The following chart shows the allowed
  24087. ** transitions and the inserted intermediate states:
  24088. **
  24089. ** UNLOCKED -> SHARED
  24090. ** SHARED -> RESERVED
  24091. ** SHARED -> (PENDING) -> EXCLUSIVE
  24092. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24093. ** PENDING -> EXCLUSIVE
  24094. **
  24095. ** flock() only really support EXCLUSIVE locks. We track intermediate
  24096. ** lock states in the sqlite3_file structure, but all locks SHARED or
  24097. ** above are really EXCLUSIVE locks and exclude all other processes from
  24098. ** access the file.
  24099. **
  24100. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24101. ** routine to lower a locking level.
  24102. */
  24103. static int flockLock(sqlite3_file *id, int eFileLock) {
  24104. int rc = SQLITE_OK;
  24105. unixFile *pFile = (unixFile*)id;
  24106. assert( pFile );
  24107. /* if we already have a lock, it is exclusive.
  24108. ** Just adjust level and punt on outta here. */
  24109. if (pFile->eFileLock > NO_LOCK) {
  24110. pFile->eFileLock = eFileLock;
  24111. return SQLITE_OK;
  24112. }
  24113. /* grab an exclusive lock */
  24114. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  24115. int tErrno = errno;
  24116. /* didn't get, must be busy */
  24117. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24118. if( IS_LOCK_ERROR(rc) ){
  24119. pFile->lastErrno = tErrno;
  24120. }
  24121. } else {
  24122. /* got it, set the type and return ok */
  24123. pFile->eFileLock = eFileLock;
  24124. }
  24125. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  24126. rc==SQLITE_OK ? "ok" : "failed"));
  24127. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24128. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  24129. rc = SQLITE_BUSY;
  24130. }
  24131. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24132. return rc;
  24133. }
  24134. /*
  24135. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24136. ** must be either NO_LOCK or SHARED_LOCK.
  24137. **
  24138. ** If the locking level of the file descriptor is already at or below
  24139. ** the requested locking level, this routine is a no-op.
  24140. */
  24141. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  24142. unixFile *pFile = (unixFile*)id;
  24143. assert( pFile );
  24144. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  24145. pFile->eFileLock, getpid()));
  24146. assert( eFileLock<=SHARED_LOCK );
  24147. /* no-op if possible */
  24148. if( pFile->eFileLock==eFileLock ){
  24149. return SQLITE_OK;
  24150. }
  24151. /* shared can just be set because we always have an exclusive */
  24152. if (eFileLock==SHARED_LOCK) {
  24153. pFile->eFileLock = eFileLock;
  24154. return SQLITE_OK;
  24155. }
  24156. /* no, really, unlock. */
  24157. if( robust_flock(pFile->h, LOCK_UN) ){
  24158. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24159. return SQLITE_OK;
  24160. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24161. return SQLITE_IOERR_UNLOCK;
  24162. }else{
  24163. pFile->eFileLock = NO_LOCK;
  24164. return SQLITE_OK;
  24165. }
  24166. }
  24167. /*
  24168. ** Close a file.
  24169. */
  24170. static int flockClose(sqlite3_file *id) {
  24171. int rc = SQLITE_OK;
  24172. if( id ){
  24173. flockUnlock(id, NO_LOCK);
  24174. rc = closeUnixFile(id);
  24175. }
  24176. return rc;
  24177. }
  24178. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  24179. /******************* End of the flock lock implementation *********************
  24180. ******************************************************************************/
  24181. /******************************************************************************
  24182. ************************ Begin Named Semaphore Locking ************************
  24183. **
  24184. ** Named semaphore locking is only supported on VxWorks.
  24185. **
  24186. ** Semaphore locking is like dot-lock and flock in that it really only
  24187. ** supports EXCLUSIVE locking. Only a single process can read or write
  24188. ** the database file at a time. This reduces potential concurrency, but
  24189. ** makes the lock implementation much easier.
  24190. */
  24191. #if OS_VXWORKS
  24192. /*
  24193. ** This routine checks if there is a RESERVED lock held on the specified
  24194. ** file by this or any other process. If such a lock is held, set *pResOut
  24195. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24196. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24197. */
  24198. static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
  24199. int rc = SQLITE_OK;
  24200. int reserved = 0;
  24201. unixFile *pFile = (unixFile*)id;
  24202. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24203. assert( pFile );
  24204. /* Check if a thread in this process holds such a lock */
  24205. if( pFile->eFileLock>SHARED_LOCK ){
  24206. reserved = 1;
  24207. }
  24208. /* Otherwise see if some other process holds it. */
  24209. if( !reserved ){
  24210. sem_t *pSem = pFile->pInode->pSem;
  24211. struct stat statBuf;
  24212. if( sem_trywait(pSem)==-1 ){
  24213. int tErrno = errno;
  24214. if( EAGAIN != tErrno ){
  24215. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  24216. pFile->lastErrno = tErrno;
  24217. } else {
  24218. /* someone else has the lock when we are in NO_LOCK */
  24219. reserved = (pFile->eFileLock < SHARED_LOCK);
  24220. }
  24221. }else{
  24222. /* we could have it if we want it */
  24223. sem_post(pSem);
  24224. }
  24225. }
  24226. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  24227. *pResOut = reserved;
  24228. return rc;
  24229. }
  24230. /*
  24231. ** Lock the file with the lock specified by parameter eFileLock - one
  24232. ** of the following:
  24233. **
  24234. ** (1) SHARED_LOCK
  24235. ** (2) RESERVED_LOCK
  24236. ** (3) PENDING_LOCK
  24237. ** (4) EXCLUSIVE_LOCK
  24238. **
  24239. ** Sometimes when requesting one lock state, additional lock states
  24240. ** are inserted in between. The locking might fail on one of the later
  24241. ** transitions leaving the lock state different from what it started but
  24242. ** still short of its goal. The following chart shows the allowed
  24243. ** transitions and the inserted intermediate states:
  24244. **
  24245. ** UNLOCKED -> SHARED
  24246. ** SHARED -> RESERVED
  24247. ** SHARED -> (PENDING) -> EXCLUSIVE
  24248. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24249. ** PENDING -> EXCLUSIVE
  24250. **
  24251. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  24252. ** lock states in the sqlite3_file structure, but all locks SHARED or
  24253. ** above are really EXCLUSIVE locks and exclude all other processes from
  24254. ** access the file.
  24255. **
  24256. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24257. ** routine to lower a locking level.
  24258. */
  24259. static int semLock(sqlite3_file *id, int eFileLock) {
  24260. unixFile *pFile = (unixFile*)id;
  24261. int fd;
  24262. sem_t *pSem = pFile->pInode->pSem;
  24263. int rc = SQLITE_OK;
  24264. /* if we already have a lock, it is exclusive.
  24265. ** Just adjust level and punt on outta here. */
  24266. if (pFile->eFileLock > NO_LOCK) {
  24267. pFile->eFileLock = eFileLock;
  24268. rc = SQLITE_OK;
  24269. goto sem_end_lock;
  24270. }
  24271. /* lock semaphore now but bail out when already locked. */
  24272. if( sem_trywait(pSem)==-1 ){
  24273. rc = SQLITE_BUSY;
  24274. goto sem_end_lock;
  24275. }
  24276. /* got it, set the type and return ok */
  24277. pFile->eFileLock = eFileLock;
  24278. sem_end_lock:
  24279. return rc;
  24280. }
  24281. /*
  24282. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24283. ** must be either NO_LOCK or SHARED_LOCK.
  24284. **
  24285. ** If the locking level of the file descriptor is already at or below
  24286. ** the requested locking level, this routine is a no-op.
  24287. */
  24288. static int semUnlock(sqlite3_file *id, int eFileLock) {
  24289. unixFile *pFile = (unixFile*)id;
  24290. sem_t *pSem = pFile->pInode->pSem;
  24291. assert( pFile );
  24292. assert( pSem );
  24293. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  24294. pFile->eFileLock, getpid()));
  24295. assert( eFileLock<=SHARED_LOCK );
  24296. /* no-op if possible */
  24297. if( pFile->eFileLock==eFileLock ){
  24298. return SQLITE_OK;
  24299. }
  24300. /* shared can just be set because we always have an exclusive */
  24301. if (eFileLock==SHARED_LOCK) {
  24302. pFile->eFileLock = eFileLock;
  24303. return SQLITE_OK;
  24304. }
  24305. /* no, really unlock. */
  24306. if ( sem_post(pSem)==-1 ) {
  24307. int rc, tErrno = errno;
  24308. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  24309. if( IS_LOCK_ERROR(rc) ){
  24310. pFile->lastErrno = tErrno;
  24311. }
  24312. return rc;
  24313. }
  24314. pFile->eFileLock = NO_LOCK;
  24315. return SQLITE_OK;
  24316. }
  24317. /*
  24318. ** Close a file.
  24319. */
  24320. static int semClose(sqlite3_file *id) {
  24321. if( id ){
  24322. unixFile *pFile = (unixFile*)id;
  24323. semUnlock(id, NO_LOCK);
  24324. assert( pFile );
  24325. unixEnterMutex();
  24326. releaseInodeInfo(pFile);
  24327. unixLeaveMutex();
  24328. closeUnixFile(id);
  24329. }
  24330. return SQLITE_OK;
  24331. }
  24332. #endif /* OS_VXWORKS */
  24333. /*
  24334. ** Named semaphore locking is only available on VxWorks.
  24335. **
  24336. *************** End of the named semaphore lock implementation ****************
  24337. ******************************************************************************/
  24338. /******************************************************************************
  24339. *************************** Begin AFP Locking *********************************
  24340. **
  24341. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  24342. ** on Apple Macintosh computers - both OS9 and OSX.
  24343. **
  24344. ** Third-party implementations of AFP are available. But this code here
  24345. ** only works on OSX.
  24346. */
  24347. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  24348. /*
  24349. ** The afpLockingContext structure contains all afp lock specific state
  24350. */
  24351. typedef struct afpLockingContext afpLockingContext;
  24352. struct afpLockingContext {
  24353. int reserved;
  24354. const char *dbPath; /* Name of the open file */
  24355. };
  24356. struct ByteRangeLockPB2
  24357. {
  24358. unsigned long long offset; /* offset to first byte to lock */
  24359. unsigned long long length; /* nbr of bytes to lock */
  24360. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  24361. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  24362. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  24363. int fd; /* file desc to assoc this lock with */
  24364. };
  24365. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  24366. /*
  24367. ** This is a utility for setting or clearing a bit-range lock on an
  24368. ** AFP filesystem.
  24369. **
  24370. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  24371. */
  24372. static int afpSetLock(
  24373. const char *path, /* Name of the file to be locked or unlocked */
  24374. unixFile *pFile, /* Open file descriptor on path */
  24375. unsigned long long offset, /* First byte to be locked */
  24376. unsigned long long length, /* Number of bytes to lock */
  24377. int setLockFlag /* True to set lock. False to clear lock */
  24378. ){
  24379. struct ByteRangeLockPB2 pb;
  24380. int err;
  24381. pb.unLockFlag = setLockFlag ? 0 : 1;
  24382. pb.startEndFlag = 0;
  24383. pb.offset = offset;
  24384. pb.length = length;
  24385. pb.fd = pFile->h;
  24386. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  24387. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  24388. offset, length));
  24389. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  24390. if ( err==-1 ) {
  24391. int rc;
  24392. int tErrno = errno;
  24393. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  24394. path, tErrno, strerror(tErrno)));
  24395. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  24396. rc = SQLITE_BUSY;
  24397. #else
  24398. rc = sqliteErrorFromPosixError(tErrno,
  24399. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  24400. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  24401. if( IS_LOCK_ERROR(rc) ){
  24402. pFile->lastErrno = tErrno;
  24403. }
  24404. return rc;
  24405. } else {
  24406. return SQLITE_OK;
  24407. }
  24408. }
  24409. /*
  24410. ** This routine checks if there is a RESERVED lock held on the specified
  24411. ** file by this or any other process. If such a lock is held, set *pResOut
  24412. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24413. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24414. */
  24415. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  24416. int rc = SQLITE_OK;
  24417. int reserved = 0;
  24418. unixFile *pFile = (unixFile*)id;
  24419. afpLockingContext *context;
  24420. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24421. assert( pFile );
  24422. context = (afpLockingContext *) pFile->lockingContext;
  24423. if( context->reserved ){
  24424. *pResOut = 1;
  24425. return SQLITE_OK;
  24426. }
  24427. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  24428. /* Check if a thread in this process holds such a lock */
  24429. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  24430. reserved = 1;
  24431. }
  24432. /* Otherwise see if some other process holds it.
  24433. */
  24434. if( !reserved ){
  24435. /* lock the RESERVED byte */
  24436. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  24437. if( SQLITE_OK==lrc ){
  24438. /* if we succeeded in taking the reserved lock, unlock it to restore
  24439. ** the original state */
  24440. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  24441. } else {
  24442. /* if we failed to get the lock then someone else must have it */
  24443. reserved = 1;
  24444. }
  24445. if( IS_LOCK_ERROR(lrc) ){
  24446. rc=lrc;
  24447. }
  24448. }
  24449. unixLeaveMutex();
  24450. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  24451. *pResOut = reserved;
  24452. return rc;
  24453. }
  24454. /*
  24455. ** Lock the file with the lock specified by parameter eFileLock - one
  24456. ** of the following:
  24457. **
  24458. ** (1) SHARED_LOCK
  24459. ** (2) RESERVED_LOCK
  24460. ** (3) PENDING_LOCK
  24461. ** (4) EXCLUSIVE_LOCK
  24462. **
  24463. ** Sometimes when requesting one lock state, additional lock states
  24464. ** are inserted in between. The locking might fail on one of the later
  24465. ** transitions leaving the lock state different from what it started but
  24466. ** still short of its goal. The following chart shows the allowed
  24467. ** transitions and the inserted intermediate states:
  24468. **
  24469. ** UNLOCKED -> SHARED
  24470. ** SHARED -> RESERVED
  24471. ** SHARED -> (PENDING) -> EXCLUSIVE
  24472. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24473. ** PENDING -> EXCLUSIVE
  24474. **
  24475. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24476. ** routine to lower a locking level.
  24477. */
  24478. static int afpLock(sqlite3_file *id, int eFileLock){
  24479. int rc = SQLITE_OK;
  24480. unixFile *pFile = (unixFile*)id;
  24481. unixInodeInfo *pInode = pFile->pInode;
  24482. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  24483. assert( pFile );
  24484. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  24485. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  24486. azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
  24487. /* If there is already a lock of this type or more restrictive on the
  24488. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  24489. ** unixEnterMutex() hasn't been called yet.
  24490. */
  24491. if( pFile->eFileLock>=eFileLock ){
  24492. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  24493. azFileLock(eFileLock)));
  24494. return SQLITE_OK;
  24495. }
  24496. /* Make sure the locking sequence is correct
  24497. ** (1) We never move from unlocked to anything higher than shared lock.
  24498. ** (2) SQLite never explicitly requests a pendig lock.
  24499. ** (3) A shared lock is always held when a reserve lock is requested.
  24500. */
  24501. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  24502. assert( eFileLock!=PENDING_LOCK );
  24503. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  24504. /* This mutex is needed because pFile->pInode is shared across threads
  24505. */
  24506. unixEnterMutex();
  24507. pInode = pFile->pInode;
  24508. /* If some thread using this PID has a lock via a different unixFile*
  24509. ** handle that precludes the requested lock, return BUSY.
  24510. */
  24511. if( (pFile->eFileLock!=pInode->eFileLock &&
  24512. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  24513. ){
  24514. rc = SQLITE_BUSY;
  24515. goto afp_end_lock;
  24516. }
  24517. /* If a SHARED lock is requested, and some thread using this PID already
  24518. ** has a SHARED or RESERVED lock, then increment reference counts and
  24519. ** return SQLITE_OK.
  24520. */
  24521. if( eFileLock==SHARED_LOCK &&
  24522. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  24523. assert( eFileLock==SHARED_LOCK );
  24524. assert( pFile->eFileLock==0 );
  24525. assert( pInode->nShared>0 );
  24526. pFile->eFileLock = SHARED_LOCK;
  24527. pInode->nShared++;
  24528. pInode->nLock++;
  24529. goto afp_end_lock;
  24530. }
  24531. /* A PENDING lock is needed before acquiring a SHARED lock and before
  24532. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  24533. ** be released.
  24534. */
  24535. if( eFileLock==SHARED_LOCK
  24536. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  24537. ){
  24538. int failed;
  24539. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  24540. if (failed) {
  24541. rc = failed;
  24542. goto afp_end_lock;
  24543. }
  24544. }
  24545. /* If control gets to this point, then actually go ahead and make
  24546. ** operating system calls for the specified lock.
  24547. */
  24548. if( eFileLock==SHARED_LOCK ){
  24549. int lrc1, lrc2, lrc1Errno = 0;
  24550. long lk, mask;
  24551. assert( pInode->nShared==0 );
  24552. assert( pInode->eFileLock==0 );
  24553. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  24554. /* Now get the read-lock SHARED_LOCK */
  24555. /* note that the quality of the randomness doesn't matter that much */
  24556. lk = random();
  24557. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  24558. lrc1 = afpSetLock(context->dbPath, pFile,
  24559. SHARED_FIRST+pInode->sharedByte, 1, 1);
  24560. if( IS_LOCK_ERROR(lrc1) ){
  24561. lrc1Errno = pFile->lastErrno;
  24562. }
  24563. /* Drop the temporary PENDING lock */
  24564. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  24565. if( IS_LOCK_ERROR(lrc1) ) {
  24566. pFile->lastErrno = lrc1Errno;
  24567. rc = lrc1;
  24568. goto afp_end_lock;
  24569. } else if( IS_LOCK_ERROR(lrc2) ){
  24570. rc = lrc2;
  24571. goto afp_end_lock;
  24572. } else if( lrc1 != SQLITE_OK ) {
  24573. rc = lrc1;
  24574. } else {
  24575. pFile->eFileLock = SHARED_LOCK;
  24576. pInode->nLock++;
  24577. pInode->nShared = 1;
  24578. }
  24579. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  24580. /* We are trying for an exclusive lock but another thread in this
  24581. ** same process is still holding a shared lock. */
  24582. rc = SQLITE_BUSY;
  24583. }else{
  24584. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  24585. ** assumed that there is a SHARED or greater lock on the file
  24586. ** already.
  24587. */
  24588. int failed = 0;
  24589. assert( 0!=pFile->eFileLock );
  24590. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  24591. /* Acquire a RESERVED lock */
  24592. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  24593. if( !failed ){
  24594. context->reserved = 1;
  24595. }
  24596. }
  24597. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  24598. /* Acquire an EXCLUSIVE lock */
  24599. /* Remove the shared lock before trying the range. we'll need to
  24600. ** reestablish the shared lock if we can't get the afpUnlock
  24601. */
  24602. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  24603. pInode->sharedByte, 1, 0)) ){
  24604. int failed2 = SQLITE_OK;
  24605. /* now attemmpt to get the exclusive lock range */
  24606. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  24607. SHARED_SIZE, 1);
  24608. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  24609. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  24610. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  24611. ** a critical I/O error
  24612. */
  24613. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  24614. SQLITE_IOERR_LOCK;
  24615. goto afp_end_lock;
  24616. }
  24617. }else{
  24618. rc = failed;
  24619. }
  24620. }
  24621. if( failed ){
  24622. rc = failed;
  24623. }
  24624. }
  24625. if( rc==SQLITE_OK ){
  24626. pFile->eFileLock = eFileLock;
  24627. pInode->eFileLock = eFileLock;
  24628. }else if( eFileLock==EXCLUSIVE_LOCK ){
  24629. pFile->eFileLock = PENDING_LOCK;
  24630. pInode->eFileLock = PENDING_LOCK;
  24631. }
  24632. afp_end_lock:
  24633. unixLeaveMutex();
  24634. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  24635. rc==SQLITE_OK ? "ok" : "failed"));
  24636. return rc;
  24637. }
  24638. /*
  24639. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24640. ** must be either NO_LOCK or SHARED_LOCK.
  24641. **
  24642. ** If the locking level of the file descriptor is already at or below
  24643. ** the requested locking level, this routine is a no-op.
  24644. */
  24645. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  24646. int rc = SQLITE_OK;
  24647. unixFile *pFile = (unixFile*)id;
  24648. unixInodeInfo *pInode;
  24649. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  24650. int skipShared = 0;
  24651. #ifdef SQLITE_TEST
  24652. int h = pFile->h;
  24653. #endif
  24654. assert( pFile );
  24655. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  24656. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  24657. getpid()));
  24658. assert( eFileLock<=SHARED_LOCK );
  24659. if( pFile->eFileLock<=eFileLock ){
  24660. return SQLITE_OK;
  24661. }
  24662. unixEnterMutex();
  24663. pInode = pFile->pInode;
  24664. assert( pInode->nShared!=0 );
  24665. if( pFile->eFileLock>SHARED_LOCK ){
  24666. assert( pInode->eFileLock==pFile->eFileLock );
  24667. SimulateIOErrorBenign(1);
  24668. SimulateIOError( h=(-1) )
  24669. SimulateIOErrorBenign(0);
  24670. #ifdef SQLITE_DEBUG
  24671. /* When reducing a lock such that other processes can start
  24672. ** reading the database file again, make sure that the
  24673. ** transaction counter was updated if any part of the database
  24674. ** file changed. If the transaction counter is not updated,
  24675. ** other connections to the same file might not realize that
  24676. ** the file has changed and hence might not know to flush their
  24677. ** cache. The use of a stale cache can lead to database corruption.
  24678. */
  24679. assert( pFile->inNormalWrite==0
  24680. || pFile->dbUpdate==0
  24681. || pFile->transCntrChng==1 );
  24682. pFile->inNormalWrite = 0;
  24683. #endif
  24684. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  24685. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  24686. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  24687. /* only re-establish the shared lock if necessary */
  24688. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  24689. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  24690. } else {
  24691. skipShared = 1;
  24692. }
  24693. }
  24694. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  24695. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  24696. }
  24697. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  24698. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  24699. if( !rc ){
  24700. context->reserved = 0;
  24701. }
  24702. }
  24703. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  24704. pInode->eFileLock = SHARED_LOCK;
  24705. }
  24706. }
  24707. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  24708. /* Decrement the shared lock counter. Release the lock using an
  24709. ** OS call only when all threads in this same process have released
  24710. ** the lock.
  24711. */
  24712. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  24713. pInode->nShared--;
  24714. if( pInode->nShared==0 ){
  24715. SimulateIOErrorBenign(1);
  24716. SimulateIOError( h=(-1) )
  24717. SimulateIOErrorBenign(0);
  24718. if( !skipShared ){
  24719. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  24720. }
  24721. if( !rc ){
  24722. pInode->eFileLock = NO_LOCK;
  24723. pFile->eFileLock = NO_LOCK;
  24724. }
  24725. }
  24726. if( rc==SQLITE_OK ){
  24727. pInode->nLock--;
  24728. assert( pInode->nLock>=0 );
  24729. if( pInode->nLock==0 ){
  24730. closePendingFds(pFile);
  24731. }
  24732. }
  24733. }
  24734. unixLeaveMutex();
  24735. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  24736. return rc;
  24737. }
  24738. /*
  24739. ** Close a file & cleanup AFP specific locking context
  24740. */
  24741. static int afpClose(sqlite3_file *id) {
  24742. int rc = SQLITE_OK;
  24743. if( id ){
  24744. unixFile *pFile = (unixFile*)id;
  24745. afpUnlock(id, NO_LOCK);
  24746. unixEnterMutex();
  24747. if( pFile->pInode && pFile->pInode->nLock ){
  24748. /* If there are outstanding locks, do not actually close the file just
  24749. ** yet because that would clear those locks. Instead, add the file
  24750. ** descriptor to pInode->aPending. It will be automatically closed when
  24751. ** the last lock is cleared.
  24752. */
  24753. setPendingFd(pFile);
  24754. }
  24755. releaseInodeInfo(pFile);
  24756. sqlite3_free(pFile->lockingContext);
  24757. rc = closeUnixFile(id);
  24758. unixLeaveMutex();
  24759. }
  24760. return rc;
  24761. }
  24762. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  24763. /*
  24764. ** The code above is the AFP lock implementation. The code is specific
  24765. ** to MacOSX and does not work on other unix platforms. No alternative
  24766. ** is available. If you don't compile for a mac, then the "unix-afp"
  24767. ** VFS is not available.
  24768. **
  24769. ********************* End of the AFP lock implementation **********************
  24770. ******************************************************************************/
  24771. /******************************************************************************
  24772. *************************** Begin NFS Locking ********************************/
  24773. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  24774. /*
  24775. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24776. ** must be either NO_LOCK or SHARED_LOCK.
  24777. **
  24778. ** If the locking level of the file descriptor is already at or below
  24779. ** the requested locking level, this routine is a no-op.
  24780. */
  24781. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  24782. return posixUnlock(id, eFileLock, 1);
  24783. }
  24784. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  24785. /*
  24786. ** The code above is the NFS lock implementation. The code is specific
  24787. ** to MacOSX and does not work on other unix platforms. No alternative
  24788. ** is available.
  24789. **
  24790. ********************* End of the NFS lock implementation **********************
  24791. ******************************************************************************/
  24792. /******************************************************************************
  24793. **************** Non-locking sqlite3_file methods *****************************
  24794. **
  24795. ** The next division contains implementations for all methods of the
  24796. ** sqlite3_file object other than the locking methods. The locking
  24797. ** methods were defined in divisions above (one locking method per
  24798. ** division). Those methods that are common to all locking modes
  24799. ** are gather together into this division.
  24800. */
  24801. /*
  24802. ** Seek to the offset passed as the second argument, then read cnt
  24803. ** bytes into pBuf. Return the number of bytes actually read.
  24804. **
  24805. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  24806. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  24807. ** one system to another. Since SQLite does not define USE_PREAD
  24808. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  24809. ** See tickets #2741 and #2681.
  24810. **
  24811. ** To avoid stomping the errno value on a failed read the lastErrno value
  24812. ** is set before returning.
  24813. */
  24814. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  24815. int got;
  24816. int prior = 0;
  24817. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  24818. i64 newOffset;
  24819. #endif
  24820. TIMER_START;
  24821. assert( cnt==(cnt&0x1ffff) );
  24822. assert( id->h>2 );
  24823. cnt &= 0x1ffff;
  24824. do{
  24825. #if defined(USE_PREAD)
  24826. got = osPread(id->h, pBuf, cnt, offset);
  24827. SimulateIOError( got = -1 );
  24828. #elif defined(USE_PREAD64)
  24829. got = osPread64(id->h, pBuf, cnt, offset);
  24830. SimulateIOError( got = -1 );
  24831. #else
  24832. newOffset = lseek(id->h, offset, SEEK_SET);
  24833. SimulateIOError( newOffset-- );
  24834. if( newOffset!=offset ){
  24835. if( newOffset == -1 ){
  24836. ((unixFile*)id)->lastErrno = errno;
  24837. }else{
  24838. ((unixFile*)id)->lastErrno = 0;
  24839. }
  24840. return -1;
  24841. }
  24842. got = osRead(id->h, pBuf, cnt);
  24843. #endif
  24844. if( got==cnt ) break;
  24845. if( got<0 ){
  24846. if( errno==EINTR ){ got = 1; continue; }
  24847. prior = 0;
  24848. ((unixFile*)id)->lastErrno = errno;
  24849. break;
  24850. }else if( got>0 ){
  24851. cnt -= got;
  24852. offset += got;
  24853. prior += got;
  24854. pBuf = (void*)(got + (char*)pBuf);
  24855. }
  24856. }while( got>0 );
  24857. TIMER_END;
  24858. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  24859. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  24860. return got+prior;
  24861. }
  24862. /*
  24863. ** Read data from a file into a buffer. Return SQLITE_OK if all
  24864. ** bytes were read successfully and SQLITE_IOERR if anything goes
  24865. ** wrong.
  24866. */
  24867. static int unixRead(
  24868. sqlite3_file *id,
  24869. void *pBuf,
  24870. int amt,
  24871. sqlite3_int64 offset
  24872. ){
  24873. unixFile *pFile = (unixFile *)id;
  24874. int got;
  24875. assert( id );
  24876. assert( offset>=0 );
  24877. assert( amt>0 );
  24878. /* If this is a database file (not a journal, master-journal or temp
  24879. ** file), the bytes in the locking range should never be read or written. */
  24880. #if 0
  24881. assert( pFile->pUnused==0
  24882. || offset>=PENDING_BYTE+512
  24883. || offset+amt<=PENDING_BYTE
  24884. );
  24885. #endif
  24886. #if SQLITE_MAX_MMAP_SIZE>0
  24887. /* Deal with as much of this read request as possible by transfering
  24888. ** data from the memory mapping using memcpy(). */
  24889. if( offset<pFile->mmapSize ){
  24890. if( offset+amt <= pFile->mmapSize ){
  24891. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  24892. return SQLITE_OK;
  24893. }else{
  24894. int nCopy = pFile->mmapSize - offset;
  24895. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  24896. pBuf = &((u8 *)pBuf)[nCopy];
  24897. amt -= nCopy;
  24898. offset += nCopy;
  24899. }
  24900. }
  24901. #endif
  24902. got = seekAndRead(pFile, offset, pBuf, amt);
  24903. if( got==amt ){
  24904. return SQLITE_OK;
  24905. }else if( got<0 ){
  24906. /* lastErrno set by seekAndRead */
  24907. return SQLITE_IOERR_READ;
  24908. }else{
  24909. pFile->lastErrno = 0; /* not a system error */
  24910. /* Unread parts of the buffer must be zero-filled */
  24911. memset(&((char*)pBuf)[got], 0, amt-got);
  24912. return SQLITE_IOERR_SHORT_READ;
  24913. }
  24914. }
  24915. /*
  24916. ** Attempt to seek the file-descriptor passed as the first argument to
  24917. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  24918. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  24919. ** return the actual number of bytes written (which may be less than
  24920. ** nBuf).
  24921. */
  24922. static int seekAndWriteFd(
  24923. int fd, /* File descriptor to write to */
  24924. i64 iOff, /* File offset to begin writing at */
  24925. const void *pBuf, /* Copy data from this buffer to the file */
  24926. int nBuf, /* Size of buffer pBuf in bytes */
  24927. int *piErrno /* OUT: Error number if error occurs */
  24928. ){
  24929. int rc = 0; /* Value returned by system call */
  24930. assert( nBuf==(nBuf&0x1ffff) );
  24931. assert( fd>2 );
  24932. nBuf &= 0x1ffff;
  24933. TIMER_START;
  24934. #if defined(USE_PREAD)
  24935. do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  24936. #elif defined(USE_PREAD64)
  24937. do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  24938. #else
  24939. do{
  24940. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  24941. SimulateIOError( iSeek-- );
  24942. if( iSeek!=iOff ){
  24943. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  24944. return -1;
  24945. }
  24946. rc = osWrite(fd, pBuf, nBuf);
  24947. }while( rc<0 && errno==EINTR );
  24948. #endif
  24949. TIMER_END;
  24950. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  24951. if( rc<0 && piErrno ) *piErrno = errno;
  24952. return rc;
  24953. }
  24954. /*
  24955. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  24956. ** Return the number of bytes actually read. Update the offset.
  24957. **
  24958. ** To avoid stomping the errno value on a failed write the lastErrno value
  24959. ** is set before returning.
  24960. */
  24961. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  24962. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  24963. }
  24964. /*
  24965. ** Write data from a buffer into a file. Return SQLITE_OK on success
  24966. ** or some other error code on failure.
  24967. */
  24968. static int unixWrite(
  24969. sqlite3_file *id,
  24970. const void *pBuf,
  24971. int amt,
  24972. sqlite3_int64 offset
  24973. ){
  24974. unixFile *pFile = (unixFile*)id;
  24975. int wrote = 0;
  24976. assert( id );
  24977. assert( amt>0 );
  24978. /* If this is a database file (not a journal, master-journal or temp
  24979. ** file), the bytes in the locking range should never be read or written. */
  24980. #if 0
  24981. assert( pFile->pUnused==0
  24982. || offset>=PENDING_BYTE+512
  24983. || offset+amt<=PENDING_BYTE
  24984. );
  24985. #endif
  24986. #ifdef SQLITE_DEBUG
  24987. /* If we are doing a normal write to a database file (as opposed to
  24988. ** doing a hot-journal rollback or a write to some file other than a
  24989. ** normal database file) then record the fact that the database
  24990. ** has changed. If the transaction counter is modified, record that
  24991. ** fact too.
  24992. */
  24993. if( pFile->inNormalWrite ){
  24994. pFile->dbUpdate = 1; /* The database has been modified */
  24995. if( offset<=24 && offset+amt>=27 ){
  24996. int rc;
  24997. char oldCntr[4];
  24998. SimulateIOErrorBenign(1);
  24999. rc = seekAndRead(pFile, 24, oldCntr, 4);
  25000. SimulateIOErrorBenign(0);
  25001. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  25002. pFile->transCntrChng = 1; /* The transaction counter has changed */
  25003. }
  25004. }
  25005. }
  25006. #endif
  25007. #if SQLITE_MAX_MMAP_SIZE>0
  25008. /* Deal with as much of this write request as possible by transfering
  25009. ** data from the memory mapping using memcpy(). */
  25010. if( offset<pFile->mmapSize ){
  25011. if( offset+amt <= pFile->mmapSize ){
  25012. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  25013. return SQLITE_OK;
  25014. }else{
  25015. int nCopy = pFile->mmapSize - offset;
  25016. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  25017. pBuf = &((u8 *)pBuf)[nCopy];
  25018. amt -= nCopy;
  25019. offset += nCopy;
  25020. }
  25021. }
  25022. #endif
  25023. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  25024. amt -= wrote;
  25025. offset += wrote;
  25026. pBuf = &((char*)pBuf)[wrote];
  25027. }
  25028. SimulateIOError(( wrote=(-1), amt=1 ));
  25029. SimulateDiskfullError(( wrote=0, amt=1 ));
  25030. if( amt>0 ){
  25031. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  25032. /* lastErrno set by seekAndWrite */
  25033. return SQLITE_IOERR_WRITE;
  25034. }else{
  25035. pFile->lastErrno = 0; /* not a system error */
  25036. return SQLITE_FULL;
  25037. }
  25038. }
  25039. return SQLITE_OK;
  25040. }
  25041. #ifdef SQLITE_TEST
  25042. /*
  25043. ** Count the number of fullsyncs and normal syncs. This is used to test
  25044. ** that syncs and fullsyncs are occurring at the right times.
  25045. */
  25046. SQLITE_API int sqlite3_sync_count = 0;
  25047. SQLITE_API int sqlite3_fullsync_count = 0;
  25048. #endif
  25049. /*
  25050. ** We do not trust systems to provide a working fdatasync(). Some do.
  25051. ** Others do no. To be safe, we will stick with the (slightly slower)
  25052. ** fsync(). If you know that your system does support fdatasync() correctly,
  25053. ** then simply compile with -Dfdatasync=fdatasync
  25054. */
  25055. #if !defined(fdatasync)
  25056. # define fdatasync fsync
  25057. #endif
  25058. /*
  25059. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  25060. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  25061. ** only available on Mac OS X. But that could change.
  25062. */
  25063. #ifdef F_FULLFSYNC
  25064. # define HAVE_FULLFSYNC 1
  25065. #else
  25066. # define HAVE_FULLFSYNC 0
  25067. #endif
  25068. /*
  25069. ** The fsync() system call does not work as advertised on many
  25070. ** unix systems. The following procedure is an attempt to make
  25071. ** it work better.
  25072. **
  25073. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  25074. ** for testing when we want to run through the test suite quickly.
  25075. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  25076. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  25077. ** or power failure will likely corrupt the database file.
  25078. **
  25079. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  25080. ** The idea behind dataOnly is that it should only write the file content
  25081. ** to disk, not the inode. We only set dataOnly if the file size is
  25082. ** unchanged since the file size is part of the inode. However,
  25083. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  25084. ** file size has changed. The only real difference between fdatasync()
  25085. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  25086. ** inode if the mtime or owner or other inode attributes have changed.
  25087. ** We only care about the file size, not the other file attributes, so
  25088. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  25089. ** So, we always use fdatasync() if it is available, regardless of
  25090. ** the value of the dataOnly flag.
  25091. */
  25092. static int full_fsync(int fd, int fullSync, int dataOnly){
  25093. int rc;
  25094. /* The following "ifdef/elif/else/" block has the same structure as
  25095. ** the one below. It is replicated here solely to avoid cluttering
  25096. ** up the real code with the UNUSED_PARAMETER() macros.
  25097. */
  25098. #ifdef SQLITE_NO_SYNC
  25099. UNUSED_PARAMETER(fd);
  25100. UNUSED_PARAMETER(fullSync);
  25101. UNUSED_PARAMETER(dataOnly);
  25102. #elif HAVE_FULLFSYNC
  25103. UNUSED_PARAMETER(dataOnly);
  25104. #else
  25105. UNUSED_PARAMETER(fullSync);
  25106. UNUSED_PARAMETER(dataOnly);
  25107. #endif
  25108. /* Record the number of times that we do a normal fsync() and
  25109. ** FULLSYNC. This is used during testing to verify that this procedure
  25110. ** gets called with the correct arguments.
  25111. */
  25112. #ifdef SQLITE_TEST
  25113. if( fullSync ) sqlite3_fullsync_count++;
  25114. sqlite3_sync_count++;
  25115. #endif
  25116. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  25117. ** no-op
  25118. */
  25119. #ifdef SQLITE_NO_SYNC
  25120. rc = SQLITE_OK;
  25121. #elif HAVE_FULLFSYNC
  25122. if( fullSync ){
  25123. rc = osFcntl(fd, F_FULLFSYNC, 0);
  25124. }else{
  25125. rc = 1;
  25126. }
  25127. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  25128. ** It shouldn't be possible for fullfsync to fail on the local
  25129. ** file system (on OSX), so failure indicates that FULLFSYNC
  25130. ** isn't supported for this file system. So, attempt an fsync
  25131. ** and (for now) ignore the overhead of a superfluous fcntl call.
  25132. ** It'd be better to detect fullfsync support once and avoid
  25133. ** the fcntl call every time sync is called.
  25134. */
  25135. if( rc ) rc = fsync(fd);
  25136. #elif defined(__APPLE__)
  25137. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  25138. ** so currently we default to the macro that redefines fdatasync to fsync
  25139. */
  25140. rc = fsync(fd);
  25141. #else
  25142. rc = fdatasync(fd);
  25143. #if OS_VXWORKS
  25144. if( rc==-1 && errno==ENOTSUP ){
  25145. rc = fsync(fd);
  25146. }
  25147. #endif /* OS_VXWORKS */
  25148. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  25149. if( OS_VXWORKS && rc!= -1 ){
  25150. rc = 0;
  25151. }
  25152. return rc;
  25153. }
  25154. /*
  25155. ** Open a file descriptor to the directory containing file zFilename.
  25156. ** If successful, *pFd is set to the opened file descriptor and
  25157. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  25158. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  25159. ** value.
  25160. **
  25161. ** The directory file descriptor is used for only one thing - to
  25162. ** fsync() a directory to make sure file creation and deletion events
  25163. ** are flushed to disk. Such fsyncs are not needed on newer
  25164. ** journaling filesystems, but are required on older filesystems.
  25165. **
  25166. ** This routine can be overridden using the xSetSysCall interface.
  25167. ** The ability to override this routine was added in support of the
  25168. ** chromium sandbox. Opening a directory is a security risk (we are
  25169. ** told) so making it overrideable allows the chromium sandbox to
  25170. ** replace this routine with a harmless no-op. To make this routine
  25171. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  25172. ** *pFd set to a negative number.
  25173. **
  25174. ** If SQLITE_OK is returned, the caller is responsible for closing
  25175. ** the file descriptor *pFd using close().
  25176. */
  25177. static int openDirectory(const char *zFilename, int *pFd){
  25178. int ii;
  25179. int fd = -1;
  25180. char zDirname[MAX_PATHNAME+1];
  25181. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  25182. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  25183. if( ii>0 ){
  25184. zDirname[ii] = '\0';
  25185. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  25186. if( fd>=0 ){
  25187. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  25188. }
  25189. }
  25190. *pFd = fd;
  25191. return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  25192. }
  25193. /*
  25194. ** Make sure all writes to a particular file are committed to disk.
  25195. **
  25196. ** If dataOnly==0 then both the file itself and its metadata (file
  25197. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  25198. ** file data is synced.
  25199. **
  25200. ** Under Unix, also make sure that the directory entry for the file
  25201. ** has been created by fsync-ing the directory that contains the file.
  25202. ** If we do not do this and we encounter a power failure, the directory
  25203. ** entry for the journal might not exist after we reboot. The next
  25204. ** SQLite to access the file will not know that the journal exists (because
  25205. ** the directory entry for the journal was never created) and the transaction
  25206. ** will not roll back - possibly leading to database corruption.
  25207. */
  25208. static int unixSync(sqlite3_file *id, int flags){
  25209. int rc;
  25210. unixFile *pFile = (unixFile*)id;
  25211. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  25212. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  25213. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  25214. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  25215. || (flags&0x0F)==SQLITE_SYNC_FULL
  25216. );
  25217. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  25218. ** line is to test that doing so does not cause any problems.
  25219. */
  25220. SimulateDiskfullError( return SQLITE_FULL );
  25221. assert( pFile );
  25222. OSTRACE(("SYNC %-3d\n", pFile->h));
  25223. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  25224. SimulateIOError( rc=1 );
  25225. if( rc ){
  25226. pFile->lastErrno = errno;
  25227. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  25228. }
  25229. /* Also fsync the directory containing the file if the DIRSYNC flag
  25230. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  25231. ** are unable to fsync a directory, so ignore errors on the fsync.
  25232. */
  25233. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  25234. int dirfd;
  25235. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  25236. HAVE_FULLFSYNC, isFullsync));
  25237. rc = osOpenDirectory(pFile->zPath, &dirfd);
  25238. if( rc==SQLITE_OK && dirfd>=0 ){
  25239. full_fsync(dirfd, 0, 0);
  25240. robust_close(pFile, dirfd, __LINE__);
  25241. }else if( rc==SQLITE_CANTOPEN ){
  25242. rc = SQLITE_OK;
  25243. }
  25244. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  25245. }
  25246. return rc;
  25247. }
  25248. /*
  25249. ** Truncate an open file to a specified size
  25250. */
  25251. static int unixTruncate(sqlite3_file *id, i64 nByte){
  25252. unixFile *pFile = (unixFile *)id;
  25253. int rc;
  25254. assert( pFile );
  25255. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  25256. /* If the user has configured a chunk-size for this file, truncate the
  25257. ** file so that it consists of an integer number of chunks (i.e. the
  25258. ** actual file size after the operation may be larger than the requested
  25259. ** size).
  25260. */
  25261. if( pFile->szChunk>0 ){
  25262. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  25263. }
  25264. rc = robust_ftruncate(pFile->h, (off_t)nByte);
  25265. if( rc ){
  25266. pFile->lastErrno = errno;
  25267. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25268. }else{
  25269. #ifdef SQLITE_DEBUG
  25270. /* If we are doing a normal write to a database file (as opposed to
  25271. ** doing a hot-journal rollback or a write to some file other than a
  25272. ** normal database file) and we truncate the file to zero length,
  25273. ** that effectively updates the change counter. This might happen
  25274. ** when restoring a database using the backup API from a zero-length
  25275. ** source.
  25276. */
  25277. if( pFile->inNormalWrite && nByte==0 ){
  25278. pFile->transCntrChng = 1;
  25279. }
  25280. #endif
  25281. #if SQLITE_MAX_MMAP_SIZE>0
  25282. /* If the file was just truncated to a size smaller than the currently
  25283. ** mapped region, reduce the effective mapping size as well. SQLite will
  25284. ** use read() and write() to access data beyond this point from now on.
  25285. */
  25286. if( nByte<pFile->mmapSize ){
  25287. pFile->mmapSize = nByte;
  25288. }
  25289. #endif
  25290. return SQLITE_OK;
  25291. }
  25292. }
  25293. /*
  25294. ** Determine the current size of a file in bytes
  25295. */
  25296. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  25297. int rc;
  25298. struct stat buf;
  25299. assert( id );
  25300. rc = osFstat(((unixFile*)id)->h, &buf);
  25301. SimulateIOError( rc=1 );
  25302. if( rc!=0 ){
  25303. ((unixFile*)id)->lastErrno = errno;
  25304. return SQLITE_IOERR_FSTAT;
  25305. }
  25306. *pSize = buf.st_size;
  25307. /* When opening a zero-size database, the findInodeInfo() procedure
  25308. ** writes a single byte into that file in order to work around a bug
  25309. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  25310. ** layers, we need to report this file size as zero even though it is
  25311. ** really 1. Ticket #3260.
  25312. */
  25313. if( *pSize==1 ) *pSize = 0;
  25314. return SQLITE_OK;
  25315. }
  25316. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25317. /*
  25318. ** Handler for proxy-locking file-control verbs. Defined below in the
  25319. ** proxying locking division.
  25320. */
  25321. static int proxyFileControl(sqlite3_file*,int,void*);
  25322. #endif
  25323. /*
  25324. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  25325. ** file-control operation. Enlarge the database to nBytes in size
  25326. ** (rounded up to the next chunk-size). If the database is already
  25327. ** nBytes or larger, this routine is a no-op.
  25328. */
  25329. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  25330. if( pFile->szChunk>0 ){
  25331. i64 nSize; /* Required file size */
  25332. struct stat buf; /* Used to hold return values of fstat() */
  25333. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  25334. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  25335. if( nSize>(i64)buf.st_size ){
  25336. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  25337. /* The code below is handling the return value of osFallocate()
  25338. ** correctly. posix_fallocate() is defined to "returns zero on success,
  25339. ** or an error number on failure". See the manpage for details. */
  25340. int err;
  25341. do{
  25342. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  25343. }while( err==EINTR );
  25344. if( err ) return SQLITE_IOERR_WRITE;
  25345. #else
  25346. /* If the OS does not have posix_fallocate(), fake it. First use
  25347. ** ftruncate() to set the file size, then write a single byte to
  25348. ** the last byte in each block within the extended region. This
  25349. ** is the same technique used by glibc to implement posix_fallocate()
  25350. ** on systems that do not have a real fallocate() system call.
  25351. */
  25352. int nBlk = buf.st_blksize; /* File-system block size */
  25353. i64 iWrite; /* Next offset to write to */
  25354. if( robust_ftruncate(pFile->h, nSize) ){
  25355. pFile->lastErrno = errno;
  25356. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25357. }
  25358. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  25359. while( iWrite<nSize ){
  25360. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  25361. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  25362. iWrite += nBlk;
  25363. }
  25364. #endif
  25365. }
  25366. }
  25367. #if SQLITE_MAX_MMAP_SIZE>0
  25368. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  25369. int rc;
  25370. if( pFile->szChunk<=0 ){
  25371. if( robust_ftruncate(pFile->h, nByte) ){
  25372. pFile->lastErrno = errno;
  25373. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25374. }
  25375. }
  25376. rc = unixMapfile(pFile, nByte);
  25377. return rc;
  25378. }
  25379. #endif
  25380. return SQLITE_OK;
  25381. }
  25382. /*
  25383. ** If *pArg is inititially negative then this is a query. Set *pArg to
  25384. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  25385. **
  25386. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  25387. */
  25388. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  25389. if( *pArg<0 ){
  25390. *pArg = (pFile->ctrlFlags & mask)!=0;
  25391. }else if( (*pArg)==0 ){
  25392. pFile->ctrlFlags &= ~mask;
  25393. }else{
  25394. pFile->ctrlFlags |= mask;
  25395. }
  25396. }
  25397. /* Forward declaration */
  25398. static int unixGetTempname(int nBuf, char *zBuf);
  25399. /*
  25400. ** Information and control of an open file handle.
  25401. */
  25402. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  25403. unixFile *pFile = (unixFile*)id;
  25404. switch( op ){
  25405. case SQLITE_FCNTL_LOCKSTATE: {
  25406. *(int*)pArg = pFile->eFileLock;
  25407. return SQLITE_OK;
  25408. }
  25409. case SQLITE_LAST_ERRNO: {
  25410. *(int*)pArg = pFile->lastErrno;
  25411. return SQLITE_OK;
  25412. }
  25413. case SQLITE_FCNTL_CHUNK_SIZE: {
  25414. pFile->szChunk = *(int *)pArg;
  25415. return SQLITE_OK;
  25416. }
  25417. case SQLITE_FCNTL_SIZE_HINT: {
  25418. int rc;
  25419. SimulateIOErrorBenign(1);
  25420. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  25421. SimulateIOErrorBenign(0);
  25422. return rc;
  25423. }
  25424. case SQLITE_FCNTL_PERSIST_WAL: {
  25425. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  25426. return SQLITE_OK;
  25427. }
  25428. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  25429. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  25430. return SQLITE_OK;
  25431. }
  25432. case SQLITE_FCNTL_VFSNAME: {
  25433. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  25434. return SQLITE_OK;
  25435. }
  25436. case SQLITE_FCNTL_TEMPFILENAME: {
  25437. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  25438. if( zTFile ){
  25439. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  25440. *(char**)pArg = zTFile;
  25441. }
  25442. return SQLITE_OK;
  25443. }
  25444. #if SQLITE_MAX_MMAP_SIZE>0
  25445. case SQLITE_FCNTL_MMAP_SIZE: {
  25446. i64 newLimit = *(i64*)pArg;
  25447. int rc = SQLITE_OK;
  25448. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  25449. newLimit = sqlite3GlobalConfig.mxMmap;
  25450. }
  25451. *(i64*)pArg = pFile->mmapSizeMax;
  25452. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  25453. pFile->mmapSizeMax = newLimit;
  25454. if( pFile->mmapSize>0 ){
  25455. unixUnmapfile(pFile);
  25456. rc = unixMapfile(pFile, -1);
  25457. }
  25458. }
  25459. return rc;
  25460. }
  25461. #endif
  25462. #ifdef SQLITE_DEBUG
  25463. /* The pager calls this method to signal that it has done
  25464. ** a rollback and that the database is therefore unchanged and
  25465. ** it hence it is OK for the transaction change counter to be
  25466. ** unchanged.
  25467. */
  25468. case SQLITE_FCNTL_DB_UNCHANGED: {
  25469. ((unixFile*)id)->dbUpdate = 0;
  25470. return SQLITE_OK;
  25471. }
  25472. #endif
  25473. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25474. case SQLITE_SET_LOCKPROXYFILE:
  25475. case SQLITE_GET_LOCKPROXYFILE: {
  25476. return proxyFileControl(id,op,pArg);
  25477. }
  25478. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  25479. }
  25480. return SQLITE_NOTFOUND;
  25481. }
  25482. /*
  25483. ** Return the sector size in bytes of the underlying block device for
  25484. ** the specified file. This is almost always 512 bytes, but may be
  25485. ** larger for some devices.
  25486. **
  25487. ** SQLite code assumes this function cannot fail. It also assumes that
  25488. ** if two files are created in the same file-system directory (i.e.
  25489. ** a database and its journal file) that the sector size will be the
  25490. ** same for both.
  25491. */
  25492. #ifndef __QNXNTO__
  25493. static int unixSectorSize(sqlite3_file *NotUsed){
  25494. UNUSED_PARAMETER(NotUsed);
  25495. return SQLITE_DEFAULT_SECTOR_SIZE;
  25496. }
  25497. #endif
  25498. /*
  25499. ** The following version of unixSectorSize() is optimized for QNX.
  25500. */
  25501. #ifdef __QNXNTO__
  25502. #include <sys/dcmd_blk.h>
  25503. #include <sys/statvfs.h>
  25504. static int unixSectorSize(sqlite3_file *id){
  25505. unixFile *pFile = (unixFile*)id;
  25506. if( pFile->sectorSize == 0 ){
  25507. struct statvfs fsInfo;
  25508. /* Set defaults for non-supported filesystems */
  25509. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  25510. pFile->deviceCharacteristics = 0;
  25511. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  25512. return pFile->sectorSize;
  25513. }
  25514. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  25515. pFile->sectorSize = fsInfo.f_bsize;
  25516. pFile->deviceCharacteristics =
  25517. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  25518. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25519. ** the write succeeds */
  25520. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25521. ** so it is ordered */
  25522. 0;
  25523. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  25524. pFile->sectorSize = fsInfo.f_bsize;
  25525. pFile->deviceCharacteristics =
  25526. /* etfs cluster size writes are atomic */
  25527. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  25528. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25529. ** the write succeeds */
  25530. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25531. ** so it is ordered */
  25532. 0;
  25533. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  25534. pFile->sectorSize = fsInfo.f_bsize;
  25535. pFile->deviceCharacteristics =
  25536. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  25537. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25538. ** the write succeeds */
  25539. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25540. ** so it is ordered */
  25541. 0;
  25542. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  25543. pFile->sectorSize = fsInfo.f_bsize;
  25544. pFile->deviceCharacteristics =
  25545. /* full bitset of atomics from max sector size and smaller */
  25546. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  25547. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25548. ** so it is ordered */
  25549. 0;
  25550. }else if( strstr(fsInfo.f_basetype, "dos") ){
  25551. pFile->sectorSize = fsInfo.f_bsize;
  25552. pFile->deviceCharacteristics =
  25553. /* full bitset of atomics from max sector size and smaller */
  25554. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  25555. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25556. ** so it is ordered */
  25557. 0;
  25558. }else{
  25559. pFile->deviceCharacteristics =
  25560. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  25561. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25562. ** the write succeeds */
  25563. 0;
  25564. }
  25565. }
  25566. /* Last chance verification. If the sector size isn't a multiple of 512
  25567. ** then it isn't valid.*/
  25568. if( pFile->sectorSize % 512 != 0 ){
  25569. pFile->deviceCharacteristics = 0;
  25570. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  25571. }
  25572. return pFile->sectorSize;
  25573. }
  25574. #endif /* __QNXNTO__ */
  25575. /*
  25576. ** Return the device characteristics for the file.
  25577. **
  25578. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  25579. ** However, that choice is contraversial since technically the underlying
  25580. ** file system does not always provide powersafe overwrites. (In other
  25581. ** words, after a power-loss event, parts of the file that were never
  25582. ** written might end up being altered.) However, non-PSOW behavior is very,
  25583. ** very rare. And asserting PSOW makes a large reduction in the amount
  25584. ** of required I/O for journaling, since a lot of padding is eliminated.
  25585. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  25586. ** available to turn it off and URI query parameter available to turn it off.
  25587. */
  25588. static int unixDeviceCharacteristics(sqlite3_file *id){
  25589. unixFile *p = (unixFile*)id;
  25590. int rc = 0;
  25591. #ifdef __QNXNTO__
  25592. if( p->sectorSize==0 ) unixSectorSize(id);
  25593. rc = p->deviceCharacteristics;
  25594. #endif
  25595. if( p->ctrlFlags & UNIXFILE_PSOW ){
  25596. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  25597. }
  25598. return rc;
  25599. }
  25600. #ifndef SQLITE_OMIT_WAL
  25601. /*
  25602. ** Object used to represent an shared memory buffer.
  25603. **
  25604. ** When multiple threads all reference the same wal-index, each thread
  25605. ** has its own unixShm object, but they all point to a single instance
  25606. ** of this unixShmNode object. In other words, each wal-index is opened
  25607. ** only once per process.
  25608. **
  25609. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  25610. ** We could coalesce this object into unixInodeInfo, but that would mean
  25611. ** every open file that does not use shared memory (in other words, most
  25612. ** open files) would have to carry around this extra information. So
  25613. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  25614. ** and the unixShmNode object is created only when needed.
  25615. **
  25616. ** unixMutexHeld() must be true when creating or destroying
  25617. ** this object or while reading or writing the following fields:
  25618. **
  25619. ** nRef
  25620. **
  25621. ** The following fields are read-only after the object is created:
  25622. **
  25623. ** fid
  25624. ** zFilename
  25625. **
  25626. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  25627. ** unixMutexHeld() is true when reading or writing any other field
  25628. ** in this structure.
  25629. */
  25630. struct unixShmNode {
  25631. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  25632. sqlite3_mutex *mutex; /* Mutex to access this object */
  25633. char *zFilename; /* Name of the mmapped file */
  25634. int h; /* Open file descriptor */
  25635. int szRegion; /* Size of shared-memory regions */
  25636. u16 nRegion; /* Size of array apRegion */
  25637. u8 isReadonly; /* True if read-only */
  25638. char **apRegion; /* Array of mapped shared-memory regions */
  25639. int nRef; /* Number of unixShm objects pointing to this */
  25640. unixShm *pFirst; /* All unixShm objects pointing to this */
  25641. #ifdef SQLITE_DEBUG
  25642. u8 exclMask; /* Mask of exclusive locks held */
  25643. u8 sharedMask; /* Mask of shared locks held */
  25644. u8 nextShmId; /* Next available unixShm.id value */
  25645. #endif
  25646. };
  25647. /*
  25648. ** Structure used internally by this VFS to record the state of an
  25649. ** open shared memory connection.
  25650. **
  25651. ** The following fields are initialized when this object is created and
  25652. ** are read-only thereafter:
  25653. **
  25654. ** unixShm.pFile
  25655. ** unixShm.id
  25656. **
  25657. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  25658. ** while accessing any read/write fields.
  25659. */
  25660. struct unixShm {
  25661. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  25662. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  25663. u8 hasMutex; /* True if holding the unixShmNode mutex */
  25664. u8 id; /* Id of this connection within its unixShmNode */
  25665. u16 sharedMask; /* Mask of shared locks held */
  25666. u16 exclMask; /* Mask of exclusive locks held */
  25667. };
  25668. /*
  25669. ** Constants used for locking
  25670. */
  25671. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  25672. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  25673. /*
  25674. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  25675. **
  25676. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  25677. ** otherwise.
  25678. */
  25679. static int unixShmSystemLock(
  25680. unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
  25681. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  25682. int ofst, /* First byte of the locking range */
  25683. int n /* Number of bytes to lock */
  25684. ){
  25685. struct flock f; /* The posix advisory locking structure */
  25686. int rc = SQLITE_OK; /* Result code form fcntl() */
  25687. /* Access to the unixShmNode object is serialized by the caller */
  25688. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  25689. /* Shared locks never span more than one byte */
  25690. assert( n==1 || lockType!=F_RDLCK );
  25691. /* Locks are within range */
  25692. assert( n>=1 && n<SQLITE_SHM_NLOCK );
  25693. if( pShmNode->h>=0 ){
  25694. /* Initialize the locking parameters */
  25695. memset(&f, 0, sizeof(f));
  25696. f.l_type = lockType;
  25697. f.l_whence = SEEK_SET;
  25698. f.l_start = ofst;
  25699. f.l_len = n;
  25700. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  25701. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  25702. }
  25703. /* Update the global lock state and do debug tracing */
  25704. #ifdef SQLITE_DEBUG
  25705. { u16 mask;
  25706. OSTRACE(("SHM-LOCK "));
  25707. mask = (1<<(ofst+n)) - (1<<ofst);
  25708. if( rc==SQLITE_OK ){
  25709. if( lockType==F_UNLCK ){
  25710. OSTRACE(("unlock %d ok", ofst));
  25711. pShmNode->exclMask &= ~mask;
  25712. pShmNode->sharedMask &= ~mask;
  25713. }else if( lockType==F_RDLCK ){
  25714. OSTRACE(("read-lock %d ok", ofst));
  25715. pShmNode->exclMask &= ~mask;
  25716. pShmNode->sharedMask |= mask;
  25717. }else{
  25718. assert( lockType==F_WRLCK );
  25719. OSTRACE(("write-lock %d ok", ofst));
  25720. pShmNode->exclMask |= mask;
  25721. pShmNode->sharedMask &= ~mask;
  25722. }
  25723. }else{
  25724. if( lockType==F_UNLCK ){
  25725. OSTRACE(("unlock %d failed", ofst));
  25726. }else if( lockType==F_RDLCK ){
  25727. OSTRACE(("read-lock failed"));
  25728. }else{
  25729. assert( lockType==F_WRLCK );
  25730. OSTRACE(("write-lock %d failed", ofst));
  25731. }
  25732. }
  25733. OSTRACE((" - afterwards %03x,%03x\n",
  25734. pShmNode->sharedMask, pShmNode->exclMask));
  25735. }
  25736. #endif
  25737. return rc;
  25738. }
  25739. /*
  25740. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  25741. **
  25742. ** This is not a VFS shared-memory method; it is a utility function called
  25743. ** by VFS shared-memory methods.
  25744. */
  25745. static void unixShmPurge(unixFile *pFd){
  25746. unixShmNode *p = pFd->pInode->pShmNode;
  25747. assert( unixMutexHeld() );
  25748. if( p && p->nRef==0 ){
  25749. int i;
  25750. assert( p->pInode==pFd->pInode );
  25751. sqlite3_mutex_free(p->mutex);
  25752. for(i=0; i<p->nRegion; i++){
  25753. if( p->h>=0 ){
  25754. osMunmap(p->apRegion[i], p->szRegion);
  25755. }else{
  25756. sqlite3_free(p->apRegion[i]);
  25757. }
  25758. }
  25759. sqlite3_free(p->apRegion);
  25760. if( p->h>=0 ){
  25761. robust_close(pFd, p->h, __LINE__);
  25762. p->h = -1;
  25763. }
  25764. p->pInode->pShmNode = 0;
  25765. sqlite3_free(p);
  25766. }
  25767. }
  25768. /*
  25769. ** Open a shared-memory area associated with open database file pDbFd.
  25770. ** This particular implementation uses mmapped files.
  25771. **
  25772. ** The file used to implement shared-memory is in the same directory
  25773. ** as the open database file and has the same name as the open database
  25774. ** file with the "-shm" suffix added. For example, if the database file
  25775. ** is "/home/user1/config.db" then the file that is created and mmapped
  25776. ** for shared memory will be called "/home/user1/config.db-shm".
  25777. **
  25778. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  25779. ** some other tmpfs mount. But if a file in a different directory
  25780. ** from the database file is used, then differing access permissions
  25781. ** or a chroot() might cause two different processes on the same
  25782. ** database to end up using different files for shared memory -
  25783. ** meaning that their memory would not really be shared - resulting
  25784. ** in database corruption. Nevertheless, this tmpfs file usage
  25785. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  25786. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  25787. ** option results in an incompatible build of SQLite; builds of SQLite
  25788. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  25789. ** same database file at the same time, database corruption will likely
  25790. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  25791. ** "unsupported" and may go away in a future SQLite release.
  25792. **
  25793. ** When opening a new shared-memory file, if no other instances of that
  25794. ** file are currently open, in this process or in other processes, then
  25795. ** the file must be truncated to zero length or have its header cleared.
  25796. **
  25797. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  25798. ** that means that an exclusive lock is held on the database file and
  25799. ** that no other processes are able to read or write the database. In
  25800. ** that case, we do not really need shared memory. No shared memory
  25801. ** file is created. The shared memory will be simulated with heap memory.
  25802. */
  25803. static int unixOpenSharedMemory(unixFile *pDbFd){
  25804. struct unixShm *p = 0; /* The connection to be opened */
  25805. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  25806. int rc; /* Result code */
  25807. unixInodeInfo *pInode; /* The inode of fd */
  25808. char *zShmFilename; /* Name of the file used for SHM */
  25809. int nShmFilename; /* Size of the SHM filename in bytes */
  25810. /* Allocate space for the new unixShm object. */
  25811. p = sqlite3_malloc( sizeof(*p) );
  25812. if( p==0 ) return SQLITE_NOMEM;
  25813. memset(p, 0, sizeof(*p));
  25814. assert( pDbFd->pShm==0 );
  25815. /* Check to see if a unixShmNode object already exists. Reuse an existing
  25816. ** one if present. Create a new one if necessary.
  25817. */
  25818. unixEnterMutex();
  25819. pInode = pDbFd->pInode;
  25820. pShmNode = pInode->pShmNode;
  25821. if( pShmNode==0 ){
  25822. struct stat sStat; /* fstat() info for database file */
  25823. /* Call fstat() to figure out the permissions on the database file. If
  25824. ** a new *-shm file is created, an attempt will be made to create it
  25825. ** with the same permissions.
  25826. */
  25827. if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  25828. rc = SQLITE_IOERR_FSTAT;
  25829. goto shm_open_err;
  25830. }
  25831. #ifdef SQLITE_SHM_DIRECTORY
  25832. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  25833. #else
  25834. nShmFilename = 6 + (int)strlen(pDbFd->zPath);
  25835. #endif
  25836. pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
  25837. if( pShmNode==0 ){
  25838. rc = SQLITE_NOMEM;
  25839. goto shm_open_err;
  25840. }
  25841. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  25842. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  25843. #ifdef SQLITE_SHM_DIRECTORY
  25844. sqlite3_snprintf(nShmFilename, zShmFilename,
  25845. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  25846. (u32)sStat.st_ino, (u32)sStat.st_dev);
  25847. #else
  25848. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
  25849. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  25850. #endif
  25851. pShmNode->h = -1;
  25852. pDbFd->pInode->pShmNode = pShmNode;
  25853. pShmNode->pInode = pDbFd->pInode;
  25854. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  25855. if( pShmNode->mutex==0 ){
  25856. rc = SQLITE_NOMEM;
  25857. goto shm_open_err;
  25858. }
  25859. if( pInode->bProcessLock==0 ){
  25860. int openFlags = O_RDWR | O_CREAT;
  25861. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  25862. openFlags = O_RDONLY;
  25863. pShmNode->isReadonly = 1;
  25864. }
  25865. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  25866. if( pShmNode->h<0 ){
  25867. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  25868. goto shm_open_err;
  25869. }
  25870. /* If this process is running as root, make sure that the SHM file
  25871. ** is owned by the same user that owns the original database. Otherwise,
  25872. ** the original owner will not be able to connect.
  25873. */
  25874. osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  25875. /* Check to see if another process is holding the dead-man switch.
  25876. ** If not, truncate the file to zero length.
  25877. */
  25878. rc = SQLITE_OK;
  25879. if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  25880. if( robust_ftruncate(pShmNode->h, 0) ){
  25881. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  25882. }
  25883. }
  25884. if( rc==SQLITE_OK ){
  25885. rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
  25886. }
  25887. if( rc ) goto shm_open_err;
  25888. }
  25889. }
  25890. /* Make the new connection a child of the unixShmNode */
  25891. p->pShmNode = pShmNode;
  25892. #ifdef SQLITE_DEBUG
  25893. p->id = pShmNode->nextShmId++;
  25894. #endif
  25895. pShmNode->nRef++;
  25896. pDbFd->pShm = p;
  25897. unixLeaveMutex();
  25898. /* The reference count on pShmNode has already been incremented under
  25899. ** the cover of the unixEnterMutex() mutex and the pointer from the
  25900. ** new (struct unixShm) object to the pShmNode has been set. All that is
  25901. ** left to do is to link the new object into the linked list starting
  25902. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  25903. ** mutex.
  25904. */
  25905. sqlite3_mutex_enter(pShmNode->mutex);
  25906. p->pNext = pShmNode->pFirst;
  25907. pShmNode->pFirst = p;
  25908. sqlite3_mutex_leave(pShmNode->mutex);
  25909. return SQLITE_OK;
  25910. /* Jump here on any error */
  25911. shm_open_err:
  25912. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  25913. sqlite3_free(p);
  25914. unixLeaveMutex();
  25915. return rc;
  25916. }
  25917. /*
  25918. ** This function is called to obtain a pointer to region iRegion of the
  25919. ** shared-memory associated with the database file fd. Shared-memory regions
  25920. ** are numbered starting from zero. Each shared-memory region is szRegion
  25921. ** bytes in size.
  25922. **
  25923. ** If an error occurs, an error code is returned and *pp is set to NULL.
  25924. **
  25925. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  25926. ** region has not been allocated (by any client, including one running in a
  25927. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  25928. ** bExtend is non-zero and the requested shared-memory region has not yet
  25929. ** been allocated, it is allocated by this function.
  25930. **
  25931. ** If the shared-memory region has already been allocated or is allocated by
  25932. ** this call as described above, then it is mapped into this processes
  25933. ** address space (if it is not already), *pp is set to point to the mapped
  25934. ** memory and SQLITE_OK returned.
  25935. */
  25936. static int unixShmMap(
  25937. sqlite3_file *fd, /* Handle open on database file */
  25938. int iRegion, /* Region to retrieve */
  25939. int szRegion, /* Size of regions */
  25940. int bExtend, /* True to extend file if necessary */
  25941. void volatile **pp /* OUT: Mapped memory */
  25942. ){
  25943. unixFile *pDbFd = (unixFile*)fd;
  25944. unixShm *p;
  25945. unixShmNode *pShmNode;
  25946. int rc = SQLITE_OK;
  25947. /* If the shared-memory file has not yet been opened, open it now. */
  25948. if( pDbFd->pShm==0 ){
  25949. rc = unixOpenSharedMemory(pDbFd);
  25950. if( rc!=SQLITE_OK ) return rc;
  25951. }
  25952. p = pDbFd->pShm;
  25953. pShmNode = p->pShmNode;
  25954. sqlite3_mutex_enter(pShmNode->mutex);
  25955. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  25956. assert( pShmNode->pInode==pDbFd->pInode );
  25957. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  25958. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  25959. if( pShmNode->nRegion<=iRegion ){
  25960. char **apNew; /* New apRegion[] array */
  25961. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  25962. struct stat sStat; /* Used by fstat() */
  25963. pShmNode->szRegion = szRegion;
  25964. if( pShmNode->h>=0 ){
  25965. /* The requested region is not mapped into this processes address space.
  25966. ** Check to see if it has been allocated (i.e. if the wal-index file is
  25967. ** large enough to contain the requested region).
  25968. */
  25969. if( osFstat(pShmNode->h, &sStat) ){
  25970. rc = SQLITE_IOERR_SHMSIZE;
  25971. goto shmpage_out;
  25972. }
  25973. if( sStat.st_size<nByte ){
  25974. /* The requested memory region does not exist. If bExtend is set to
  25975. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  25976. */
  25977. if( !bExtend ){
  25978. goto shmpage_out;
  25979. }
  25980. /* Alternatively, if bExtend is true, extend the file. Do this by
  25981. ** writing a single byte to the end of each (OS) page being
  25982. ** allocated or extended. Technically, we need only write to the
  25983. ** last page in order to extend the file. But writing to all new
  25984. ** pages forces the OS to allocate them immediately, which reduces
  25985. ** the chances of SIGBUS while accessing the mapped region later on.
  25986. */
  25987. else{
  25988. static const int pgsz = 4096;
  25989. int iPg;
  25990. /* Write to the last byte of each newly allocated or extended page */
  25991. assert( (nByte % pgsz)==0 );
  25992. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  25993. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
  25994. const char *zFile = pShmNode->zFilename;
  25995. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  25996. goto shmpage_out;
  25997. }
  25998. }
  25999. }
  26000. }
  26001. }
  26002. /* Map the requested memory region into this processes address space. */
  26003. apNew = (char **)sqlite3_realloc(
  26004. pShmNode->apRegion, (iRegion+1)*sizeof(char *)
  26005. );
  26006. if( !apNew ){
  26007. rc = SQLITE_IOERR_NOMEM;
  26008. goto shmpage_out;
  26009. }
  26010. pShmNode->apRegion = apNew;
  26011. while(pShmNode->nRegion<=iRegion){
  26012. void *pMem;
  26013. if( pShmNode->h>=0 ){
  26014. pMem = osMmap(0, szRegion,
  26015. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  26016. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  26017. );
  26018. if( pMem==MAP_FAILED ){
  26019. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  26020. goto shmpage_out;
  26021. }
  26022. }else{
  26023. pMem = sqlite3_malloc(szRegion);
  26024. if( pMem==0 ){
  26025. rc = SQLITE_NOMEM;
  26026. goto shmpage_out;
  26027. }
  26028. memset(pMem, 0, szRegion);
  26029. }
  26030. pShmNode->apRegion[pShmNode->nRegion] = pMem;
  26031. pShmNode->nRegion++;
  26032. }
  26033. }
  26034. shmpage_out:
  26035. if( pShmNode->nRegion>iRegion ){
  26036. *pp = pShmNode->apRegion[iRegion];
  26037. }else{
  26038. *pp = 0;
  26039. }
  26040. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  26041. sqlite3_mutex_leave(pShmNode->mutex);
  26042. return rc;
  26043. }
  26044. /*
  26045. ** Change the lock state for a shared-memory segment.
  26046. **
  26047. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  26048. ** different here than in posix. In xShmLock(), one can go from unlocked
  26049. ** to shared and back or from unlocked to exclusive and back. But one may
  26050. ** not go from shared to exclusive or from exclusive to shared.
  26051. */
  26052. static int unixShmLock(
  26053. sqlite3_file *fd, /* Database file holding the shared memory */
  26054. int ofst, /* First lock to acquire or release */
  26055. int n, /* Number of locks to acquire or release */
  26056. int flags /* What to do with the lock */
  26057. ){
  26058. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  26059. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  26060. unixShm *pX; /* For looping over all siblings */
  26061. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  26062. int rc = SQLITE_OK; /* Result code */
  26063. u16 mask; /* Mask of locks to take or release */
  26064. assert( pShmNode==pDbFd->pInode->pShmNode );
  26065. assert( pShmNode->pInode==pDbFd->pInode );
  26066. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  26067. assert( n>=1 );
  26068. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  26069. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  26070. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  26071. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  26072. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  26073. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  26074. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  26075. mask = (1<<(ofst+n)) - (1<<ofst);
  26076. assert( n>1 || mask==(1<<ofst) );
  26077. sqlite3_mutex_enter(pShmNode->mutex);
  26078. if( flags & SQLITE_SHM_UNLOCK ){
  26079. u16 allMask = 0; /* Mask of locks held by siblings */
  26080. /* See if any siblings hold this same lock */
  26081. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26082. if( pX==p ) continue;
  26083. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  26084. allMask |= pX->sharedMask;
  26085. }
  26086. /* Unlock the system-level locks */
  26087. if( (mask & allMask)==0 ){
  26088. rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  26089. }else{
  26090. rc = SQLITE_OK;
  26091. }
  26092. /* Undo the local locks */
  26093. if( rc==SQLITE_OK ){
  26094. p->exclMask &= ~mask;
  26095. p->sharedMask &= ~mask;
  26096. }
  26097. }else if( flags & SQLITE_SHM_SHARED ){
  26098. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  26099. /* Find out which shared locks are already held by sibling connections.
  26100. ** If any sibling already holds an exclusive lock, go ahead and return
  26101. ** SQLITE_BUSY.
  26102. */
  26103. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26104. if( (pX->exclMask & mask)!=0 ){
  26105. rc = SQLITE_BUSY;
  26106. break;
  26107. }
  26108. allShared |= pX->sharedMask;
  26109. }
  26110. /* Get shared locks at the system level, if necessary */
  26111. if( rc==SQLITE_OK ){
  26112. if( (allShared & mask)==0 ){
  26113. rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  26114. }else{
  26115. rc = SQLITE_OK;
  26116. }
  26117. }
  26118. /* Get the local shared locks */
  26119. if( rc==SQLITE_OK ){
  26120. p->sharedMask |= mask;
  26121. }
  26122. }else{
  26123. /* Make sure no sibling connections hold locks that will block this
  26124. ** lock. If any do, return SQLITE_BUSY right away.
  26125. */
  26126. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26127. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  26128. rc = SQLITE_BUSY;
  26129. break;
  26130. }
  26131. }
  26132. /* Get the exclusive locks at the system level. Then if successful
  26133. ** also mark the local connection as being locked.
  26134. */
  26135. if( rc==SQLITE_OK ){
  26136. rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  26137. if( rc==SQLITE_OK ){
  26138. assert( (p->sharedMask & mask)==0 );
  26139. p->exclMask |= mask;
  26140. }
  26141. }
  26142. }
  26143. sqlite3_mutex_leave(pShmNode->mutex);
  26144. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  26145. p->id, getpid(), p->sharedMask, p->exclMask));
  26146. return rc;
  26147. }
  26148. /*
  26149. ** Implement a memory barrier or memory fence on shared memory.
  26150. **
  26151. ** All loads and stores begun before the barrier must complete before
  26152. ** any load or store begun after the barrier.
  26153. */
  26154. static void unixShmBarrier(
  26155. sqlite3_file *fd /* Database file holding the shared memory */
  26156. ){
  26157. UNUSED_PARAMETER(fd);
  26158. unixEnterMutex();
  26159. unixLeaveMutex();
  26160. }
  26161. /*
  26162. ** Close a connection to shared-memory. Delete the underlying
  26163. ** storage if deleteFlag is true.
  26164. **
  26165. ** If there is no shared memory associated with the connection then this
  26166. ** routine is a harmless no-op.
  26167. */
  26168. static int unixShmUnmap(
  26169. sqlite3_file *fd, /* The underlying database file */
  26170. int deleteFlag /* Delete shared-memory if true */
  26171. ){
  26172. unixShm *p; /* The connection to be closed */
  26173. unixShmNode *pShmNode; /* The underlying shared-memory file */
  26174. unixShm **pp; /* For looping over sibling connections */
  26175. unixFile *pDbFd; /* The underlying database file */
  26176. pDbFd = (unixFile*)fd;
  26177. p = pDbFd->pShm;
  26178. if( p==0 ) return SQLITE_OK;
  26179. pShmNode = p->pShmNode;
  26180. assert( pShmNode==pDbFd->pInode->pShmNode );
  26181. assert( pShmNode->pInode==pDbFd->pInode );
  26182. /* Remove connection p from the set of connections associated
  26183. ** with pShmNode */
  26184. sqlite3_mutex_enter(pShmNode->mutex);
  26185. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  26186. *pp = p->pNext;
  26187. /* Free the connection p */
  26188. sqlite3_free(p);
  26189. pDbFd->pShm = 0;
  26190. sqlite3_mutex_leave(pShmNode->mutex);
  26191. /* If pShmNode->nRef has reached 0, then close the underlying
  26192. ** shared-memory file, too */
  26193. unixEnterMutex();
  26194. assert( pShmNode->nRef>0 );
  26195. pShmNode->nRef--;
  26196. if( pShmNode->nRef==0 ){
  26197. if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
  26198. unixShmPurge(pDbFd);
  26199. }
  26200. unixLeaveMutex();
  26201. return SQLITE_OK;
  26202. }
  26203. #else
  26204. # define unixShmMap 0
  26205. # define unixShmLock 0
  26206. # define unixShmBarrier 0
  26207. # define unixShmUnmap 0
  26208. #endif /* #ifndef SQLITE_OMIT_WAL */
  26209. #if SQLITE_MAX_MMAP_SIZE>0
  26210. /*
  26211. ** If it is currently memory mapped, unmap file pFd.
  26212. */
  26213. static void unixUnmapfile(unixFile *pFd){
  26214. assert( pFd->nFetchOut==0 );
  26215. if( pFd->pMapRegion ){
  26216. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  26217. pFd->pMapRegion = 0;
  26218. pFd->mmapSize = 0;
  26219. pFd->mmapSizeActual = 0;
  26220. }
  26221. }
  26222. /*
  26223. ** Return the system page size.
  26224. */
  26225. static int unixGetPagesize(void){
  26226. #if HAVE_MREMAP
  26227. return 512;
  26228. #elif defined(_BSD_SOURCE)
  26229. return getpagesize();
  26230. #else
  26231. return (int)sysconf(_SC_PAGESIZE);
  26232. #endif
  26233. }
  26234. /*
  26235. ** Attempt to set the size of the memory mapping maintained by file
  26236. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  26237. **
  26238. ** If successful, this function sets the following variables:
  26239. **
  26240. ** unixFile.pMapRegion
  26241. ** unixFile.mmapSize
  26242. ** unixFile.mmapSizeActual
  26243. **
  26244. ** If unsuccessful, an error message is logged via sqlite3_log() and
  26245. ** the three variables above are zeroed. In this case SQLite should
  26246. ** continue accessing the database using the xRead() and xWrite()
  26247. ** methods.
  26248. */
  26249. static void unixRemapfile(
  26250. unixFile *pFd, /* File descriptor object */
  26251. i64 nNew /* Required mapping size */
  26252. ){
  26253. const char *zErr = "mmap";
  26254. int h = pFd->h; /* File descriptor open on db file */
  26255. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  26256. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  26257. u8 *pNew = 0; /* Location of new mapping */
  26258. int flags = PROT_READ; /* Flags to pass to mmap() */
  26259. assert( pFd->nFetchOut==0 );
  26260. assert( nNew>pFd->mmapSize );
  26261. assert( nNew<=pFd->mmapSizeMax );
  26262. assert( nNew>0 );
  26263. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  26264. assert( MAP_FAILED!=0 );
  26265. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  26266. if( pOrig ){
  26267. const int szSyspage = unixGetPagesize();
  26268. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  26269. u8 *pReq = &pOrig[nReuse];
  26270. /* Unmap any pages of the existing mapping that cannot be reused. */
  26271. if( nReuse!=nOrig ){
  26272. osMunmap(pReq, nOrig-nReuse);
  26273. }
  26274. #if HAVE_MREMAP
  26275. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  26276. zErr = "mremap";
  26277. #else
  26278. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  26279. if( pNew!=MAP_FAILED ){
  26280. if( pNew!=pReq ){
  26281. osMunmap(pNew, nNew - nReuse);
  26282. pNew = 0;
  26283. }else{
  26284. pNew = pOrig;
  26285. }
  26286. }
  26287. #endif
  26288. /* The attempt to extend the existing mapping failed. Free it. */
  26289. if( pNew==MAP_FAILED || pNew==0 ){
  26290. osMunmap(pOrig, nReuse);
  26291. }
  26292. }
  26293. /* If pNew is still NULL, try to create an entirely new mapping. */
  26294. if( pNew==0 ){
  26295. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  26296. }
  26297. if( pNew==MAP_FAILED ){
  26298. pNew = 0;
  26299. nNew = 0;
  26300. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  26301. /* If the mmap() above failed, assume that all subsequent mmap() calls
  26302. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  26303. ** in this case. */
  26304. pFd->mmapSizeMax = 0;
  26305. }
  26306. pFd->pMapRegion = (void *)pNew;
  26307. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  26308. }
  26309. /*
  26310. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  26311. ** is already mapped, the existing mapping is replaced by the new). Or, if
  26312. ** there already exists a mapping for this file, and there are still
  26313. ** outstanding xFetch() references to it, this function is a no-op.
  26314. **
  26315. ** If parameter nByte is non-negative, then it is the requested size of
  26316. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  26317. ** requested size is the size of the file on disk. The actual size of the
  26318. ** created mapping is either the requested size or the value configured
  26319. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  26320. **
  26321. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  26322. ** recreated as a result of outstanding references) or an SQLite error
  26323. ** code otherwise.
  26324. */
  26325. static int unixMapfile(unixFile *pFd, i64 nByte){
  26326. i64 nMap = nByte;
  26327. int rc;
  26328. assert( nMap>=0 || pFd->nFetchOut==0 );
  26329. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  26330. if( nMap<0 ){
  26331. struct stat statbuf; /* Low-level file information */
  26332. rc = osFstat(pFd->h, &statbuf);
  26333. if( rc!=SQLITE_OK ){
  26334. return SQLITE_IOERR_FSTAT;
  26335. }
  26336. nMap = statbuf.st_size;
  26337. }
  26338. if( nMap>pFd->mmapSizeMax ){
  26339. nMap = pFd->mmapSizeMax;
  26340. }
  26341. if( nMap!=pFd->mmapSize ){
  26342. if( nMap>0 ){
  26343. unixRemapfile(pFd, nMap);
  26344. }else{
  26345. unixUnmapfile(pFd);
  26346. }
  26347. }
  26348. return SQLITE_OK;
  26349. }
  26350. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  26351. /*
  26352. ** If possible, return a pointer to a mapping of file fd starting at offset
  26353. ** iOff. The mapping must be valid for at least nAmt bytes.
  26354. **
  26355. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  26356. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  26357. ** Finally, if an error does occur, return an SQLite error code. The final
  26358. ** value of *pp is undefined in this case.
  26359. **
  26360. ** If this function does return a pointer, the caller must eventually
  26361. ** release the reference by calling unixUnfetch().
  26362. */
  26363. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  26364. #if SQLITE_MAX_MMAP_SIZE>0
  26365. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  26366. #endif
  26367. *pp = 0;
  26368. #if SQLITE_MAX_MMAP_SIZE>0
  26369. if( pFd->mmapSizeMax>0 ){
  26370. if( pFd->pMapRegion==0 ){
  26371. int rc = unixMapfile(pFd, -1);
  26372. if( rc!=SQLITE_OK ) return rc;
  26373. }
  26374. if( pFd->mmapSize >= iOff+nAmt ){
  26375. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  26376. pFd->nFetchOut++;
  26377. }
  26378. }
  26379. #endif
  26380. return SQLITE_OK;
  26381. }
  26382. /*
  26383. ** If the third argument is non-NULL, then this function releases a
  26384. ** reference obtained by an earlier call to unixFetch(). The second
  26385. ** argument passed to this function must be the same as the corresponding
  26386. ** argument that was passed to the unixFetch() invocation.
  26387. **
  26388. ** Or, if the third argument is NULL, then this function is being called
  26389. ** to inform the VFS layer that, according to POSIX, any existing mapping
  26390. ** may now be invalid and should be unmapped.
  26391. */
  26392. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  26393. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  26394. UNUSED_PARAMETER(iOff);
  26395. #if SQLITE_MAX_MMAP_SIZE>0
  26396. /* If p==0 (unmap the entire file) then there must be no outstanding
  26397. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  26398. ** then there must be at least one outstanding. */
  26399. assert( (p==0)==(pFd->nFetchOut==0) );
  26400. /* If p!=0, it must match the iOff value. */
  26401. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  26402. if( p ){
  26403. pFd->nFetchOut--;
  26404. }else{
  26405. unixUnmapfile(pFd);
  26406. }
  26407. assert( pFd->nFetchOut>=0 );
  26408. #endif
  26409. return SQLITE_OK;
  26410. }
  26411. /*
  26412. ** Here ends the implementation of all sqlite3_file methods.
  26413. **
  26414. ********************** End sqlite3_file Methods *******************************
  26415. ******************************************************************************/
  26416. /*
  26417. ** This division contains definitions of sqlite3_io_methods objects that
  26418. ** implement various file locking strategies. It also contains definitions
  26419. ** of "finder" functions. A finder-function is used to locate the appropriate
  26420. ** sqlite3_io_methods object for a particular database file. The pAppData
  26421. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  26422. ** the correct finder-function for that VFS.
  26423. **
  26424. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  26425. ** object. The only interesting finder-function is autolockIoFinder, which
  26426. ** looks at the filesystem type and tries to guess the best locking
  26427. ** strategy from that.
  26428. **
  26429. ** For finder-funtion F, two objects are created:
  26430. **
  26431. ** (1) The real finder-function named "FImpt()".
  26432. **
  26433. ** (2) A constant pointer to this function named just "F".
  26434. **
  26435. **
  26436. ** A pointer to the F pointer is used as the pAppData value for VFS
  26437. ** objects. We have to do this instead of letting pAppData point
  26438. ** directly at the finder-function since C90 rules prevent a void*
  26439. ** from be cast into a function pointer.
  26440. **
  26441. **
  26442. ** Each instance of this macro generates two objects:
  26443. **
  26444. ** * A constant sqlite3_io_methods object call METHOD that has locking
  26445. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  26446. **
  26447. ** * An I/O method finder function called FINDER that returns a pointer
  26448. ** to the METHOD object in the previous bullet.
  26449. */
  26450. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
  26451. static const sqlite3_io_methods METHOD = { \
  26452. VERSION, /* iVersion */ \
  26453. CLOSE, /* xClose */ \
  26454. unixRead, /* xRead */ \
  26455. unixWrite, /* xWrite */ \
  26456. unixTruncate, /* xTruncate */ \
  26457. unixSync, /* xSync */ \
  26458. unixFileSize, /* xFileSize */ \
  26459. LOCK, /* xLock */ \
  26460. UNLOCK, /* xUnlock */ \
  26461. CKLOCK, /* xCheckReservedLock */ \
  26462. unixFileControl, /* xFileControl */ \
  26463. unixSectorSize, /* xSectorSize */ \
  26464. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  26465. unixShmMap, /* xShmMap */ \
  26466. unixShmLock, /* xShmLock */ \
  26467. unixShmBarrier, /* xShmBarrier */ \
  26468. unixShmUnmap, /* xShmUnmap */ \
  26469. unixFetch, /* xFetch */ \
  26470. unixUnfetch, /* xUnfetch */ \
  26471. }; \
  26472. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  26473. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  26474. return &METHOD; \
  26475. } \
  26476. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  26477. = FINDER##Impl;
  26478. /*
  26479. ** Here are all of the sqlite3_io_methods objects for each of the
  26480. ** locking strategies. Functions that return pointers to these methods
  26481. ** are also created.
  26482. */
  26483. IOMETHODS(
  26484. posixIoFinder, /* Finder function name */
  26485. posixIoMethods, /* sqlite3_io_methods object name */
  26486. 3, /* shared memory and mmap are enabled */
  26487. unixClose, /* xClose method */
  26488. unixLock, /* xLock method */
  26489. unixUnlock, /* xUnlock method */
  26490. unixCheckReservedLock /* xCheckReservedLock method */
  26491. )
  26492. IOMETHODS(
  26493. nolockIoFinder, /* Finder function name */
  26494. nolockIoMethods, /* sqlite3_io_methods object name */
  26495. 1, /* shared memory is disabled */
  26496. nolockClose, /* xClose method */
  26497. nolockLock, /* xLock method */
  26498. nolockUnlock, /* xUnlock method */
  26499. nolockCheckReservedLock /* xCheckReservedLock method */
  26500. )
  26501. IOMETHODS(
  26502. dotlockIoFinder, /* Finder function name */
  26503. dotlockIoMethods, /* sqlite3_io_methods object name */
  26504. 1, /* shared memory is disabled */
  26505. dotlockClose, /* xClose method */
  26506. dotlockLock, /* xLock method */
  26507. dotlockUnlock, /* xUnlock method */
  26508. dotlockCheckReservedLock /* xCheckReservedLock method */
  26509. )
  26510. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  26511. IOMETHODS(
  26512. flockIoFinder, /* Finder function name */
  26513. flockIoMethods, /* sqlite3_io_methods object name */
  26514. 1, /* shared memory is disabled */
  26515. flockClose, /* xClose method */
  26516. flockLock, /* xLock method */
  26517. flockUnlock, /* xUnlock method */
  26518. flockCheckReservedLock /* xCheckReservedLock method */
  26519. )
  26520. #endif
  26521. #if OS_VXWORKS
  26522. IOMETHODS(
  26523. semIoFinder, /* Finder function name */
  26524. semIoMethods, /* sqlite3_io_methods object name */
  26525. 1, /* shared memory is disabled */
  26526. semClose, /* xClose method */
  26527. semLock, /* xLock method */
  26528. semUnlock, /* xUnlock method */
  26529. semCheckReservedLock /* xCheckReservedLock method */
  26530. )
  26531. #endif
  26532. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26533. IOMETHODS(
  26534. afpIoFinder, /* Finder function name */
  26535. afpIoMethods, /* sqlite3_io_methods object name */
  26536. 1, /* shared memory is disabled */
  26537. afpClose, /* xClose method */
  26538. afpLock, /* xLock method */
  26539. afpUnlock, /* xUnlock method */
  26540. afpCheckReservedLock /* xCheckReservedLock method */
  26541. )
  26542. #endif
  26543. /*
  26544. ** The proxy locking method is a "super-method" in the sense that it
  26545. ** opens secondary file descriptors for the conch and lock files and
  26546. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  26547. ** secondary files. For this reason, the division that implements
  26548. ** proxy locking is located much further down in the file. But we need
  26549. ** to go ahead and define the sqlite3_io_methods and finder function
  26550. ** for proxy locking here. So we forward declare the I/O methods.
  26551. */
  26552. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26553. static int proxyClose(sqlite3_file*);
  26554. static int proxyLock(sqlite3_file*, int);
  26555. static int proxyUnlock(sqlite3_file*, int);
  26556. static int proxyCheckReservedLock(sqlite3_file*, int*);
  26557. IOMETHODS(
  26558. proxyIoFinder, /* Finder function name */
  26559. proxyIoMethods, /* sqlite3_io_methods object name */
  26560. 1, /* shared memory is disabled */
  26561. proxyClose, /* xClose method */
  26562. proxyLock, /* xLock method */
  26563. proxyUnlock, /* xUnlock method */
  26564. proxyCheckReservedLock /* xCheckReservedLock method */
  26565. )
  26566. #endif
  26567. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  26568. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26569. IOMETHODS(
  26570. nfsIoFinder, /* Finder function name */
  26571. nfsIoMethods, /* sqlite3_io_methods object name */
  26572. 1, /* shared memory is disabled */
  26573. unixClose, /* xClose method */
  26574. unixLock, /* xLock method */
  26575. nfsUnlock, /* xUnlock method */
  26576. unixCheckReservedLock /* xCheckReservedLock method */
  26577. )
  26578. #endif
  26579. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26580. /*
  26581. ** This "finder" function attempts to determine the best locking strategy
  26582. ** for the database file "filePath". It then returns the sqlite3_io_methods
  26583. ** object that implements that strategy.
  26584. **
  26585. ** This is for MacOSX only.
  26586. */
  26587. static const sqlite3_io_methods *autolockIoFinderImpl(
  26588. const char *filePath, /* name of the database file */
  26589. unixFile *pNew /* open file object for the database file */
  26590. ){
  26591. static const struct Mapping {
  26592. const char *zFilesystem; /* Filesystem type name */
  26593. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  26594. } aMap[] = {
  26595. { "hfs", &posixIoMethods },
  26596. { "ufs", &posixIoMethods },
  26597. { "afpfs", &afpIoMethods },
  26598. { "smbfs", &afpIoMethods },
  26599. { "webdav", &nolockIoMethods },
  26600. { 0, 0 }
  26601. };
  26602. int i;
  26603. struct statfs fsInfo;
  26604. struct flock lockInfo;
  26605. if( !filePath ){
  26606. /* If filePath==NULL that means we are dealing with a transient file
  26607. ** that does not need to be locked. */
  26608. return &nolockIoMethods;
  26609. }
  26610. if( statfs(filePath, &fsInfo) != -1 ){
  26611. if( fsInfo.f_flags & MNT_RDONLY ){
  26612. return &nolockIoMethods;
  26613. }
  26614. for(i=0; aMap[i].zFilesystem; i++){
  26615. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  26616. return aMap[i].pMethods;
  26617. }
  26618. }
  26619. }
  26620. /* Default case. Handles, amongst others, "nfs".
  26621. ** Test byte-range lock using fcntl(). If the call succeeds,
  26622. ** assume that the file-system supports POSIX style locks.
  26623. */
  26624. lockInfo.l_len = 1;
  26625. lockInfo.l_start = 0;
  26626. lockInfo.l_whence = SEEK_SET;
  26627. lockInfo.l_type = F_RDLCK;
  26628. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  26629. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  26630. return &nfsIoMethods;
  26631. } else {
  26632. return &posixIoMethods;
  26633. }
  26634. }else{
  26635. return &dotlockIoMethods;
  26636. }
  26637. }
  26638. static const sqlite3_io_methods
  26639. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  26640. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26641. #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
  26642. /*
  26643. ** This "finder" function attempts to determine the best locking strategy
  26644. ** for the database file "filePath". It then returns the sqlite3_io_methods
  26645. ** object that implements that strategy.
  26646. **
  26647. ** This is for VXWorks only.
  26648. */
  26649. static const sqlite3_io_methods *autolockIoFinderImpl(
  26650. const char *filePath, /* name of the database file */
  26651. unixFile *pNew /* the open file object */
  26652. ){
  26653. struct flock lockInfo;
  26654. if( !filePath ){
  26655. /* If filePath==NULL that means we are dealing with a transient file
  26656. ** that does not need to be locked. */
  26657. return &nolockIoMethods;
  26658. }
  26659. /* Test if fcntl() is supported and use POSIX style locks.
  26660. ** Otherwise fall back to the named semaphore method.
  26661. */
  26662. lockInfo.l_len = 1;
  26663. lockInfo.l_start = 0;
  26664. lockInfo.l_whence = SEEK_SET;
  26665. lockInfo.l_type = F_RDLCK;
  26666. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  26667. return &posixIoMethods;
  26668. }else{
  26669. return &semIoMethods;
  26670. }
  26671. }
  26672. static const sqlite3_io_methods
  26673. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  26674. #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
  26675. /*
  26676. ** An abstract type for a pointer to a IO method finder function:
  26677. */
  26678. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  26679. /****************************************************************************
  26680. **************************** sqlite3_vfs methods ****************************
  26681. **
  26682. ** This division contains the implementation of methods on the
  26683. ** sqlite3_vfs object.
  26684. */
  26685. /*
  26686. ** Initialize the contents of the unixFile structure pointed to by pId.
  26687. */
  26688. static int fillInUnixFile(
  26689. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  26690. int h, /* Open file descriptor of file being opened */
  26691. sqlite3_file *pId, /* Write to the unixFile structure here */
  26692. const char *zFilename, /* Name of the file being opened */
  26693. int ctrlFlags /* Zero or more UNIXFILE_* values */
  26694. ){
  26695. const sqlite3_io_methods *pLockingStyle;
  26696. unixFile *pNew = (unixFile *)pId;
  26697. int rc = SQLITE_OK;
  26698. assert( pNew->pInode==NULL );
  26699. /* Usually the path zFilename should not be a relative pathname. The
  26700. ** exception is when opening the proxy "conch" file in builds that
  26701. ** include the special Apple locking styles.
  26702. */
  26703. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26704. assert( zFilename==0 || zFilename[0]=='/'
  26705. || pVfs->pAppData==(void*)&autolockIoFinder );
  26706. #else
  26707. assert( zFilename==0 || zFilename[0]=='/' );
  26708. #endif
  26709. /* No locking occurs in temporary files */
  26710. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  26711. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  26712. pNew->h = h;
  26713. pNew->pVfs = pVfs;
  26714. pNew->zPath = zFilename;
  26715. pNew->ctrlFlags = (u8)ctrlFlags;
  26716. #if SQLITE_MAX_MMAP_SIZE>0
  26717. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  26718. #endif
  26719. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  26720. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  26721. pNew->ctrlFlags |= UNIXFILE_PSOW;
  26722. }
  26723. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  26724. pNew->ctrlFlags |= UNIXFILE_EXCL;
  26725. }
  26726. #if OS_VXWORKS
  26727. pNew->pId = vxworksFindFileId(zFilename);
  26728. if( pNew->pId==0 ){
  26729. ctrlFlags |= UNIXFILE_NOLOCK;
  26730. rc = SQLITE_NOMEM;
  26731. }
  26732. #endif
  26733. if( ctrlFlags & UNIXFILE_NOLOCK ){
  26734. pLockingStyle = &nolockIoMethods;
  26735. }else{
  26736. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  26737. #if SQLITE_ENABLE_LOCKING_STYLE
  26738. /* Cache zFilename in the locking context (AFP and dotlock override) for
  26739. ** proxyLock activation is possible (remote proxy is based on db name)
  26740. ** zFilename remains valid until file is closed, to support */
  26741. pNew->lockingContext = (void*)zFilename;
  26742. #endif
  26743. }
  26744. if( pLockingStyle == &posixIoMethods
  26745. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26746. || pLockingStyle == &nfsIoMethods
  26747. #endif
  26748. ){
  26749. unixEnterMutex();
  26750. rc = findInodeInfo(pNew, &pNew->pInode);
  26751. if( rc!=SQLITE_OK ){
  26752. /* If an error occurred in findInodeInfo(), close the file descriptor
  26753. ** immediately, before releasing the mutex. findInodeInfo() may fail
  26754. ** in two scenarios:
  26755. **
  26756. ** (a) A call to fstat() failed.
  26757. ** (b) A malloc failed.
  26758. **
  26759. ** Scenario (b) may only occur if the process is holding no other
  26760. ** file descriptors open on the same file. If there were other file
  26761. ** descriptors on this file, then no malloc would be required by
  26762. ** findInodeInfo(). If this is the case, it is quite safe to close
  26763. ** handle h - as it is guaranteed that no posix locks will be released
  26764. ** by doing so.
  26765. **
  26766. ** If scenario (a) caused the error then things are not so safe. The
  26767. ** implicit assumption here is that if fstat() fails, things are in
  26768. ** such bad shape that dropping a lock or two doesn't matter much.
  26769. */
  26770. robust_close(pNew, h, __LINE__);
  26771. h = -1;
  26772. }
  26773. unixLeaveMutex();
  26774. }
  26775. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  26776. else if( pLockingStyle == &afpIoMethods ){
  26777. /* AFP locking uses the file path so it needs to be included in
  26778. ** the afpLockingContext.
  26779. */
  26780. afpLockingContext *pCtx;
  26781. pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
  26782. if( pCtx==0 ){
  26783. rc = SQLITE_NOMEM;
  26784. }else{
  26785. /* NB: zFilename exists and remains valid until the file is closed
  26786. ** according to requirement F11141. So we do not need to make a
  26787. ** copy of the filename. */
  26788. pCtx->dbPath = zFilename;
  26789. pCtx->reserved = 0;
  26790. srandomdev();
  26791. unixEnterMutex();
  26792. rc = findInodeInfo(pNew, &pNew->pInode);
  26793. if( rc!=SQLITE_OK ){
  26794. sqlite3_free(pNew->lockingContext);
  26795. robust_close(pNew, h, __LINE__);
  26796. h = -1;
  26797. }
  26798. unixLeaveMutex();
  26799. }
  26800. }
  26801. #endif
  26802. else if( pLockingStyle == &dotlockIoMethods ){
  26803. /* Dotfile locking uses the file path so it needs to be included in
  26804. ** the dotlockLockingContext
  26805. */
  26806. char *zLockFile;
  26807. int nFilename;
  26808. assert( zFilename!=0 );
  26809. nFilename = (int)strlen(zFilename) + 6;
  26810. zLockFile = (char *)sqlite3_malloc(nFilename);
  26811. if( zLockFile==0 ){
  26812. rc = SQLITE_NOMEM;
  26813. }else{
  26814. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  26815. }
  26816. pNew->lockingContext = zLockFile;
  26817. }
  26818. #if OS_VXWORKS
  26819. else if( pLockingStyle == &semIoMethods ){
  26820. /* Named semaphore locking uses the file path so it needs to be
  26821. ** included in the semLockingContext
  26822. */
  26823. unixEnterMutex();
  26824. rc = findInodeInfo(pNew, &pNew->pInode);
  26825. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  26826. char *zSemName = pNew->pInode->aSemName;
  26827. int n;
  26828. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  26829. pNew->pId->zCanonicalName);
  26830. for( n=1; zSemName[n]; n++ )
  26831. if( zSemName[n]=='/' ) zSemName[n] = '_';
  26832. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  26833. if( pNew->pInode->pSem == SEM_FAILED ){
  26834. rc = SQLITE_NOMEM;
  26835. pNew->pInode->aSemName[0] = '\0';
  26836. }
  26837. }
  26838. unixLeaveMutex();
  26839. }
  26840. #endif
  26841. pNew->lastErrno = 0;
  26842. #if OS_VXWORKS
  26843. if( rc!=SQLITE_OK ){
  26844. if( h>=0 ) robust_close(pNew, h, __LINE__);
  26845. h = -1;
  26846. osUnlink(zFilename);
  26847. pNew->ctrlFlags |= UNIXFILE_DELETE;
  26848. }
  26849. #endif
  26850. if( rc!=SQLITE_OK ){
  26851. if( h>=0 ) robust_close(pNew, h, __LINE__);
  26852. }else{
  26853. pNew->pMethod = pLockingStyle;
  26854. OpenCounter(+1);
  26855. verifyDbFile(pNew);
  26856. }
  26857. return rc;
  26858. }
  26859. /*
  26860. ** Return the name of a directory in which to put temporary files.
  26861. ** If no suitable temporary file directory can be found, return NULL.
  26862. */
  26863. static const char *unixTempFileDir(void){
  26864. static const char *azDirs[] = {
  26865. 0,
  26866. 0,
  26867. 0,
  26868. "/var/tmp",
  26869. "/usr/tmp",
  26870. "/tmp",
  26871. 0 /* List terminator */
  26872. };
  26873. unsigned int i;
  26874. struct stat buf;
  26875. const char *zDir = 0;
  26876. azDirs[0] = sqlite3_temp_directory;
  26877. if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
  26878. if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
  26879. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  26880. if( zDir==0 ) continue;
  26881. if( osStat(zDir, &buf) ) continue;
  26882. if( !S_ISDIR(buf.st_mode) ) continue;
  26883. if( osAccess(zDir, 07) ) continue;
  26884. break;
  26885. }
  26886. return zDir;
  26887. }
  26888. /*
  26889. ** Create a temporary file name in zBuf. zBuf must be allocated
  26890. ** by the calling process and must be big enough to hold at least
  26891. ** pVfs->mxPathname bytes.
  26892. */
  26893. static int unixGetTempname(int nBuf, char *zBuf){
  26894. static const unsigned char zChars[] =
  26895. "abcdefghijklmnopqrstuvwxyz"
  26896. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  26897. "0123456789";
  26898. unsigned int i, j;
  26899. const char *zDir;
  26900. /* It's odd to simulate an io-error here, but really this is just
  26901. ** using the io-error infrastructure to test that SQLite handles this
  26902. ** function failing.
  26903. */
  26904. SimulateIOError( return SQLITE_IOERR );
  26905. zDir = unixTempFileDir();
  26906. if( zDir==0 ) zDir = ".";
  26907. /* Check that the output buffer is large enough for the temporary file
  26908. ** name. If it is not, return SQLITE_ERROR.
  26909. */
  26910. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  26911. return SQLITE_ERROR;
  26912. }
  26913. do{
  26914. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  26915. j = (int)strlen(zBuf);
  26916. sqlite3_randomness(15, &zBuf[j]);
  26917. for(i=0; i<15; i++, j++){
  26918. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  26919. }
  26920. zBuf[j] = 0;
  26921. zBuf[j+1] = 0;
  26922. }while( osAccess(zBuf,0)==0 );
  26923. return SQLITE_OK;
  26924. }
  26925. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  26926. /*
  26927. ** Routine to transform a unixFile into a proxy-locking unixFile.
  26928. ** Implementation in the proxy-lock division, but used by unixOpen()
  26929. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  26930. */
  26931. static int proxyTransformUnixFile(unixFile*, const char*);
  26932. #endif
  26933. /*
  26934. ** Search for an unused file descriptor that was opened on the database
  26935. ** file (not a journal or master-journal file) identified by pathname
  26936. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  26937. ** argument to this function.
  26938. **
  26939. ** Such a file descriptor may exist if a database connection was closed
  26940. ** but the associated file descriptor could not be closed because some
  26941. ** other file descriptor open on the same file is holding a file-lock.
  26942. ** Refer to comments in the unixClose() function and the lengthy comment
  26943. ** describing "Posix Advisory Locking" at the start of this file for
  26944. ** further details. Also, ticket #4018.
  26945. **
  26946. ** If a suitable file descriptor is found, then it is returned. If no
  26947. ** such file descriptor is located, -1 is returned.
  26948. */
  26949. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  26950. UnixUnusedFd *pUnused = 0;
  26951. /* Do not search for an unused file descriptor on vxworks. Not because
  26952. ** vxworks would not benefit from the change (it might, we're not sure),
  26953. ** but because no way to test it is currently available. It is better
  26954. ** not to risk breaking vxworks support for the sake of such an obscure
  26955. ** feature. */
  26956. #if !OS_VXWORKS
  26957. struct stat sStat; /* Results of stat() call */
  26958. /* A stat() call may fail for various reasons. If this happens, it is
  26959. ** almost certain that an open() call on the same path will also fail.
  26960. ** For this reason, if an error occurs in the stat() call here, it is
  26961. ** ignored and -1 is returned. The caller will try to open a new file
  26962. ** descriptor on the same path, fail, and return an error to SQLite.
  26963. **
  26964. ** Even if a subsequent open() call does succeed, the consequences of
  26965. ** not searching for a resusable file descriptor are not dire. */
  26966. if( 0==osStat(zPath, &sStat) ){
  26967. unixInodeInfo *pInode;
  26968. unixEnterMutex();
  26969. pInode = inodeList;
  26970. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  26971. || pInode->fileId.ino!=sStat.st_ino) ){
  26972. pInode = pInode->pNext;
  26973. }
  26974. if( pInode ){
  26975. UnixUnusedFd **pp;
  26976. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  26977. pUnused = *pp;
  26978. if( pUnused ){
  26979. *pp = pUnused->pNext;
  26980. }
  26981. }
  26982. unixLeaveMutex();
  26983. }
  26984. #endif /* if !OS_VXWORKS */
  26985. return pUnused;
  26986. }
  26987. /*
  26988. ** This function is called by unixOpen() to determine the unix permissions
  26989. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  26990. ** and a value suitable for passing as the third argument to open(2) is
  26991. ** written to *pMode. If an IO error occurs, an SQLite error code is
  26992. ** returned and the value of *pMode is not modified.
  26993. **
  26994. ** In most cases cases, this routine sets *pMode to 0, which will become
  26995. ** an indication to robust_open() to create the file using
  26996. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  26997. ** But if the file being opened is a WAL or regular journal file, then
  26998. ** this function queries the file-system for the permissions on the
  26999. ** corresponding database file and sets *pMode to this value. Whenever
  27000. ** possible, WAL and journal files are created using the same permissions
  27001. ** as the associated database file.
  27002. **
  27003. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  27004. ** original filename is unavailable. But 8_3_NAMES is only used for
  27005. ** FAT filesystems and permissions do not matter there, so just use
  27006. ** the default permissions.
  27007. */
  27008. static int findCreateFileMode(
  27009. const char *zPath, /* Path of file (possibly) being created */
  27010. int flags, /* Flags passed as 4th argument to xOpen() */
  27011. mode_t *pMode, /* OUT: Permissions to open file with */
  27012. uid_t *pUid, /* OUT: uid to set on the file */
  27013. gid_t *pGid /* OUT: gid to set on the file */
  27014. ){
  27015. int rc = SQLITE_OK; /* Return Code */
  27016. *pMode = 0;
  27017. *pUid = 0;
  27018. *pGid = 0;
  27019. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  27020. char zDb[MAX_PATHNAME+1]; /* Database file path */
  27021. int nDb; /* Number of valid bytes in zDb */
  27022. struct stat sStat; /* Output of stat() on database file */
  27023. /* zPath is a path to a WAL or journal file. The following block derives
  27024. ** the path to the associated database file from zPath. This block handles
  27025. ** the following naming conventions:
  27026. **
  27027. ** "<path to db>-journal"
  27028. ** "<path to db>-wal"
  27029. ** "<path to db>-journalNN"
  27030. ** "<path to db>-walNN"
  27031. **
  27032. ** where NN is a decimal number. The NN naming schemes are
  27033. ** used by the test_multiplex.c module.
  27034. */
  27035. nDb = sqlite3Strlen30(zPath) - 1;
  27036. #ifdef SQLITE_ENABLE_8_3_NAMES
  27037. while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
  27038. if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
  27039. #else
  27040. while( zPath[nDb]!='-' ){
  27041. assert( nDb>0 );
  27042. assert( zPath[nDb]!='\n' );
  27043. nDb--;
  27044. }
  27045. #endif
  27046. memcpy(zDb, zPath, nDb);
  27047. zDb[nDb] = '\0';
  27048. if( 0==osStat(zDb, &sStat) ){
  27049. *pMode = sStat.st_mode & 0777;
  27050. *pUid = sStat.st_uid;
  27051. *pGid = sStat.st_gid;
  27052. }else{
  27053. rc = SQLITE_IOERR_FSTAT;
  27054. }
  27055. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  27056. *pMode = 0600;
  27057. }
  27058. return rc;
  27059. }
  27060. /*
  27061. ** Open the file zPath.
  27062. **
  27063. ** Previously, the SQLite OS layer used three functions in place of this
  27064. ** one:
  27065. **
  27066. ** sqlite3OsOpenReadWrite();
  27067. ** sqlite3OsOpenReadOnly();
  27068. ** sqlite3OsOpenExclusive();
  27069. **
  27070. ** These calls correspond to the following combinations of flags:
  27071. **
  27072. ** ReadWrite() -> (READWRITE | CREATE)
  27073. ** ReadOnly() -> (READONLY)
  27074. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  27075. **
  27076. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  27077. ** true, the file was configured to be automatically deleted when the
  27078. ** file handle closed. To achieve the same effect using this new
  27079. ** interface, add the DELETEONCLOSE flag to those specified above for
  27080. ** OpenExclusive().
  27081. */
  27082. static int unixOpen(
  27083. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  27084. const char *zPath, /* Pathname of file to be opened */
  27085. sqlite3_file *pFile, /* The file descriptor to be filled in */
  27086. int flags, /* Input flags to control the opening */
  27087. int *pOutFlags /* Output flags returned to SQLite core */
  27088. ){
  27089. unixFile *p = (unixFile *)pFile;
  27090. int fd = -1; /* File descriptor returned by open() */
  27091. int openFlags = 0; /* Flags to pass to open() */
  27092. int eType = flags&0xFFFFFF00; /* Type of file to open */
  27093. int noLock; /* True to omit locking primitives */
  27094. int rc = SQLITE_OK; /* Function Return Code */
  27095. int ctrlFlags = 0; /* UNIXFILE_* flags */
  27096. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  27097. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  27098. int isCreate = (flags & SQLITE_OPEN_CREATE);
  27099. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  27100. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  27101. #if SQLITE_ENABLE_LOCKING_STYLE
  27102. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  27103. #endif
  27104. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  27105. struct statfs fsInfo;
  27106. #endif
  27107. /* If creating a master or main-file journal, this function will open
  27108. ** a file-descriptor on the directory too. The first time unixSync()
  27109. ** is called the directory file descriptor will be fsync()ed and close()d.
  27110. */
  27111. int syncDir = (isCreate && (
  27112. eType==SQLITE_OPEN_MASTER_JOURNAL
  27113. || eType==SQLITE_OPEN_MAIN_JOURNAL
  27114. || eType==SQLITE_OPEN_WAL
  27115. ));
  27116. /* If argument zPath is a NULL pointer, this function is required to open
  27117. ** a temporary file. Use this buffer to store the file name in.
  27118. */
  27119. char zTmpname[MAX_PATHNAME+2];
  27120. const char *zName = zPath;
  27121. /* Check the following statements are true:
  27122. **
  27123. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  27124. ** (b) if CREATE is set, then READWRITE must also be set, and
  27125. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  27126. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  27127. */
  27128. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  27129. assert(isCreate==0 || isReadWrite);
  27130. assert(isExclusive==0 || isCreate);
  27131. assert(isDelete==0 || isCreate);
  27132. /* The main DB, main journal, WAL file and master journal are never
  27133. ** automatically deleted. Nor are they ever temporary files. */
  27134. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  27135. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  27136. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  27137. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  27138. /* Assert that the upper layer has set one of the "file-type" flags. */
  27139. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  27140. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  27141. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  27142. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  27143. );
  27144. memset(p, 0, sizeof(unixFile));
  27145. if( eType==SQLITE_OPEN_MAIN_DB ){
  27146. UnixUnusedFd *pUnused;
  27147. pUnused = findReusableFd(zName, flags);
  27148. if( pUnused ){
  27149. fd = pUnused->fd;
  27150. }else{
  27151. pUnused = sqlite3_malloc(sizeof(*pUnused));
  27152. if( !pUnused ){
  27153. return SQLITE_NOMEM;
  27154. }
  27155. }
  27156. p->pUnused = pUnused;
  27157. /* Database filenames are double-zero terminated if they are not
  27158. ** URIs with parameters. Hence, they can always be passed into
  27159. ** sqlite3_uri_parameter(). */
  27160. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  27161. }else if( !zName ){
  27162. /* If zName is NULL, the upper layer is requesting a temp file. */
  27163. assert(isDelete && !syncDir);
  27164. rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
  27165. if( rc!=SQLITE_OK ){
  27166. return rc;
  27167. }
  27168. zName = zTmpname;
  27169. /* Generated temporary filenames are always double-zero terminated
  27170. ** for use by sqlite3_uri_parameter(). */
  27171. assert( zName[strlen(zName)+1]==0 );
  27172. }
  27173. /* Determine the value of the flags parameter passed to POSIX function
  27174. ** open(). These must be calculated even if open() is not called, as
  27175. ** they may be stored as part of the file handle and used by the
  27176. ** 'conch file' locking functions later on. */
  27177. if( isReadonly ) openFlags |= O_RDONLY;
  27178. if( isReadWrite ) openFlags |= O_RDWR;
  27179. if( isCreate ) openFlags |= O_CREAT;
  27180. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  27181. openFlags |= (O_LARGEFILE|O_BINARY);
  27182. if( fd<0 ){
  27183. mode_t openMode; /* Permissions to create file with */
  27184. uid_t uid; /* Userid for the file */
  27185. gid_t gid; /* Groupid for the file */
  27186. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  27187. if( rc!=SQLITE_OK ){
  27188. assert( !p->pUnused );
  27189. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  27190. return rc;
  27191. }
  27192. fd = robust_open(zName, openFlags, openMode);
  27193. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  27194. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  27195. /* Failed to open the file for read/write access. Try read-only. */
  27196. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  27197. openFlags &= ~(O_RDWR|O_CREAT);
  27198. flags |= SQLITE_OPEN_READONLY;
  27199. openFlags |= O_RDONLY;
  27200. isReadonly = 1;
  27201. fd = robust_open(zName, openFlags, openMode);
  27202. }
  27203. if( fd<0 ){
  27204. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  27205. goto open_finished;
  27206. }
  27207. /* If this process is running as root and if creating a new rollback
  27208. ** journal or WAL file, set the ownership of the journal or WAL to be
  27209. ** the same as the original database.
  27210. */
  27211. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  27212. osFchown(fd, uid, gid);
  27213. }
  27214. }
  27215. assert( fd>=0 );
  27216. if( pOutFlags ){
  27217. *pOutFlags = flags;
  27218. }
  27219. if( p->pUnused ){
  27220. p->pUnused->fd = fd;
  27221. p->pUnused->flags = flags;
  27222. }
  27223. if( isDelete ){
  27224. #if OS_VXWORKS
  27225. zPath = zName;
  27226. #else
  27227. osUnlink(zName);
  27228. #endif
  27229. }
  27230. #if SQLITE_ENABLE_LOCKING_STYLE
  27231. else{
  27232. p->openFlags = openFlags;
  27233. }
  27234. #endif
  27235. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  27236. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  27237. if( fstatfs(fd, &fsInfo) == -1 ){
  27238. ((unixFile*)pFile)->lastErrno = errno;
  27239. robust_close(p, fd, __LINE__);
  27240. return SQLITE_IOERR_ACCESS;
  27241. }
  27242. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  27243. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  27244. }
  27245. #endif
  27246. /* Set up appropriate ctrlFlags */
  27247. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  27248. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  27249. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  27250. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  27251. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  27252. #if SQLITE_ENABLE_LOCKING_STYLE
  27253. #if SQLITE_PREFER_PROXY_LOCKING
  27254. isAutoProxy = 1;
  27255. #endif
  27256. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  27257. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  27258. int useProxy = 0;
  27259. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  27260. ** never use proxy, NULL means use proxy for non-local files only. */
  27261. if( envforce!=NULL ){
  27262. useProxy = atoi(envforce)>0;
  27263. }else{
  27264. if( statfs(zPath, &fsInfo) == -1 ){
  27265. /* In theory, the close(fd) call is sub-optimal. If the file opened
  27266. ** with fd is a database file, and there are other connections open
  27267. ** on that file that are currently holding advisory locks on it,
  27268. ** then the call to close() will cancel those locks. In practice,
  27269. ** we're assuming that statfs() doesn't fail very often. At least
  27270. ** not while other file descriptors opened by the same process on
  27271. ** the same file are working. */
  27272. p->lastErrno = errno;
  27273. robust_close(p, fd, __LINE__);
  27274. rc = SQLITE_IOERR_ACCESS;
  27275. goto open_finished;
  27276. }
  27277. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  27278. }
  27279. if( useProxy ){
  27280. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  27281. if( rc==SQLITE_OK ){
  27282. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  27283. if( rc!=SQLITE_OK ){
  27284. /* Use unixClose to clean up the resources added in fillInUnixFile
  27285. ** and clear all the structure's references. Specifically,
  27286. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  27287. */
  27288. unixClose(pFile);
  27289. return rc;
  27290. }
  27291. }
  27292. goto open_finished;
  27293. }
  27294. }
  27295. #endif
  27296. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  27297. open_finished:
  27298. if( rc!=SQLITE_OK ){
  27299. sqlite3_free(p->pUnused);
  27300. }
  27301. return rc;
  27302. }
  27303. /*
  27304. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  27305. ** the directory after deleting the file.
  27306. */
  27307. static int unixDelete(
  27308. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  27309. const char *zPath, /* Name of file to be deleted */
  27310. int dirSync /* If true, fsync() directory after deleting file */
  27311. ){
  27312. int rc = SQLITE_OK;
  27313. UNUSED_PARAMETER(NotUsed);
  27314. SimulateIOError(return SQLITE_IOERR_DELETE);
  27315. if( osUnlink(zPath)==(-1) ){
  27316. if( errno==ENOENT ){
  27317. rc = SQLITE_IOERR_DELETE_NOENT;
  27318. }else{
  27319. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  27320. }
  27321. return rc;
  27322. }
  27323. #ifndef SQLITE_DISABLE_DIRSYNC
  27324. if( (dirSync & 1)!=0 ){
  27325. int fd;
  27326. rc = osOpenDirectory(zPath, &fd);
  27327. if( rc==SQLITE_OK ){
  27328. #if OS_VXWORKS
  27329. if( fsync(fd)==-1 )
  27330. #else
  27331. if( fsync(fd) )
  27332. #endif
  27333. {
  27334. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  27335. }
  27336. robust_close(0, fd, __LINE__);
  27337. }else if( rc==SQLITE_CANTOPEN ){
  27338. rc = SQLITE_OK;
  27339. }
  27340. }
  27341. #endif
  27342. return rc;
  27343. }
  27344. /*
  27345. ** Test the existence of or access permissions of file zPath. The
  27346. ** test performed depends on the value of flags:
  27347. **
  27348. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  27349. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  27350. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  27351. **
  27352. ** Otherwise return 0.
  27353. */
  27354. static int unixAccess(
  27355. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  27356. const char *zPath, /* Path of the file to examine */
  27357. int flags, /* What do we want to learn about the zPath file? */
  27358. int *pResOut /* Write result boolean here */
  27359. ){
  27360. int amode = 0;
  27361. UNUSED_PARAMETER(NotUsed);
  27362. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  27363. switch( flags ){
  27364. case SQLITE_ACCESS_EXISTS:
  27365. amode = F_OK;
  27366. break;
  27367. case SQLITE_ACCESS_READWRITE:
  27368. amode = W_OK|R_OK;
  27369. break;
  27370. case SQLITE_ACCESS_READ:
  27371. amode = R_OK;
  27372. break;
  27373. default:
  27374. assert(!"Invalid flags argument");
  27375. }
  27376. *pResOut = (osAccess(zPath, amode)==0);
  27377. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  27378. struct stat buf;
  27379. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  27380. *pResOut = 0;
  27381. }
  27382. }
  27383. return SQLITE_OK;
  27384. }
  27385. /*
  27386. ** Turn a relative pathname into a full pathname. The relative path
  27387. ** is stored as a nul-terminated string in the buffer pointed to by
  27388. ** zPath.
  27389. **
  27390. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  27391. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  27392. ** this buffer before returning.
  27393. */
  27394. static int unixFullPathname(
  27395. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  27396. const char *zPath, /* Possibly relative input path */
  27397. int nOut, /* Size of output buffer in bytes */
  27398. char *zOut /* Output buffer */
  27399. ){
  27400. /* It's odd to simulate an io-error here, but really this is just
  27401. ** using the io-error infrastructure to test that SQLite handles this
  27402. ** function failing. This function could fail if, for example, the
  27403. ** current working directory has been unlinked.
  27404. */
  27405. SimulateIOError( return SQLITE_ERROR );
  27406. assert( pVfs->mxPathname==MAX_PATHNAME );
  27407. UNUSED_PARAMETER(pVfs);
  27408. zOut[nOut-1] = '\0';
  27409. if( zPath[0]=='/' ){
  27410. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  27411. }else{
  27412. int nCwd;
  27413. if( osGetcwd(zOut, nOut-1)==0 ){
  27414. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  27415. }
  27416. nCwd = (int)strlen(zOut);
  27417. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  27418. }
  27419. return SQLITE_OK;
  27420. }
  27421. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  27422. /*
  27423. ** Interfaces for opening a shared library, finding entry points
  27424. ** within the shared library, and closing the shared library.
  27425. */
  27426. #include <dlfcn.h>
  27427. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  27428. UNUSED_PARAMETER(NotUsed);
  27429. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  27430. }
  27431. /*
  27432. ** SQLite calls this function immediately after a call to unixDlSym() or
  27433. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  27434. ** message is available, it is written to zBufOut. If no error message
  27435. ** is available, zBufOut is left unmodified and SQLite uses a default
  27436. ** error message.
  27437. */
  27438. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  27439. const char *zErr;
  27440. UNUSED_PARAMETER(NotUsed);
  27441. unixEnterMutex();
  27442. zErr = dlerror();
  27443. if( zErr ){
  27444. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  27445. }
  27446. unixLeaveMutex();
  27447. }
  27448. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  27449. /*
  27450. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  27451. ** cast into a pointer to a function. And yet the library dlsym() routine
  27452. ** returns a void* which is really a pointer to a function. So how do we
  27453. ** use dlsym() with -pedantic-errors?
  27454. **
  27455. ** Variable x below is defined to be a pointer to a function taking
  27456. ** parameters void* and const char* and returning a pointer to a function.
  27457. ** We initialize x by assigning it a pointer to the dlsym() function.
  27458. ** (That assignment requires a cast.) Then we call the function that
  27459. ** x points to.
  27460. **
  27461. ** This work-around is unlikely to work correctly on any system where
  27462. ** you really cannot cast a function pointer into void*. But then, on the
  27463. ** other hand, dlsym() will not work on such a system either, so we have
  27464. ** not really lost anything.
  27465. */
  27466. void (*(*x)(void*,const char*))(void);
  27467. UNUSED_PARAMETER(NotUsed);
  27468. x = (void(*(*)(void*,const char*))(void))dlsym;
  27469. return (*x)(p, zSym);
  27470. }
  27471. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  27472. UNUSED_PARAMETER(NotUsed);
  27473. dlclose(pHandle);
  27474. }
  27475. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  27476. #define unixDlOpen 0
  27477. #define unixDlError 0
  27478. #define unixDlSym 0
  27479. #define unixDlClose 0
  27480. #endif
  27481. /*
  27482. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  27483. */
  27484. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  27485. UNUSED_PARAMETER(NotUsed);
  27486. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  27487. /* We have to initialize zBuf to prevent valgrind from reporting
  27488. ** errors. The reports issued by valgrind are incorrect - we would
  27489. ** prefer that the randomness be increased by making use of the
  27490. ** uninitialized space in zBuf - but valgrind errors tend to worry
  27491. ** some users. Rather than argue, it seems easier just to initialize
  27492. ** the whole array and silence valgrind, even if that means less randomness
  27493. ** in the random seed.
  27494. **
  27495. ** When testing, initializing zBuf[] to zero is all we do. That means
  27496. ** that we always use the same random number sequence. This makes the
  27497. ** tests repeatable.
  27498. */
  27499. memset(zBuf, 0, nBuf);
  27500. #if !defined(SQLITE_TEST)
  27501. {
  27502. int pid, fd, got;
  27503. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  27504. if( fd<0 ){
  27505. time_t t;
  27506. time(&t);
  27507. memcpy(zBuf, &t, sizeof(t));
  27508. pid = getpid();
  27509. memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
  27510. assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
  27511. nBuf = sizeof(t) + sizeof(pid);
  27512. }else{
  27513. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  27514. robust_close(0, fd, __LINE__);
  27515. }
  27516. }
  27517. #endif
  27518. return nBuf;
  27519. }
  27520. /*
  27521. ** Sleep for a little while. Return the amount of time slept.
  27522. ** The argument is the number of microseconds we want to sleep.
  27523. ** The return value is the number of microseconds of sleep actually
  27524. ** requested from the underlying operating system, a number which
  27525. ** might be greater than or equal to the argument, but not less
  27526. ** than the argument.
  27527. */
  27528. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  27529. #if OS_VXWORKS
  27530. struct timespec sp;
  27531. sp.tv_sec = microseconds / 1000000;
  27532. sp.tv_nsec = (microseconds % 1000000) * 1000;
  27533. nanosleep(&sp, NULL);
  27534. UNUSED_PARAMETER(NotUsed);
  27535. return microseconds;
  27536. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  27537. usleep(microseconds);
  27538. UNUSED_PARAMETER(NotUsed);
  27539. return microseconds;
  27540. #else
  27541. int seconds = (microseconds+999999)/1000000;
  27542. sleep(seconds);
  27543. UNUSED_PARAMETER(NotUsed);
  27544. return seconds*1000000;
  27545. #endif
  27546. }
  27547. /*
  27548. ** The following variable, if set to a non-zero value, is interpreted as
  27549. ** the number of seconds since 1970 and is used to set the result of
  27550. ** sqlite3OsCurrentTime() during testing.
  27551. */
  27552. #ifdef SQLITE_TEST
  27553. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  27554. #endif
  27555. /*
  27556. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  27557. ** the current time and date as a Julian Day number times 86_400_000. In
  27558. ** other words, write into *piNow the number of milliseconds since the Julian
  27559. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  27560. ** proleptic Gregorian calendar.
  27561. **
  27562. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  27563. ** cannot be found.
  27564. */
  27565. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  27566. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  27567. int rc = SQLITE_OK;
  27568. #if defined(NO_GETTOD)
  27569. time_t t;
  27570. time(&t);
  27571. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  27572. #elif OS_VXWORKS
  27573. struct timespec sNow;
  27574. clock_gettime(CLOCK_REALTIME, &sNow);
  27575. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  27576. #else
  27577. struct timeval sNow;
  27578. if( gettimeofday(&sNow, 0)==0 ){
  27579. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  27580. }else{
  27581. rc = SQLITE_ERROR;
  27582. }
  27583. #endif
  27584. #ifdef SQLITE_TEST
  27585. if( sqlite3_current_time ){
  27586. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  27587. }
  27588. #endif
  27589. UNUSED_PARAMETER(NotUsed);
  27590. return rc;
  27591. }
  27592. /*
  27593. ** Find the current time (in Universal Coordinated Time). Write the
  27594. ** current time and date as a Julian Day number into *prNow and
  27595. ** return 0. Return 1 if the time and date cannot be found.
  27596. */
  27597. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  27598. sqlite3_int64 i = 0;
  27599. int rc;
  27600. UNUSED_PARAMETER(NotUsed);
  27601. rc = unixCurrentTimeInt64(0, &i);
  27602. *prNow = i/86400000.0;
  27603. return rc;
  27604. }
  27605. /*
  27606. ** We added the xGetLastError() method with the intention of providing
  27607. ** better low-level error messages when operating-system problems come up
  27608. ** during SQLite operation. But so far, none of that has been implemented
  27609. ** in the core. So this routine is never called. For now, it is merely
  27610. ** a place-holder.
  27611. */
  27612. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  27613. UNUSED_PARAMETER(NotUsed);
  27614. UNUSED_PARAMETER(NotUsed2);
  27615. UNUSED_PARAMETER(NotUsed3);
  27616. return 0;
  27617. }
  27618. /*
  27619. ************************ End of sqlite3_vfs methods ***************************
  27620. ******************************************************************************/
  27621. /******************************************************************************
  27622. ************************** Begin Proxy Locking ********************************
  27623. **
  27624. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  27625. ** other locking methods on secondary lock files. Proxy locking is a
  27626. ** meta-layer over top of the primitive locking implemented above. For
  27627. ** this reason, the division that implements of proxy locking is deferred
  27628. ** until late in the file (here) after all of the other I/O methods have
  27629. ** been defined - so that the primitive locking methods are available
  27630. ** as services to help with the implementation of proxy locking.
  27631. **
  27632. ****
  27633. **
  27634. ** The default locking schemes in SQLite use byte-range locks on the
  27635. ** database file to coordinate safe, concurrent access by multiple readers
  27636. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  27637. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  27638. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  27639. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  27640. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  27641. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  27642. ** address in the shared range is taken for a SHARED lock, the entire
  27643. ** shared range is taken for an EXCLUSIVE lock):
  27644. **
  27645. ** PENDING_BYTE 0x40000000
  27646. ** RESERVED_BYTE 0x40000001
  27647. ** SHARED_RANGE 0x40000002 -> 0x40000200
  27648. **
  27649. ** This works well on the local file system, but shows a nearly 100x
  27650. ** slowdown in read performance on AFP because the AFP client disables
  27651. ** the read cache when byte-range locks are present. Enabling the read
  27652. ** cache exposes a cache coherency problem that is present on all OS X
  27653. ** supported network file systems. NFS and AFP both observe the
  27654. ** close-to-open semantics for ensuring cache coherency
  27655. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  27656. ** address the requirements for concurrent database access by multiple
  27657. ** readers and writers
  27658. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  27659. **
  27660. ** To address the performance and cache coherency issues, proxy file locking
  27661. ** changes the way database access is controlled by limiting access to a
  27662. ** single host at a time and moving file locks off of the database file
  27663. ** and onto a proxy file on the local file system.
  27664. **
  27665. **
  27666. ** Using proxy locks
  27667. ** -----------------
  27668. **
  27669. ** C APIs
  27670. **
  27671. ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
  27672. ** <proxy_path> | ":auto:");
  27673. ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
  27674. **
  27675. **
  27676. ** SQL pragmas
  27677. **
  27678. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  27679. ** PRAGMA [database.]lock_proxy_file
  27680. **
  27681. ** Specifying ":auto:" means that if there is a conch file with a matching
  27682. ** host ID in it, the proxy path in the conch file will be used, otherwise
  27683. ** a proxy path based on the user's temp dir
  27684. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  27685. ** actual proxy file name is generated from the name and path of the
  27686. ** database file. For example:
  27687. **
  27688. ** For database path "/Users/me/foo.db"
  27689. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  27690. **
  27691. ** Once a lock proxy is configured for a database connection, it can not
  27692. ** be removed, however it may be switched to a different proxy path via
  27693. ** the above APIs (assuming the conch file is not being held by another
  27694. ** connection or process).
  27695. **
  27696. **
  27697. ** How proxy locking works
  27698. ** -----------------------
  27699. **
  27700. ** Proxy file locking relies primarily on two new supporting files:
  27701. **
  27702. ** * conch file to limit access to the database file to a single host
  27703. ** at a time
  27704. **
  27705. ** * proxy file to act as a proxy for the advisory locks normally
  27706. ** taken on the database
  27707. **
  27708. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  27709. ** by taking an sqlite-style shared lock on the conch file, reading the
  27710. ** contents and comparing the host's unique host ID (see below) and lock
  27711. ** proxy path against the values stored in the conch. The conch file is
  27712. ** stored in the same directory as the database file and the file name
  27713. ** is patterned after the database file name as ".<databasename>-conch".
  27714. ** If the conch file does not exist, or it's contents do not match the
  27715. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  27716. ** lock and the conch file contents is updated with the host ID and proxy
  27717. ** path and the lock is downgraded to a shared lock again. If the conch
  27718. ** is held by another process (with a shared lock), the exclusive lock
  27719. ** will fail and SQLITE_BUSY is returned.
  27720. **
  27721. ** The proxy file - a single-byte file used for all advisory file locks
  27722. ** normally taken on the database file. This allows for safe sharing
  27723. ** of the database file for multiple readers and writers on the same
  27724. ** host (the conch ensures that they all use the same local lock file).
  27725. **
  27726. ** Requesting the lock proxy does not immediately take the conch, it is
  27727. ** only taken when the first request to lock database file is made.
  27728. ** This matches the semantics of the traditional locking behavior, where
  27729. ** opening a connection to a database file does not take a lock on it.
  27730. ** The shared lock and an open file descriptor are maintained until
  27731. ** the connection to the database is closed.
  27732. **
  27733. ** The proxy file and the lock file are never deleted so they only need
  27734. ** to be created the first time they are used.
  27735. **
  27736. ** Configuration options
  27737. ** ---------------------
  27738. **
  27739. ** SQLITE_PREFER_PROXY_LOCKING
  27740. **
  27741. ** Database files accessed on non-local file systems are
  27742. ** automatically configured for proxy locking, lock files are
  27743. ** named automatically using the same logic as
  27744. ** PRAGMA lock_proxy_file=":auto:"
  27745. **
  27746. ** SQLITE_PROXY_DEBUG
  27747. **
  27748. ** Enables the logging of error messages during host id file
  27749. ** retrieval and creation
  27750. **
  27751. ** LOCKPROXYDIR
  27752. **
  27753. ** Overrides the default directory used for lock proxy files that
  27754. ** are named automatically via the ":auto:" setting
  27755. **
  27756. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  27757. **
  27758. ** Permissions to use when creating a directory for storing the
  27759. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  27760. **
  27761. **
  27762. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  27763. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  27764. ** force proxy locking to be used for every database file opened, and 0
  27765. ** will force automatic proxy locking to be disabled for all database
  27766. ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
  27767. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  27768. */
  27769. /*
  27770. ** Proxy locking is only available on MacOSX
  27771. */
  27772. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27773. /*
  27774. ** The proxyLockingContext has the path and file structures for the remote
  27775. ** and local proxy files in it
  27776. */
  27777. typedef struct proxyLockingContext proxyLockingContext;
  27778. struct proxyLockingContext {
  27779. unixFile *conchFile; /* Open conch file */
  27780. char *conchFilePath; /* Name of the conch file */
  27781. unixFile *lockProxy; /* Open proxy lock file */
  27782. char *lockProxyPath; /* Name of the proxy lock file */
  27783. char *dbPath; /* Name of the open file */
  27784. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  27785. void *oldLockingContext; /* Original lockingcontext to restore on close */
  27786. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  27787. };
  27788. /*
  27789. ** The proxy lock file path for the database at dbPath is written into lPath,
  27790. ** which must point to valid, writable memory large enough for a maxLen length
  27791. ** file path.
  27792. */
  27793. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  27794. int len;
  27795. int dbLen;
  27796. int i;
  27797. #ifdef LOCKPROXYDIR
  27798. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  27799. #else
  27800. # ifdef _CS_DARWIN_USER_TEMP_DIR
  27801. {
  27802. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  27803. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  27804. lPath, errno, getpid()));
  27805. return SQLITE_IOERR_LOCK;
  27806. }
  27807. len = strlcat(lPath, "sqliteplocks", maxLen);
  27808. }
  27809. # else
  27810. len = strlcpy(lPath, "/tmp/", maxLen);
  27811. # endif
  27812. #endif
  27813. if( lPath[len-1]!='/' ){
  27814. len = strlcat(lPath, "/", maxLen);
  27815. }
  27816. /* transform the db path to a unique cache name */
  27817. dbLen = (int)strlen(dbPath);
  27818. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  27819. char c = dbPath[i];
  27820. lPath[i+len] = (c=='/')?'_':c;
  27821. }
  27822. lPath[i+len]='\0';
  27823. strlcat(lPath, ":auto:", maxLen);
  27824. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
  27825. return SQLITE_OK;
  27826. }
  27827. /*
  27828. ** Creates the lock file and any missing directories in lockPath
  27829. */
  27830. static int proxyCreateLockPath(const char *lockPath){
  27831. int i, len;
  27832. char buf[MAXPATHLEN];
  27833. int start = 0;
  27834. assert(lockPath!=NULL);
  27835. /* try to create all the intermediate directories */
  27836. len = (int)strlen(lockPath);
  27837. buf[0] = lockPath[0];
  27838. for( i=1; i<len; i++ ){
  27839. if( lockPath[i] == '/' && (i - start > 0) ){
  27840. /* only mkdir if leaf dir != "." or "/" or ".." */
  27841. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  27842. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  27843. buf[i]='\0';
  27844. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  27845. int err=errno;
  27846. if( err!=EEXIST ) {
  27847. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  27848. "'%s' proxy lock path=%s pid=%d\n",
  27849. buf, strerror(err), lockPath, getpid()));
  27850. return err;
  27851. }
  27852. }
  27853. }
  27854. start=i+1;
  27855. }
  27856. buf[i] = lockPath[i];
  27857. }
  27858. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
  27859. return 0;
  27860. }
  27861. /*
  27862. ** Create a new VFS file descriptor (stored in memory obtained from
  27863. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  27864. **
  27865. ** The caller is responsible not only for closing the file descriptor
  27866. ** but also for freeing the memory associated with the file descriptor.
  27867. */
  27868. static int proxyCreateUnixFile(
  27869. const char *path, /* path for the new unixFile */
  27870. unixFile **ppFile, /* unixFile created and returned by ref */
  27871. int islockfile /* if non zero missing dirs will be created */
  27872. ) {
  27873. int fd = -1;
  27874. unixFile *pNew;
  27875. int rc = SQLITE_OK;
  27876. int openFlags = O_RDWR | O_CREAT;
  27877. sqlite3_vfs dummyVfs;
  27878. int terrno = 0;
  27879. UnixUnusedFd *pUnused = NULL;
  27880. /* 1. first try to open/create the file
  27881. ** 2. if that fails, and this is a lock file (not-conch), try creating
  27882. ** the parent directories and then try again.
  27883. ** 3. if that fails, try to open the file read-only
  27884. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  27885. */
  27886. pUnused = findReusableFd(path, openFlags);
  27887. if( pUnused ){
  27888. fd = pUnused->fd;
  27889. }else{
  27890. pUnused = sqlite3_malloc(sizeof(*pUnused));
  27891. if( !pUnused ){
  27892. return SQLITE_NOMEM;
  27893. }
  27894. }
  27895. if( fd<0 ){
  27896. fd = robust_open(path, openFlags, 0);
  27897. terrno = errno;
  27898. if( fd<0 && errno==ENOENT && islockfile ){
  27899. if( proxyCreateLockPath(path) == SQLITE_OK ){
  27900. fd = robust_open(path, openFlags, 0);
  27901. }
  27902. }
  27903. }
  27904. if( fd<0 ){
  27905. openFlags = O_RDONLY;
  27906. fd = robust_open(path, openFlags, 0);
  27907. terrno = errno;
  27908. }
  27909. if( fd<0 ){
  27910. if( islockfile ){
  27911. return SQLITE_BUSY;
  27912. }
  27913. switch (terrno) {
  27914. case EACCES:
  27915. return SQLITE_PERM;
  27916. case EIO:
  27917. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  27918. default:
  27919. return SQLITE_CANTOPEN_BKPT;
  27920. }
  27921. }
  27922. pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
  27923. if( pNew==NULL ){
  27924. rc = SQLITE_NOMEM;
  27925. goto end_create_proxy;
  27926. }
  27927. memset(pNew, 0, sizeof(unixFile));
  27928. pNew->openFlags = openFlags;
  27929. memset(&dummyVfs, 0, sizeof(dummyVfs));
  27930. dummyVfs.pAppData = (void*)&autolockIoFinder;
  27931. dummyVfs.zName = "dummy";
  27932. pUnused->fd = fd;
  27933. pUnused->flags = openFlags;
  27934. pNew->pUnused = pUnused;
  27935. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  27936. if( rc==SQLITE_OK ){
  27937. *ppFile = pNew;
  27938. return SQLITE_OK;
  27939. }
  27940. end_create_proxy:
  27941. robust_close(pNew, fd, __LINE__);
  27942. sqlite3_free(pNew);
  27943. sqlite3_free(pUnused);
  27944. return rc;
  27945. }
  27946. #ifdef SQLITE_TEST
  27947. /* simulate multiple hosts by creating unique hostid file paths */
  27948. SQLITE_API int sqlite3_hostid_num = 0;
  27949. #endif
  27950. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  27951. /* Not always defined in the headers as it ought to be */
  27952. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  27953. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  27954. ** bytes of writable memory.
  27955. */
  27956. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  27957. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  27958. memset(pHostID, 0, PROXY_HOSTIDLEN);
  27959. #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
  27960. && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
  27961. {
  27962. static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
  27963. if( gethostuuid(pHostID, &timeout) ){
  27964. int err = errno;
  27965. if( pError ){
  27966. *pError = err;
  27967. }
  27968. return SQLITE_IOERR;
  27969. }
  27970. }
  27971. #else
  27972. UNUSED_PARAMETER(pError);
  27973. #endif
  27974. #ifdef SQLITE_TEST
  27975. /* simulate multiple hosts by creating unique hostid file paths */
  27976. if( sqlite3_hostid_num != 0){
  27977. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  27978. }
  27979. #endif
  27980. return SQLITE_OK;
  27981. }
  27982. /* The conch file contains the header, host id and lock file path
  27983. */
  27984. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  27985. #define PROXY_HEADERLEN 1 /* conch file header length */
  27986. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  27987. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  27988. /*
  27989. ** Takes an open conch file, copies the contents to a new path and then moves
  27990. ** it back. The newly created file's file descriptor is assigned to the
  27991. ** conch file structure and finally the original conch file descriptor is
  27992. ** closed. Returns zero if successful.
  27993. */
  27994. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  27995. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  27996. unixFile *conchFile = pCtx->conchFile;
  27997. char tPath[MAXPATHLEN];
  27998. char buf[PROXY_MAXCONCHLEN];
  27999. char *cPath = pCtx->conchFilePath;
  28000. size_t readLen = 0;
  28001. size_t pathLen = 0;
  28002. char errmsg[64] = "";
  28003. int fd = -1;
  28004. int rc = -1;
  28005. UNUSED_PARAMETER(myHostID);
  28006. /* create a new path by replace the trailing '-conch' with '-break' */
  28007. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  28008. if( pathLen>MAXPATHLEN || pathLen<6 ||
  28009. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  28010. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  28011. goto end_breaklock;
  28012. }
  28013. /* read the conch content */
  28014. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  28015. if( readLen<PROXY_PATHINDEX ){
  28016. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  28017. goto end_breaklock;
  28018. }
  28019. /* write it out to the temporary break file */
  28020. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  28021. if( fd<0 ){
  28022. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  28023. goto end_breaklock;
  28024. }
  28025. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  28026. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  28027. goto end_breaklock;
  28028. }
  28029. if( rename(tPath, cPath) ){
  28030. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  28031. goto end_breaklock;
  28032. }
  28033. rc = 0;
  28034. fprintf(stderr, "broke stale lock on %s\n", cPath);
  28035. robust_close(pFile, conchFile->h, __LINE__);
  28036. conchFile->h = fd;
  28037. conchFile->openFlags = O_RDWR | O_CREAT;
  28038. end_breaklock:
  28039. if( rc ){
  28040. if( fd>=0 ){
  28041. osUnlink(tPath);
  28042. robust_close(pFile, fd, __LINE__);
  28043. }
  28044. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  28045. }
  28046. return rc;
  28047. }
  28048. /* Take the requested lock on the conch file and break a stale lock if the
  28049. ** host id matches.
  28050. */
  28051. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  28052. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28053. unixFile *conchFile = pCtx->conchFile;
  28054. int rc = SQLITE_OK;
  28055. int nTries = 0;
  28056. struct timespec conchModTime;
  28057. memset(&conchModTime, 0, sizeof(conchModTime));
  28058. do {
  28059. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  28060. nTries ++;
  28061. if( rc==SQLITE_BUSY ){
  28062. /* If the lock failed (busy):
  28063. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  28064. * 2nd try: fail if the mod time changed or host id is different, wait
  28065. * 10 sec and try again
  28066. * 3rd try: break the lock unless the mod time has changed.
  28067. */
  28068. struct stat buf;
  28069. if( osFstat(conchFile->h, &buf) ){
  28070. pFile->lastErrno = errno;
  28071. return SQLITE_IOERR_LOCK;
  28072. }
  28073. if( nTries==1 ){
  28074. conchModTime = buf.st_mtimespec;
  28075. usleep(500000); /* wait 0.5 sec and try the lock again*/
  28076. continue;
  28077. }
  28078. assert( nTries>1 );
  28079. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  28080. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  28081. return SQLITE_BUSY;
  28082. }
  28083. if( nTries==2 ){
  28084. char tBuf[PROXY_MAXCONCHLEN];
  28085. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  28086. if( len<0 ){
  28087. pFile->lastErrno = errno;
  28088. return SQLITE_IOERR_LOCK;
  28089. }
  28090. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  28091. /* don't break the lock if the host id doesn't match */
  28092. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  28093. return SQLITE_BUSY;
  28094. }
  28095. }else{
  28096. /* don't break the lock on short read or a version mismatch */
  28097. return SQLITE_BUSY;
  28098. }
  28099. usleep(10000000); /* wait 10 sec and try the lock again */
  28100. continue;
  28101. }
  28102. assert( nTries==3 );
  28103. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  28104. rc = SQLITE_OK;
  28105. if( lockType==EXCLUSIVE_LOCK ){
  28106. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  28107. }
  28108. if( !rc ){
  28109. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  28110. }
  28111. }
  28112. }
  28113. } while( rc==SQLITE_BUSY && nTries<3 );
  28114. return rc;
  28115. }
  28116. /* Takes the conch by taking a shared lock and read the contents conch, if
  28117. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  28118. ** lockPath means that the lockPath in the conch file will be used if the
  28119. ** host IDs match, or a new lock path will be generated automatically
  28120. ** and written to the conch file.
  28121. */
  28122. static int proxyTakeConch(unixFile *pFile){
  28123. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28124. if( pCtx->conchHeld!=0 ){
  28125. return SQLITE_OK;
  28126. }else{
  28127. unixFile *conchFile = pCtx->conchFile;
  28128. uuid_t myHostID;
  28129. int pError = 0;
  28130. char readBuf[PROXY_MAXCONCHLEN];
  28131. char lockPath[MAXPATHLEN];
  28132. char *tempLockPath = NULL;
  28133. int rc = SQLITE_OK;
  28134. int createConch = 0;
  28135. int hostIdMatch = 0;
  28136. int readLen = 0;
  28137. int tryOldLockPath = 0;
  28138. int forceNewLockPath = 0;
  28139. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  28140. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
  28141. rc = proxyGetHostID(myHostID, &pError);
  28142. if( (rc&0xff)==SQLITE_IOERR ){
  28143. pFile->lastErrno = pError;
  28144. goto end_takeconch;
  28145. }
  28146. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  28147. if( rc!=SQLITE_OK ){
  28148. goto end_takeconch;
  28149. }
  28150. /* read the existing conch file */
  28151. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  28152. if( readLen<0 ){
  28153. /* I/O error: lastErrno set by seekAndRead */
  28154. pFile->lastErrno = conchFile->lastErrno;
  28155. rc = SQLITE_IOERR_READ;
  28156. goto end_takeconch;
  28157. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  28158. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  28159. /* a short read or version format mismatch means we need to create a new
  28160. ** conch file.
  28161. */
  28162. createConch = 1;
  28163. }
  28164. /* if the host id matches and the lock path already exists in the conch
  28165. ** we'll try to use the path there, if we can't open that path, we'll
  28166. ** retry with a new auto-generated path
  28167. */
  28168. do { /* in case we need to try again for an :auto: named lock file */
  28169. if( !createConch && !forceNewLockPath ){
  28170. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  28171. PROXY_HOSTIDLEN);
  28172. /* if the conch has data compare the contents */
  28173. if( !pCtx->lockProxyPath ){
  28174. /* for auto-named local lock file, just check the host ID and we'll
  28175. ** use the local lock file path that's already in there
  28176. */
  28177. if( hostIdMatch ){
  28178. size_t pathLen = (readLen - PROXY_PATHINDEX);
  28179. if( pathLen>=MAXPATHLEN ){
  28180. pathLen=MAXPATHLEN-1;
  28181. }
  28182. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  28183. lockPath[pathLen] = 0;
  28184. tempLockPath = lockPath;
  28185. tryOldLockPath = 1;
  28186. /* create a copy of the lock path if the conch is taken */
  28187. goto end_takeconch;
  28188. }
  28189. }else if( hostIdMatch
  28190. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  28191. readLen-PROXY_PATHINDEX)
  28192. ){
  28193. /* conch host and lock path match */
  28194. goto end_takeconch;
  28195. }
  28196. }
  28197. /* if the conch isn't writable and doesn't match, we can't take it */
  28198. if( (conchFile->openFlags&O_RDWR) == 0 ){
  28199. rc = SQLITE_BUSY;
  28200. goto end_takeconch;
  28201. }
  28202. /* either the conch didn't match or we need to create a new one */
  28203. if( !pCtx->lockProxyPath ){
  28204. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  28205. tempLockPath = lockPath;
  28206. /* create a copy of the lock path _only_ if the conch is taken */
  28207. }
  28208. /* update conch with host and path (this will fail if other process
  28209. ** has a shared lock already), if the host id matches, use the big
  28210. ** stick.
  28211. */
  28212. futimes(conchFile->h, NULL);
  28213. if( hostIdMatch && !createConch ){
  28214. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  28215. /* We are trying for an exclusive lock but another thread in this
  28216. ** same process is still holding a shared lock. */
  28217. rc = SQLITE_BUSY;
  28218. } else {
  28219. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  28220. }
  28221. }else{
  28222. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
  28223. }
  28224. if( rc==SQLITE_OK ){
  28225. char writeBuffer[PROXY_MAXCONCHLEN];
  28226. int writeSize = 0;
  28227. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  28228. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  28229. if( pCtx->lockProxyPath!=NULL ){
  28230. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
  28231. }else{
  28232. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  28233. }
  28234. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  28235. robust_ftruncate(conchFile->h, writeSize);
  28236. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  28237. fsync(conchFile->h);
  28238. /* If we created a new conch file (not just updated the contents of a
  28239. ** valid conch file), try to match the permissions of the database
  28240. */
  28241. if( rc==SQLITE_OK && createConch ){
  28242. struct stat buf;
  28243. int err = osFstat(pFile->h, &buf);
  28244. if( err==0 ){
  28245. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  28246. S_IROTH|S_IWOTH);
  28247. /* try to match the database file R/W permissions, ignore failure */
  28248. #ifndef SQLITE_PROXY_DEBUG
  28249. osFchmod(conchFile->h, cmode);
  28250. #else
  28251. do{
  28252. rc = osFchmod(conchFile->h, cmode);
  28253. }while( rc==(-1) && errno==EINTR );
  28254. if( rc!=0 ){
  28255. int code = errno;
  28256. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  28257. cmode, code, strerror(code));
  28258. } else {
  28259. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  28260. }
  28261. }else{
  28262. int code = errno;
  28263. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  28264. err, code, strerror(code));
  28265. #endif
  28266. }
  28267. }
  28268. }
  28269. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  28270. end_takeconch:
  28271. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  28272. if( rc==SQLITE_OK && pFile->openFlags ){
  28273. int fd;
  28274. if( pFile->h>=0 ){
  28275. robust_close(pFile, pFile->h, __LINE__);
  28276. }
  28277. pFile->h = -1;
  28278. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  28279. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  28280. if( fd>=0 ){
  28281. pFile->h = fd;
  28282. }else{
  28283. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  28284. during locking */
  28285. }
  28286. }
  28287. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  28288. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  28289. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  28290. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  28291. /* we couldn't create the proxy lock file with the old lock file path
  28292. ** so try again via auto-naming
  28293. */
  28294. forceNewLockPath = 1;
  28295. tryOldLockPath = 0;
  28296. continue; /* go back to the do {} while start point, try again */
  28297. }
  28298. }
  28299. if( rc==SQLITE_OK ){
  28300. /* Need to make a copy of path if we extracted the value
  28301. ** from the conch file or the path was allocated on the stack
  28302. */
  28303. if( tempLockPath ){
  28304. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  28305. if( !pCtx->lockProxyPath ){
  28306. rc = SQLITE_NOMEM;
  28307. }
  28308. }
  28309. }
  28310. if( rc==SQLITE_OK ){
  28311. pCtx->conchHeld = 1;
  28312. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  28313. afpLockingContext *afpCtx;
  28314. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  28315. afpCtx->dbPath = pCtx->lockProxyPath;
  28316. }
  28317. } else {
  28318. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  28319. }
  28320. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  28321. rc==SQLITE_OK?"ok":"failed"));
  28322. return rc;
  28323. } while (1); /* in case we need to retry the :auto: lock file -
  28324. ** we should never get here except via the 'continue' call. */
  28325. }
  28326. }
  28327. /*
  28328. ** If pFile holds a lock on a conch file, then release that lock.
  28329. */
  28330. static int proxyReleaseConch(unixFile *pFile){
  28331. int rc = SQLITE_OK; /* Subroutine return code */
  28332. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  28333. unixFile *conchFile; /* Name of the conch file */
  28334. pCtx = (proxyLockingContext *)pFile->lockingContext;
  28335. conchFile = pCtx->conchFile;
  28336. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  28337. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  28338. getpid()));
  28339. if( pCtx->conchHeld>0 ){
  28340. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  28341. }
  28342. pCtx->conchHeld = 0;
  28343. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  28344. (rc==SQLITE_OK ? "ok" : "failed")));
  28345. return rc;
  28346. }
  28347. /*
  28348. ** Given the name of a database file, compute the name of its conch file.
  28349. ** Store the conch filename in memory obtained from sqlite3_malloc().
  28350. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  28351. ** or SQLITE_NOMEM if unable to obtain memory.
  28352. **
  28353. ** The caller is responsible for ensuring that the allocated memory
  28354. ** space is eventually freed.
  28355. **
  28356. ** *pConchPath is set to NULL if a memory allocation error occurs.
  28357. */
  28358. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  28359. int i; /* Loop counter */
  28360. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  28361. char *conchPath; /* buffer in which to construct conch name */
  28362. /* Allocate space for the conch filename and initialize the name to
  28363. ** the name of the original database file. */
  28364. *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
  28365. if( conchPath==0 ){
  28366. return SQLITE_NOMEM;
  28367. }
  28368. memcpy(conchPath, dbPath, len+1);
  28369. /* now insert a "." before the last / character */
  28370. for( i=(len-1); i>=0; i-- ){
  28371. if( conchPath[i]=='/' ){
  28372. i++;
  28373. break;
  28374. }
  28375. }
  28376. conchPath[i]='.';
  28377. while ( i<len ){
  28378. conchPath[i+1]=dbPath[i];
  28379. i++;
  28380. }
  28381. /* append the "-conch" suffix to the file */
  28382. memcpy(&conchPath[i+1], "-conch", 7);
  28383. assert( (int)strlen(conchPath) == len+7 );
  28384. return SQLITE_OK;
  28385. }
  28386. /* Takes a fully configured proxy locking-style unix file and switches
  28387. ** the local lock file path
  28388. */
  28389. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  28390. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  28391. char *oldPath = pCtx->lockProxyPath;
  28392. int rc = SQLITE_OK;
  28393. if( pFile->eFileLock!=NO_LOCK ){
  28394. return SQLITE_BUSY;
  28395. }
  28396. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  28397. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  28398. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  28399. return SQLITE_OK;
  28400. }else{
  28401. unixFile *lockProxy = pCtx->lockProxy;
  28402. pCtx->lockProxy=NULL;
  28403. pCtx->conchHeld = 0;
  28404. if( lockProxy!=NULL ){
  28405. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  28406. if( rc ) return rc;
  28407. sqlite3_free(lockProxy);
  28408. }
  28409. sqlite3_free(oldPath);
  28410. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  28411. }
  28412. return rc;
  28413. }
  28414. /*
  28415. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  28416. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  28417. **
  28418. ** This routine find the filename associated with pFile and writes it
  28419. ** int dbPath.
  28420. */
  28421. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  28422. #if defined(__APPLE__)
  28423. if( pFile->pMethod == &afpIoMethods ){
  28424. /* afp style keeps a reference to the db path in the filePath field
  28425. ** of the struct */
  28426. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  28427. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
  28428. } else
  28429. #endif
  28430. if( pFile->pMethod == &dotlockIoMethods ){
  28431. /* dot lock style uses the locking context to store the dot lock
  28432. ** file path */
  28433. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  28434. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  28435. }else{
  28436. /* all other styles use the locking context to store the db file path */
  28437. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  28438. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  28439. }
  28440. return SQLITE_OK;
  28441. }
  28442. /*
  28443. ** Takes an already filled in unix file and alters it so all file locking
  28444. ** will be performed on the local proxy lock file. The following fields
  28445. ** are preserved in the locking context so that they can be restored and
  28446. ** the unix structure properly cleaned up at close time:
  28447. ** ->lockingContext
  28448. ** ->pMethod
  28449. */
  28450. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  28451. proxyLockingContext *pCtx;
  28452. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  28453. char *lockPath=NULL;
  28454. int rc = SQLITE_OK;
  28455. if( pFile->eFileLock!=NO_LOCK ){
  28456. return SQLITE_BUSY;
  28457. }
  28458. proxyGetDbPathForUnixFile(pFile, dbPath);
  28459. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  28460. lockPath=NULL;
  28461. }else{
  28462. lockPath=(char *)path;
  28463. }
  28464. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  28465. (lockPath ? lockPath : ":auto:"), getpid()));
  28466. pCtx = sqlite3_malloc( sizeof(*pCtx) );
  28467. if( pCtx==0 ){
  28468. return SQLITE_NOMEM;
  28469. }
  28470. memset(pCtx, 0, sizeof(*pCtx));
  28471. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  28472. if( rc==SQLITE_OK ){
  28473. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  28474. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  28475. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  28476. ** (c) the file system is read-only, then enable no-locking access.
  28477. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  28478. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  28479. */
  28480. struct statfs fsInfo;
  28481. struct stat conchInfo;
  28482. int goLockless = 0;
  28483. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  28484. int err = errno;
  28485. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  28486. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  28487. }
  28488. }
  28489. if( goLockless ){
  28490. pCtx->conchHeld = -1; /* read only FS/ lockless */
  28491. rc = SQLITE_OK;
  28492. }
  28493. }
  28494. }
  28495. if( rc==SQLITE_OK && lockPath ){
  28496. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  28497. }
  28498. if( rc==SQLITE_OK ){
  28499. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  28500. if( pCtx->dbPath==NULL ){
  28501. rc = SQLITE_NOMEM;
  28502. }
  28503. }
  28504. if( rc==SQLITE_OK ){
  28505. /* all memory is allocated, proxys are created and assigned,
  28506. ** switch the locking context and pMethod then return.
  28507. */
  28508. pCtx->oldLockingContext = pFile->lockingContext;
  28509. pFile->lockingContext = pCtx;
  28510. pCtx->pOldMethod = pFile->pMethod;
  28511. pFile->pMethod = &proxyIoMethods;
  28512. }else{
  28513. if( pCtx->conchFile ){
  28514. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  28515. sqlite3_free(pCtx->conchFile);
  28516. }
  28517. sqlite3DbFree(0, pCtx->lockProxyPath);
  28518. sqlite3_free(pCtx->conchFilePath);
  28519. sqlite3_free(pCtx);
  28520. }
  28521. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  28522. (rc==SQLITE_OK ? "ok" : "failed")));
  28523. return rc;
  28524. }
  28525. /*
  28526. ** This routine handles sqlite3_file_control() calls that are specific
  28527. ** to proxy locking.
  28528. */
  28529. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  28530. switch( op ){
  28531. case SQLITE_GET_LOCKPROXYFILE: {
  28532. unixFile *pFile = (unixFile*)id;
  28533. if( pFile->pMethod == &proxyIoMethods ){
  28534. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  28535. proxyTakeConch(pFile);
  28536. if( pCtx->lockProxyPath ){
  28537. *(const char **)pArg = pCtx->lockProxyPath;
  28538. }else{
  28539. *(const char **)pArg = ":auto: (not held)";
  28540. }
  28541. } else {
  28542. *(const char **)pArg = NULL;
  28543. }
  28544. return SQLITE_OK;
  28545. }
  28546. case SQLITE_SET_LOCKPROXYFILE: {
  28547. unixFile *pFile = (unixFile*)id;
  28548. int rc = SQLITE_OK;
  28549. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  28550. if( pArg==NULL || (const char *)pArg==0 ){
  28551. if( isProxyStyle ){
  28552. /* turn off proxy locking - not supported */
  28553. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  28554. }else{
  28555. /* turn off proxy locking - already off - NOOP */
  28556. rc = SQLITE_OK;
  28557. }
  28558. }else{
  28559. const char *proxyPath = (const char *)pArg;
  28560. if( isProxyStyle ){
  28561. proxyLockingContext *pCtx =
  28562. (proxyLockingContext*)pFile->lockingContext;
  28563. if( !strcmp(pArg, ":auto:")
  28564. || (pCtx->lockProxyPath &&
  28565. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  28566. ){
  28567. rc = SQLITE_OK;
  28568. }else{
  28569. rc = switchLockProxyPath(pFile, proxyPath);
  28570. }
  28571. }else{
  28572. /* turn on proxy file locking */
  28573. rc = proxyTransformUnixFile(pFile, proxyPath);
  28574. }
  28575. }
  28576. return rc;
  28577. }
  28578. default: {
  28579. assert( 0 ); /* The call assures that only valid opcodes are sent */
  28580. }
  28581. }
  28582. /*NOTREACHED*/
  28583. return SQLITE_ERROR;
  28584. }
  28585. /*
  28586. ** Within this division (the proxying locking implementation) the procedures
  28587. ** above this point are all utilities. The lock-related methods of the
  28588. ** proxy-locking sqlite3_io_method object follow.
  28589. */
  28590. /*
  28591. ** This routine checks if there is a RESERVED lock held on the specified
  28592. ** file by this or any other process. If such a lock is held, set *pResOut
  28593. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  28594. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  28595. */
  28596. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  28597. unixFile *pFile = (unixFile*)id;
  28598. int rc = proxyTakeConch(pFile);
  28599. if( rc==SQLITE_OK ){
  28600. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28601. if( pCtx->conchHeld>0 ){
  28602. unixFile *proxy = pCtx->lockProxy;
  28603. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  28604. }else{ /* conchHeld < 0 is lockless */
  28605. pResOut=0;
  28606. }
  28607. }
  28608. return rc;
  28609. }
  28610. /*
  28611. ** Lock the file with the lock specified by parameter eFileLock - one
  28612. ** of the following:
  28613. **
  28614. ** (1) SHARED_LOCK
  28615. ** (2) RESERVED_LOCK
  28616. ** (3) PENDING_LOCK
  28617. ** (4) EXCLUSIVE_LOCK
  28618. **
  28619. ** Sometimes when requesting one lock state, additional lock states
  28620. ** are inserted in between. The locking might fail on one of the later
  28621. ** transitions leaving the lock state different from what it started but
  28622. ** still short of its goal. The following chart shows the allowed
  28623. ** transitions and the inserted intermediate states:
  28624. **
  28625. ** UNLOCKED -> SHARED
  28626. ** SHARED -> RESERVED
  28627. ** SHARED -> (PENDING) -> EXCLUSIVE
  28628. ** RESERVED -> (PENDING) -> EXCLUSIVE
  28629. ** PENDING -> EXCLUSIVE
  28630. **
  28631. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  28632. ** routine to lower a locking level.
  28633. */
  28634. static int proxyLock(sqlite3_file *id, int eFileLock) {
  28635. unixFile *pFile = (unixFile*)id;
  28636. int rc = proxyTakeConch(pFile);
  28637. if( rc==SQLITE_OK ){
  28638. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28639. if( pCtx->conchHeld>0 ){
  28640. unixFile *proxy = pCtx->lockProxy;
  28641. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  28642. pFile->eFileLock = proxy->eFileLock;
  28643. }else{
  28644. /* conchHeld < 0 is lockless */
  28645. }
  28646. }
  28647. return rc;
  28648. }
  28649. /*
  28650. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28651. ** must be either NO_LOCK or SHARED_LOCK.
  28652. **
  28653. ** If the locking level of the file descriptor is already at or below
  28654. ** the requested locking level, this routine is a no-op.
  28655. */
  28656. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  28657. unixFile *pFile = (unixFile*)id;
  28658. int rc = proxyTakeConch(pFile);
  28659. if( rc==SQLITE_OK ){
  28660. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28661. if( pCtx->conchHeld>0 ){
  28662. unixFile *proxy = pCtx->lockProxy;
  28663. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  28664. pFile->eFileLock = proxy->eFileLock;
  28665. }else{
  28666. /* conchHeld < 0 is lockless */
  28667. }
  28668. }
  28669. return rc;
  28670. }
  28671. /*
  28672. ** Close a file that uses proxy locks.
  28673. */
  28674. static int proxyClose(sqlite3_file *id) {
  28675. if( id ){
  28676. unixFile *pFile = (unixFile*)id;
  28677. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28678. unixFile *lockProxy = pCtx->lockProxy;
  28679. unixFile *conchFile = pCtx->conchFile;
  28680. int rc = SQLITE_OK;
  28681. if( lockProxy ){
  28682. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  28683. if( rc ) return rc;
  28684. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  28685. if( rc ) return rc;
  28686. sqlite3_free(lockProxy);
  28687. pCtx->lockProxy = 0;
  28688. }
  28689. if( conchFile ){
  28690. if( pCtx->conchHeld ){
  28691. rc = proxyReleaseConch(pFile);
  28692. if( rc ) return rc;
  28693. }
  28694. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  28695. if( rc ) return rc;
  28696. sqlite3_free(conchFile);
  28697. }
  28698. sqlite3DbFree(0, pCtx->lockProxyPath);
  28699. sqlite3_free(pCtx->conchFilePath);
  28700. sqlite3DbFree(0, pCtx->dbPath);
  28701. /* restore the original locking context and pMethod then close it */
  28702. pFile->lockingContext = pCtx->oldLockingContext;
  28703. pFile->pMethod = pCtx->pOldMethod;
  28704. sqlite3_free(pCtx);
  28705. return pFile->pMethod->xClose(id);
  28706. }
  28707. return SQLITE_OK;
  28708. }
  28709. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28710. /*
  28711. ** The proxy locking style is intended for use with AFP filesystems.
  28712. ** And since AFP is only supported on MacOSX, the proxy locking is also
  28713. ** restricted to MacOSX.
  28714. **
  28715. **
  28716. ******************* End of the proxy lock implementation **********************
  28717. ******************************************************************************/
  28718. /*
  28719. ** Initialize the operating system interface.
  28720. **
  28721. ** This routine registers all VFS implementations for unix-like operating
  28722. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  28723. ** should be the only routines in this file that are visible from other
  28724. ** files.
  28725. **
  28726. ** This routine is called once during SQLite initialization and by a
  28727. ** single thread. The memory allocation and mutex subsystems have not
  28728. ** necessarily been initialized when this routine is called, and so they
  28729. ** should not be used.
  28730. */
  28731. SQLITE_API int sqlite3_os_init(void){
  28732. /*
  28733. ** The following macro defines an initializer for an sqlite3_vfs object.
  28734. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  28735. ** to the "finder" function. (pAppData is a pointer to a pointer because
  28736. ** silly C90 rules prohibit a void* from being cast to a function pointer
  28737. ** and so we have to go through the intermediate pointer to avoid problems
  28738. ** when compiling with -pedantic-errors on GCC.)
  28739. **
  28740. ** The FINDER parameter to this macro is the name of the pointer to the
  28741. ** finder-function. The finder-function returns a pointer to the
  28742. ** sqlite_io_methods object that implements the desired locking
  28743. ** behaviors. See the division above that contains the IOMETHODS
  28744. ** macro for addition information on finder-functions.
  28745. **
  28746. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  28747. ** object. But the "autolockIoFinder" available on MacOSX does a little
  28748. ** more than that; it looks at the filesystem type that hosts the
  28749. ** database file and tries to choose an locking method appropriate for
  28750. ** that filesystem time.
  28751. */
  28752. #define UNIXVFS(VFSNAME, FINDER) { \
  28753. 3, /* iVersion */ \
  28754. sizeof(unixFile), /* szOsFile */ \
  28755. MAX_PATHNAME, /* mxPathname */ \
  28756. 0, /* pNext */ \
  28757. VFSNAME, /* zName */ \
  28758. (void*)&FINDER, /* pAppData */ \
  28759. unixOpen, /* xOpen */ \
  28760. unixDelete, /* xDelete */ \
  28761. unixAccess, /* xAccess */ \
  28762. unixFullPathname, /* xFullPathname */ \
  28763. unixDlOpen, /* xDlOpen */ \
  28764. unixDlError, /* xDlError */ \
  28765. unixDlSym, /* xDlSym */ \
  28766. unixDlClose, /* xDlClose */ \
  28767. unixRandomness, /* xRandomness */ \
  28768. unixSleep, /* xSleep */ \
  28769. unixCurrentTime, /* xCurrentTime */ \
  28770. unixGetLastError, /* xGetLastError */ \
  28771. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  28772. unixSetSystemCall, /* xSetSystemCall */ \
  28773. unixGetSystemCall, /* xGetSystemCall */ \
  28774. unixNextSystemCall, /* xNextSystemCall */ \
  28775. }
  28776. /*
  28777. ** All default VFSes for unix are contained in the following array.
  28778. **
  28779. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  28780. ** by the SQLite core when the VFS is registered. So the following
  28781. ** array cannot be const.
  28782. */
  28783. static sqlite3_vfs aVfs[] = {
  28784. #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
  28785. UNIXVFS("unix", autolockIoFinder ),
  28786. #else
  28787. UNIXVFS("unix", posixIoFinder ),
  28788. #endif
  28789. UNIXVFS("unix-none", nolockIoFinder ),
  28790. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  28791. UNIXVFS("unix-excl", posixIoFinder ),
  28792. #if OS_VXWORKS
  28793. UNIXVFS("unix-namedsem", semIoFinder ),
  28794. #endif
  28795. #if SQLITE_ENABLE_LOCKING_STYLE
  28796. UNIXVFS("unix-posix", posixIoFinder ),
  28797. #if !OS_VXWORKS
  28798. UNIXVFS("unix-flock", flockIoFinder ),
  28799. #endif
  28800. #endif
  28801. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28802. UNIXVFS("unix-afp", afpIoFinder ),
  28803. UNIXVFS("unix-nfs", nfsIoFinder ),
  28804. UNIXVFS("unix-proxy", proxyIoFinder ),
  28805. #endif
  28806. };
  28807. unsigned int i; /* Loop counter */
  28808. /* Double-check that the aSyscall[] array has been constructed
  28809. ** correctly. See ticket [bb3a86e890c8e96ab] */
  28810. assert( ArraySize(aSyscall)==24 );
  28811. /* Register all VFSes defined in the aVfs[] array */
  28812. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  28813. sqlite3_vfs_register(&aVfs[i], i==0);
  28814. }
  28815. return SQLITE_OK;
  28816. }
  28817. /*
  28818. ** Shutdown the operating system interface.
  28819. **
  28820. ** Some operating systems might need to do some cleanup in this routine,
  28821. ** to release dynamically allocated objects. But not on unix.
  28822. ** This routine is a no-op for unix.
  28823. */
  28824. SQLITE_API int sqlite3_os_end(void){
  28825. return SQLITE_OK;
  28826. }
  28827. #endif /* SQLITE_OS_UNIX */
  28828. /************** End of os_unix.c *********************************************/
  28829. /************** Begin file os_win.c ******************************************/
  28830. /*
  28831. ** 2004 May 22
  28832. **
  28833. ** The author disclaims copyright to this source code. In place of
  28834. ** a legal notice, here is a blessing:
  28835. **
  28836. ** May you do good and not evil.
  28837. ** May you find forgiveness for yourself and forgive others.
  28838. ** May you share freely, never taking more than you give.
  28839. **
  28840. ******************************************************************************
  28841. **
  28842. ** This file contains code that is specific to Windows.
  28843. */
  28844. #if SQLITE_OS_WIN /* This file is used for Windows only */
  28845. #ifdef __CYGWIN__
  28846. # include <sys/cygwin.h>
  28847. # include <errno.h> /* amalgamator: keep */
  28848. #endif
  28849. /*
  28850. ** Include code that is common to all os_*.c files
  28851. */
  28852. /************** Include os_common.h in the middle of os_win.c ****************/
  28853. /************** Begin file os_common.h ***************************************/
  28854. /*
  28855. ** 2004 May 22
  28856. **
  28857. ** The author disclaims copyright to this source code. In place of
  28858. ** a legal notice, here is a blessing:
  28859. **
  28860. ** May you do good and not evil.
  28861. ** May you find forgiveness for yourself and forgive others.
  28862. ** May you share freely, never taking more than you give.
  28863. **
  28864. ******************************************************************************
  28865. **
  28866. ** This file contains macros and a little bit of code that is common to
  28867. ** all of the platform-specific files (os_*.c) and is #included into those
  28868. ** files.
  28869. **
  28870. ** This file should be #included by the os_*.c files only. It is not a
  28871. ** general purpose header file.
  28872. */
  28873. #ifndef _OS_COMMON_H_
  28874. #define _OS_COMMON_H_
  28875. /*
  28876. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  28877. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  28878. ** switch. The following code should catch this problem at compile-time.
  28879. */
  28880. #ifdef MEMORY_DEBUG
  28881. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  28882. #endif
  28883. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  28884. # ifndef SQLITE_DEBUG_OS_TRACE
  28885. # define SQLITE_DEBUG_OS_TRACE 0
  28886. # endif
  28887. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  28888. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  28889. #else
  28890. # define OSTRACE(X)
  28891. #endif
  28892. /*
  28893. ** Macros for performance tracing. Normally turned off. Only works
  28894. ** on i486 hardware.
  28895. */
  28896. #ifdef SQLITE_PERFORMANCE_TRACE
  28897. /*
  28898. ** hwtime.h contains inline assembler code for implementing
  28899. ** high-performance timing routines.
  28900. */
  28901. /************** Include hwtime.h in the middle of os_common.h ****************/
  28902. /************** Begin file hwtime.h ******************************************/
  28903. /*
  28904. ** 2008 May 27
  28905. **
  28906. ** The author disclaims copyright to this source code. In place of
  28907. ** a legal notice, here is a blessing:
  28908. **
  28909. ** May you do good and not evil.
  28910. ** May you find forgiveness for yourself and forgive others.
  28911. ** May you share freely, never taking more than you give.
  28912. **
  28913. ******************************************************************************
  28914. **
  28915. ** This file contains inline asm code for retrieving "high-performance"
  28916. ** counters for x86 class CPUs.
  28917. */
  28918. #ifndef _HWTIME_H_
  28919. #define _HWTIME_H_
  28920. /*
  28921. ** The following routine only works on pentium-class (or newer) processors.
  28922. ** It uses the RDTSC opcode to read the cycle count value out of the
  28923. ** processor and returns that value. This can be used for high-res
  28924. ** profiling.
  28925. */
  28926. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  28927. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  28928. #if defined(__GNUC__)
  28929. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28930. unsigned int lo, hi;
  28931. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  28932. return (sqlite_uint64)hi << 32 | lo;
  28933. }
  28934. #elif defined(_MSC_VER)
  28935. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  28936. __asm {
  28937. rdtsc
  28938. ret ; return value at EDX:EAX
  28939. }
  28940. }
  28941. #endif
  28942. #elif (defined(__GNUC__) && defined(__x86_64__))
  28943. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28944. unsigned long val;
  28945. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  28946. return val;
  28947. }
  28948. #elif (defined(__GNUC__) && defined(__ppc__))
  28949. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28950. unsigned long long retval;
  28951. unsigned long junk;
  28952. __asm__ __volatile__ ("\n\
  28953. 1: mftbu %1\n\
  28954. mftb %L0\n\
  28955. mftbu %0\n\
  28956. cmpw %0,%1\n\
  28957. bne 1b"
  28958. : "=r" (retval), "=r" (junk));
  28959. return retval;
  28960. }
  28961. #else
  28962. #error Need implementation of sqlite3Hwtime() for your platform.
  28963. /*
  28964. ** To compile without implementing sqlite3Hwtime() for your platform,
  28965. ** you can remove the above #error and use the following
  28966. ** stub function. You will lose timing support for many
  28967. ** of the debugging and testing utilities, but it should at
  28968. ** least compile and run.
  28969. */
  28970. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  28971. #endif
  28972. #endif /* !defined(_HWTIME_H_) */
  28973. /************** End of hwtime.h **********************************************/
  28974. /************** Continuing where we left off in os_common.h ******************/
  28975. static sqlite_uint64 g_start;
  28976. static sqlite_uint64 g_elapsed;
  28977. #define TIMER_START g_start=sqlite3Hwtime()
  28978. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  28979. #define TIMER_ELAPSED g_elapsed
  28980. #else
  28981. #define TIMER_START
  28982. #define TIMER_END
  28983. #define TIMER_ELAPSED ((sqlite_uint64)0)
  28984. #endif
  28985. /*
  28986. ** If we compile with the SQLITE_TEST macro set, then the following block
  28987. ** of code will give us the ability to simulate a disk I/O error. This
  28988. ** is used for testing the I/O recovery logic.
  28989. */
  28990. #ifdef SQLITE_TEST
  28991. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  28992. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  28993. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  28994. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  28995. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  28996. SQLITE_API int sqlite3_diskfull_pending = 0;
  28997. SQLITE_API int sqlite3_diskfull = 0;
  28998. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  28999. #define SimulateIOError(CODE) \
  29000. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  29001. || sqlite3_io_error_pending-- == 1 ) \
  29002. { local_ioerr(); CODE; }
  29003. static void local_ioerr(){
  29004. IOTRACE(("IOERR\n"));
  29005. sqlite3_io_error_hit++;
  29006. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  29007. }
  29008. #define SimulateDiskfullError(CODE) \
  29009. if( sqlite3_diskfull_pending ){ \
  29010. if( sqlite3_diskfull_pending == 1 ){ \
  29011. local_ioerr(); \
  29012. sqlite3_diskfull = 1; \
  29013. sqlite3_io_error_hit = 1; \
  29014. CODE; \
  29015. }else{ \
  29016. sqlite3_diskfull_pending--; \
  29017. } \
  29018. }
  29019. #else
  29020. #define SimulateIOErrorBenign(X)
  29021. #define SimulateIOError(A)
  29022. #define SimulateDiskfullError(A)
  29023. #endif
  29024. /*
  29025. ** When testing, keep a count of the number of open files.
  29026. */
  29027. #ifdef SQLITE_TEST
  29028. SQLITE_API int sqlite3_open_file_count = 0;
  29029. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  29030. #else
  29031. #define OpenCounter(X)
  29032. #endif
  29033. #endif /* !defined(_OS_COMMON_H_) */
  29034. /************** End of os_common.h *******************************************/
  29035. /************** Continuing where we left off in os_win.c *********************/
  29036. /*
  29037. ** Compiling and using WAL mode requires several APIs that are only
  29038. ** available in Windows platforms based on the NT kernel.
  29039. */
  29040. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  29041. # error "WAL mode requires support from the Windows NT kernel, compile\
  29042. with SQLITE_OMIT_WAL."
  29043. #endif
  29044. /*
  29045. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  29046. ** based on the sub-platform)?
  29047. */
  29048. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  29049. # define SQLITE_WIN32_HAS_ANSI
  29050. #endif
  29051. /*
  29052. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  29053. ** based on the sub-platform)?
  29054. */
  29055. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  29056. !defined(SQLITE_WIN32_NO_WIDE)
  29057. # define SQLITE_WIN32_HAS_WIDE
  29058. #endif
  29059. /*
  29060. ** Make sure at least one set of Win32 APIs is available.
  29061. */
  29062. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  29063. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  29064. must be defined."
  29065. #endif
  29066. /*
  29067. ** Maximum pathname length (in chars) for Win32. This should normally be
  29068. ** MAX_PATH.
  29069. */
  29070. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  29071. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  29072. #endif
  29073. /*
  29074. ** Maximum pathname length (in chars) for WinNT. This should normally be
  29075. ** 32767.
  29076. */
  29077. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  29078. # define SQLITE_WINNT_MAX_PATH_CHARS (32767)
  29079. #endif
  29080. /*
  29081. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  29082. ** characters, so we allocate 3 bytes per character assuming worst-case of
  29083. ** 4-bytes-per-character for UTF8.
  29084. */
  29085. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  29086. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  29087. #endif
  29088. /*
  29089. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  29090. ** 32767 * sizeof(WCHAR).
  29091. */
  29092. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  29093. # define SQLITE_WINNT_MAX_PATH_BYTES \
  29094. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  29095. #endif
  29096. /*
  29097. ** Maximum error message length (in chars) for WinRT.
  29098. */
  29099. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  29100. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  29101. #endif
  29102. /*
  29103. ** Returns non-zero if the character should be treated as a directory
  29104. ** separator.
  29105. */
  29106. #ifndef winIsDirSep
  29107. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  29108. #endif
  29109. /*
  29110. ** This macro is used when a local variable is set to a value that is
  29111. ** [sometimes] not used by the code (e.g. via conditional compilation).
  29112. */
  29113. #ifndef UNUSED_VARIABLE_VALUE
  29114. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  29115. #endif
  29116. /*
  29117. ** Returns the string that should be used as the directory separator.
  29118. */
  29119. #ifndef winGetDirDep
  29120. # ifdef __CYGWIN__
  29121. # define winGetDirDep() "/"
  29122. # else
  29123. # define winGetDirDep() "\\"
  29124. # endif
  29125. #endif
  29126. /*
  29127. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  29128. ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
  29129. ** are not present in the header file)?
  29130. */
  29131. #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
  29132. /*
  29133. ** Two of the file mapping APIs are different under WinRT. Figure out which
  29134. ** set we need.
  29135. */
  29136. #if SQLITE_OS_WINRT
  29137. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  29138. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  29139. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  29140. #else
  29141. #if defined(SQLITE_WIN32_HAS_ANSI)
  29142. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  29143. DWORD, DWORD, DWORD, LPCSTR);
  29144. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  29145. #if defined(SQLITE_WIN32_HAS_WIDE)
  29146. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  29147. DWORD, DWORD, DWORD, LPCWSTR);
  29148. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  29149. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  29150. #endif /* SQLITE_OS_WINRT */
  29151. /*
  29152. ** This file mapping API is common to both Win32 and WinRT.
  29153. */
  29154. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  29155. #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
  29156. /*
  29157. ** Some Microsoft compilers lack this definition.
  29158. */
  29159. #ifndef INVALID_FILE_ATTRIBUTES
  29160. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  29161. #endif
  29162. #ifndef FILE_FLAG_MASK
  29163. # define FILE_FLAG_MASK (0xFF3C0000)
  29164. #endif
  29165. #ifndef FILE_ATTRIBUTE_MASK
  29166. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  29167. #endif
  29168. #ifndef SQLITE_OMIT_WAL
  29169. /* Forward references to structures used for WAL */
  29170. typedef struct winShm winShm; /* A connection to shared-memory */
  29171. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  29172. #endif
  29173. /*
  29174. ** WinCE lacks native support for file locking so we have to fake it
  29175. ** with some code of our own.
  29176. */
  29177. #if SQLITE_OS_WINCE
  29178. typedef struct winceLock {
  29179. int nReaders; /* Number of reader locks obtained */
  29180. BOOL bPending; /* Indicates a pending lock has been obtained */
  29181. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  29182. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  29183. } winceLock;
  29184. #endif
  29185. /*
  29186. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  29187. ** portability layer.
  29188. */
  29189. typedef struct winFile winFile;
  29190. struct winFile {
  29191. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  29192. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  29193. HANDLE h; /* Handle for accessing the file */
  29194. u8 locktype; /* Type of lock currently held on this file */
  29195. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  29196. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  29197. DWORD lastErrno; /* The Windows errno from the last I/O error */
  29198. #ifndef SQLITE_OMIT_WAL
  29199. winShm *pShm; /* Instance of shared memory on this file */
  29200. #endif
  29201. const char *zPath; /* Full pathname of this file */
  29202. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  29203. #if SQLITE_OS_WINCE
  29204. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  29205. HANDLE hMutex; /* Mutex used to control access to shared lock */
  29206. HANDLE hShared; /* Shared memory segment used for locking */
  29207. winceLock local; /* Locks obtained by this instance of winFile */
  29208. winceLock *shared; /* Global shared lock memory for the file */
  29209. #endif
  29210. #if SQLITE_MAX_MMAP_SIZE>0
  29211. int nFetchOut; /* Number of outstanding xFetch references */
  29212. HANDLE hMap; /* Handle for accessing memory mapping */
  29213. void *pMapRegion; /* Area memory mapped */
  29214. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  29215. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  29216. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  29217. #endif
  29218. };
  29219. /*
  29220. ** Allowed values for winFile.ctrlFlags
  29221. */
  29222. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  29223. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  29224. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  29225. /*
  29226. * The size of the buffer used by sqlite3_win32_write_debug().
  29227. */
  29228. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  29229. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  29230. #endif
  29231. /*
  29232. * The value used with sqlite3_win32_set_directory() to specify that
  29233. * the data directory should be changed.
  29234. */
  29235. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  29236. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  29237. #endif
  29238. /*
  29239. * The value used with sqlite3_win32_set_directory() to specify that
  29240. * the temporary directory should be changed.
  29241. */
  29242. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  29243. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  29244. #endif
  29245. /*
  29246. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  29247. * various Win32 API heap functions instead of our own.
  29248. */
  29249. #ifdef SQLITE_WIN32_MALLOC
  29250. /*
  29251. * If this is non-zero, an isolated heap will be created by the native Win32
  29252. * allocator subsystem; otherwise, the default process heap will be used. This
  29253. * setting has no effect when compiling for WinRT. By default, this is enabled
  29254. * and an isolated heap will be created to store all allocated data.
  29255. *
  29256. ******************************************************************************
  29257. * WARNING: It is important to note that when this setting is non-zero and the
  29258. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  29259. * function), all data that was allocated using the isolated heap will
  29260. * be freed immediately and any attempt to access any of that freed
  29261. * data will almost certainly result in an immediate access violation.
  29262. ******************************************************************************
  29263. */
  29264. #ifndef SQLITE_WIN32_HEAP_CREATE
  29265. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  29266. #endif
  29267. /*
  29268. * The initial size of the Win32-specific heap. This value may be zero.
  29269. */
  29270. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  29271. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  29272. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  29273. #endif
  29274. /*
  29275. * The maximum size of the Win32-specific heap. This value may be zero.
  29276. */
  29277. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  29278. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  29279. #endif
  29280. /*
  29281. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  29282. * zero for the default behavior.
  29283. */
  29284. #ifndef SQLITE_WIN32_HEAP_FLAGS
  29285. # define SQLITE_WIN32_HEAP_FLAGS (0)
  29286. #endif
  29287. /*
  29288. ** The winMemData structure stores information required by the Win32-specific
  29289. ** sqlite3_mem_methods implementation.
  29290. */
  29291. typedef struct winMemData winMemData;
  29292. struct winMemData {
  29293. #ifndef NDEBUG
  29294. u32 magic; /* Magic number to detect structure corruption. */
  29295. #endif
  29296. HANDLE hHeap; /* The handle to our heap. */
  29297. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  29298. };
  29299. #ifndef NDEBUG
  29300. #define WINMEM_MAGIC 0x42b2830b
  29301. #endif
  29302. static struct winMemData win_mem_data = {
  29303. #ifndef NDEBUG
  29304. WINMEM_MAGIC,
  29305. #endif
  29306. NULL, FALSE
  29307. };
  29308. #ifndef NDEBUG
  29309. #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
  29310. #else
  29311. #define winMemAssertMagic()
  29312. #endif
  29313. #define winMemGetHeap() win_mem_data.hHeap
  29314. static void *winMemMalloc(int nBytes);
  29315. static void winMemFree(void *pPrior);
  29316. static void *winMemRealloc(void *pPrior, int nBytes);
  29317. static int winMemSize(void *p);
  29318. static int winMemRoundup(int n);
  29319. static int winMemInit(void *pAppData);
  29320. static void winMemShutdown(void *pAppData);
  29321. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  29322. #endif /* SQLITE_WIN32_MALLOC */
  29323. /*
  29324. ** The following variable is (normally) set once and never changes
  29325. ** thereafter. It records whether the operating system is Win9x
  29326. ** or WinNT.
  29327. **
  29328. ** 0: Operating system unknown.
  29329. ** 1: Operating system is Win9x.
  29330. ** 2: Operating system is WinNT.
  29331. **
  29332. ** In order to facilitate testing on a WinNT system, the test fixture
  29333. ** can manually set this value to 1 to emulate Win98 behavior.
  29334. */
  29335. #ifdef SQLITE_TEST
  29336. SQLITE_API int sqlite3_os_type = 0;
  29337. #elif !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  29338. defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_HAS_WIDE)
  29339. static int sqlite3_os_type = 0;
  29340. #endif
  29341. #ifndef SYSCALL
  29342. # define SYSCALL sqlite3_syscall_ptr
  29343. #endif
  29344. /*
  29345. ** This function is not available on Windows CE or WinRT.
  29346. */
  29347. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  29348. # define osAreFileApisANSI() 1
  29349. #endif
  29350. /*
  29351. ** Many system calls are accessed through pointer-to-functions so that
  29352. ** they may be overridden at runtime to facilitate fault injection during
  29353. ** testing and sandboxing. The following array holds the names and pointers
  29354. ** to all overrideable system calls.
  29355. */
  29356. static struct win_syscall {
  29357. const char *zName; /* Name of the system call */
  29358. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  29359. sqlite3_syscall_ptr pDefault; /* Default value */
  29360. } aSyscall[] = {
  29361. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  29362. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  29363. #else
  29364. { "AreFileApisANSI", (SYSCALL)0, 0 },
  29365. #endif
  29366. #ifndef osAreFileApisANSI
  29367. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  29368. #endif
  29369. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  29370. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  29371. #else
  29372. { "CharLowerW", (SYSCALL)0, 0 },
  29373. #endif
  29374. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  29375. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  29376. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  29377. #else
  29378. { "CharUpperW", (SYSCALL)0, 0 },
  29379. #endif
  29380. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  29381. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  29382. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  29383. #if defined(SQLITE_WIN32_HAS_ANSI)
  29384. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  29385. #else
  29386. { "CreateFileA", (SYSCALL)0, 0 },
  29387. #endif
  29388. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  29389. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  29390. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29391. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  29392. #else
  29393. { "CreateFileW", (SYSCALL)0, 0 },
  29394. #endif
  29395. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  29396. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  29397. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  29398. !defined(SQLITE_OMIT_WAL))
  29399. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  29400. #else
  29401. { "CreateFileMappingA", (SYSCALL)0, 0 },
  29402. #endif
  29403. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  29404. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  29405. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  29406. !defined(SQLITE_OMIT_WAL))
  29407. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  29408. #else
  29409. { "CreateFileMappingW", (SYSCALL)0, 0 },
  29410. #endif
  29411. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  29412. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  29413. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29414. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  29415. #else
  29416. { "CreateMutexW", (SYSCALL)0, 0 },
  29417. #endif
  29418. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  29419. LPCWSTR))aSyscall[8].pCurrent)
  29420. #if defined(SQLITE_WIN32_HAS_ANSI)
  29421. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  29422. #else
  29423. { "DeleteFileA", (SYSCALL)0, 0 },
  29424. #endif
  29425. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  29426. #if defined(SQLITE_WIN32_HAS_WIDE)
  29427. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  29428. #else
  29429. { "DeleteFileW", (SYSCALL)0, 0 },
  29430. #endif
  29431. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  29432. #if SQLITE_OS_WINCE
  29433. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  29434. #else
  29435. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  29436. #endif
  29437. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  29438. LPFILETIME))aSyscall[11].pCurrent)
  29439. #if SQLITE_OS_WINCE
  29440. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  29441. #else
  29442. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  29443. #endif
  29444. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  29445. LPSYSTEMTIME))aSyscall[12].pCurrent)
  29446. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  29447. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  29448. #if defined(SQLITE_WIN32_HAS_ANSI)
  29449. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  29450. #else
  29451. { "FormatMessageA", (SYSCALL)0, 0 },
  29452. #endif
  29453. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  29454. DWORD,va_list*))aSyscall[14].pCurrent)
  29455. #if defined(SQLITE_WIN32_HAS_WIDE)
  29456. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  29457. #else
  29458. { "FormatMessageW", (SYSCALL)0, 0 },
  29459. #endif
  29460. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  29461. DWORD,va_list*))aSyscall[15].pCurrent)
  29462. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29463. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  29464. #else
  29465. { "FreeLibrary", (SYSCALL)0, 0 },
  29466. #endif
  29467. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  29468. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  29469. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  29470. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  29471. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  29472. #else
  29473. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  29474. #endif
  29475. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  29476. LPDWORD))aSyscall[18].pCurrent)
  29477. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29478. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  29479. #else
  29480. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  29481. #endif
  29482. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  29483. LPDWORD))aSyscall[19].pCurrent)
  29484. #if defined(SQLITE_WIN32_HAS_ANSI)
  29485. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  29486. #else
  29487. { "GetFileAttributesA", (SYSCALL)0, 0 },
  29488. #endif
  29489. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  29490. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29491. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  29492. #else
  29493. { "GetFileAttributesW", (SYSCALL)0, 0 },
  29494. #endif
  29495. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  29496. #if defined(SQLITE_WIN32_HAS_WIDE)
  29497. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  29498. #else
  29499. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  29500. #endif
  29501. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  29502. LPVOID))aSyscall[22].pCurrent)
  29503. #if !SQLITE_OS_WINRT
  29504. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  29505. #else
  29506. { "GetFileSize", (SYSCALL)0, 0 },
  29507. #endif
  29508. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  29509. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  29510. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  29511. #else
  29512. { "GetFullPathNameA", (SYSCALL)0, 0 },
  29513. #endif
  29514. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  29515. LPSTR*))aSyscall[24].pCurrent)
  29516. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29517. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  29518. #else
  29519. { "GetFullPathNameW", (SYSCALL)0, 0 },
  29520. #endif
  29521. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  29522. LPWSTR*))aSyscall[25].pCurrent)
  29523. { "GetLastError", (SYSCALL)GetLastError, 0 },
  29524. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  29525. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29526. #if SQLITE_OS_WINCE
  29527. /* The GetProcAddressA() routine is only available on Windows CE. */
  29528. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  29529. #else
  29530. /* All other Windows platforms expect GetProcAddress() to take
  29531. ** an ANSI string regardless of the _UNICODE setting */
  29532. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  29533. #endif
  29534. #else
  29535. { "GetProcAddressA", (SYSCALL)0, 0 },
  29536. #endif
  29537. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  29538. LPCSTR))aSyscall[27].pCurrent)
  29539. #if !SQLITE_OS_WINRT
  29540. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  29541. #else
  29542. { "GetSystemInfo", (SYSCALL)0, 0 },
  29543. #endif
  29544. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  29545. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  29546. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  29547. #if !SQLITE_OS_WINCE
  29548. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  29549. #else
  29550. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  29551. #endif
  29552. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  29553. LPFILETIME))aSyscall[30].pCurrent)
  29554. #if defined(SQLITE_WIN32_HAS_ANSI)
  29555. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  29556. #else
  29557. { "GetTempPathA", (SYSCALL)0, 0 },
  29558. #endif
  29559. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  29560. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29561. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  29562. #else
  29563. { "GetTempPathW", (SYSCALL)0, 0 },
  29564. #endif
  29565. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  29566. #if !SQLITE_OS_WINRT
  29567. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  29568. #else
  29569. { "GetTickCount", (SYSCALL)0, 0 },
  29570. #endif
  29571. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  29572. #if defined(SQLITE_WIN32_HAS_ANSI)
  29573. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  29574. #else
  29575. { "GetVersionExA", (SYSCALL)0, 0 },
  29576. #endif
  29577. #define osGetVersionExA ((BOOL(WINAPI*)( \
  29578. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  29579. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29580. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  29581. #else
  29582. { "GetVersionExW", (SYSCALL)0, 0 },
  29583. #endif
  29584. #define osGetVersionExW ((BOOL(WINAPI*)( \
  29585. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  29586. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  29587. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  29588. SIZE_T))aSyscall[36].pCurrent)
  29589. #if !SQLITE_OS_WINRT
  29590. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  29591. #else
  29592. { "HeapCreate", (SYSCALL)0, 0 },
  29593. #endif
  29594. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  29595. SIZE_T))aSyscall[37].pCurrent)
  29596. #if !SQLITE_OS_WINRT
  29597. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  29598. #else
  29599. { "HeapDestroy", (SYSCALL)0, 0 },
  29600. #endif
  29601. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  29602. { "HeapFree", (SYSCALL)HeapFree, 0 },
  29603. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  29604. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  29605. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  29606. SIZE_T))aSyscall[40].pCurrent)
  29607. { "HeapSize", (SYSCALL)HeapSize, 0 },
  29608. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  29609. LPCVOID))aSyscall[41].pCurrent)
  29610. #if !SQLITE_OS_WINRT
  29611. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  29612. #else
  29613. { "HeapValidate", (SYSCALL)0, 0 },
  29614. #endif
  29615. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  29616. LPCVOID))aSyscall[42].pCurrent)
  29617. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29618. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  29619. #else
  29620. { "LoadLibraryA", (SYSCALL)0, 0 },
  29621. #endif
  29622. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[43].pCurrent)
  29623. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  29624. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29625. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  29626. #else
  29627. { "LoadLibraryW", (SYSCALL)0, 0 },
  29628. #endif
  29629. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[44].pCurrent)
  29630. #if !SQLITE_OS_WINRT
  29631. { "LocalFree", (SYSCALL)LocalFree, 0 },
  29632. #else
  29633. { "LocalFree", (SYSCALL)0, 0 },
  29634. #endif
  29635. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[45].pCurrent)
  29636. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  29637. { "LockFile", (SYSCALL)LockFile, 0 },
  29638. #else
  29639. { "LockFile", (SYSCALL)0, 0 },
  29640. #endif
  29641. #ifndef osLockFile
  29642. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  29643. DWORD))aSyscall[46].pCurrent)
  29644. #endif
  29645. #if !SQLITE_OS_WINCE
  29646. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  29647. #else
  29648. { "LockFileEx", (SYSCALL)0, 0 },
  29649. #endif
  29650. #ifndef osLockFileEx
  29651. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  29652. LPOVERLAPPED))aSyscall[47].pCurrent)
  29653. #endif
  29654. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
  29655. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  29656. #else
  29657. { "MapViewOfFile", (SYSCALL)0, 0 },
  29658. #endif
  29659. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  29660. SIZE_T))aSyscall[48].pCurrent)
  29661. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  29662. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  29663. int))aSyscall[49].pCurrent)
  29664. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  29665. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  29666. LARGE_INTEGER*))aSyscall[50].pCurrent)
  29667. { "ReadFile", (SYSCALL)ReadFile, 0 },
  29668. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  29669. LPOVERLAPPED))aSyscall[51].pCurrent)
  29670. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  29671. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[52].pCurrent)
  29672. #if !SQLITE_OS_WINRT
  29673. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  29674. #else
  29675. { "SetFilePointer", (SYSCALL)0, 0 },
  29676. #endif
  29677. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  29678. DWORD))aSyscall[53].pCurrent)
  29679. #if !SQLITE_OS_WINRT
  29680. { "Sleep", (SYSCALL)Sleep, 0 },
  29681. #else
  29682. { "Sleep", (SYSCALL)0, 0 },
  29683. #endif
  29684. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[54].pCurrent)
  29685. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  29686. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  29687. LPFILETIME))aSyscall[55].pCurrent)
  29688. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  29689. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  29690. #else
  29691. { "UnlockFile", (SYSCALL)0, 0 },
  29692. #endif
  29693. #ifndef osUnlockFile
  29694. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  29695. DWORD))aSyscall[56].pCurrent)
  29696. #endif
  29697. #if !SQLITE_OS_WINCE
  29698. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  29699. #else
  29700. { "UnlockFileEx", (SYSCALL)0, 0 },
  29701. #endif
  29702. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  29703. LPOVERLAPPED))aSyscall[57].pCurrent)
  29704. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
  29705. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  29706. #else
  29707. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  29708. #endif
  29709. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[58].pCurrent)
  29710. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  29711. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  29712. LPCSTR,LPBOOL))aSyscall[59].pCurrent)
  29713. { "WriteFile", (SYSCALL)WriteFile, 0 },
  29714. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  29715. LPOVERLAPPED))aSyscall[60].pCurrent)
  29716. #if SQLITE_OS_WINRT
  29717. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  29718. #else
  29719. { "CreateEventExW", (SYSCALL)0, 0 },
  29720. #endif
  29721. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  29722. DWORD,DWORD))aSyscall[61].pCurrent)
  29723. #if !SQLITE_OS_WINRT
  29724. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  29725. #else
  29726. { "WaitForSingleObject", (SYSCALL)0, 0 },
  29727. #endif
  29728. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  29729. DWORD))aSyscall[62].pCurrent)
  29730. #if SQLITE_OS_WINRT
  29731. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  29732. #else
  29733. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  29734. #endif
  29735. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  29736. BOOL))aSyscall[63].pCurrent)
  29737. #if SQLITE_OS_WINRT
  29738. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  29739. #else
  29740. { "SetFilePointerEx", (SYSCALL)0, 0 },
  29741. #endif
  29742. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  29743. PLARGE_INTEGER,DWORD))aSyscall[64].pCurrent)
  29744. #if SQLITE_OS_WINRT
  29745. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  29746. #else
  29747. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  29748. #endif
  29749. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  29750. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[65].pCurrent)
  29751. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  29752. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  29753. #else
  29754. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  29755. #endif
  29756. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  29757. SIZE_T))aSyscall[66].pCurrent)
  29758. #if SQLITE_OS_WINRT
  29759. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  29760. #else
  29761. { "CreateFile2", (SYSCALL)0, 0 },
  29762. #endif
  29763. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  29764. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[67].pCurrent)
  29765. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29766. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  29767. #else
  29768. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  29769. #endif
  29770. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  29771. DWORD))aSyscall[68].pCurrent)
  29772. #if SQLITE_OS_WINRT
  29773. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  29774. #else
  29775. { "GetTickCount64", (SYSCALL)0, 0 },
  29776. #endif
  29777. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[69].pCurrent)
  29778. #if SQLITE_OS_WINRT
  29779. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  29780. #else
  29781. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  29782. #endif
  29783. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  29784. LPSYSTEM_INFO))aSyscall[70].pCurrent)
  29785. #if defined(SQLITE_WIN32_HAS_ANSI)
  29786. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  29787. #else
  29788. { "OutputDebugStringA", (SYSCALL)0, 0 },
  29789. #endif
  29790. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[71].pCurrent)
  29791. #if defined(SQLITE_WIN32_HAS_WIDE)
  29792. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  29793. #else
  29794. { "OutputDebugStringW", (SYSCALL)0, 0 },
  29795. #endif
  29796. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[72].pCurrent)
  29797. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  29798. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[73].pCurrent)
  29799. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  29800. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  29801. #else
  29802. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  29803. #endif
  29804. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  29805. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[74].pCurrent)
  29806. }; /* End of the overrideable system calls */
  29807. /*
  29808. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  29809. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  29810. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  29811. ** system call named zName.
  29812. */
  29813. static int winSetSystemCall(
  29814. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  29815. const char *zName, /* Name of system call to override */
  29816. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  29817. ){
  29818. unsigned int i;
  29819. int rc = SQLITE_NOTFOUND;
  29820. UNUSED_PARAMETER(pNotUsed);
  29821. if( zName==0 ){
  29822. /* If no zName is given, restore all system calls to their default
  29823. ** settings and return NULL
  29824. */
  29825. rc = SQLITE_OK;
  29826. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29827. if( aSyscall[i].pDefault ){
  29828. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  29829. }
  29830. }
  29831. }else{
  29832. /* If zName is specified, operate on only the one system call
  29833. ** specified.
  29834. */
  29835. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29836. if( strcmp(zName, aSyscall[i].zName)==0 ){
  29837. if( aSyscall[i].pDefault==0 ){
  29838. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  29839. }
  29840. rc = SQLITE_OK;
  29841. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  29842. aSyscall[i].pCurrent = pNewFunc;
  29843. break;
  29844. }
  29845. }
  29846. }
  29847. return rc;
  29848. }
  29849. /*
  29850. ** Return the value of a system call. Return NULL if zName is not a
  29851. ** recognized system call name. NULL is also returned if the system call
  29852. ** is currently undefined.
  29853. */
  29854. static sqlite3_syscall_ptr winGetSystemCall(
  29855. sqlite3_vfs *pNotUsed,
  29856. const char *zName
  29857. ){
  29858. unsigned int i;
  29859. UNUSED_PARAMETER(pNotUsed);
  29860. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29861. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  29862. }
  29863. return 0;
  29864. }
  29865. /*
  29866. ** Return the name of the first system call after zName. If zName==NULL
  29867. ** then return the name of the first system call. Return NULL if zName
  29868. ** is the last system call or if zName is not the name of a valid
  29869. ** system call.
  29870. */
  29871. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  29872. int i = -1;
  29873. UNUSED_PARAMETER(p);
  29874. if( zName ){
  29875. for(i=0; i<ArraySize(aSyscall)-1; i++){
  29876. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  29877. }
  29878. }
  29879. for(i++; i<ArraySize(aSyscall); i++){
  29880. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  29881. }
  29882. return 0;
  29883. }
  29884. /*
  29885. ** This function outputs the specified (ANSI) string to the Win32 debugger
  29886. ** (if available).
  29887. */
  29888. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  29889. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  29890. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  29891. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  29892. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  29893. #if defined(SQLITE_WIN32_HAS_ANSI)
  29894. if( nMin>0 ){
  29895. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  29896. memcpy(zDbgBuf, zBuf, nMin);
  29897. osOutputDebugStringA(zDbgBuf);
  29898. }else{
  29899. osOutputDebugStringA(zBuf);
  29900. }
  29901. #elif defined(SQLITE_WIN32_HAS_WIDE)
  29902. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  29903. if ( osMultiByteToWideChar(
  29904. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  29905. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  29906. return;
  29907. }
  29908. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  29909. #else
  29910. if( nMin>0 ){
  29911. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  29912. memcpy(zDbgBuf, zBuf, nMin);
  29913. fprintf(stderr, "%s", zDbgBuf);
  29914. }else{
  29915. fprintf(stderr, "%s", zBuf);
  29916. }
  29917. #endif
  29918. }
  29919. /*
  29920. ** The following routine suspends the current thread for at least ms
  29921. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  29922. */
  29923. #if SQLITE_OS_WINRT
  29924. static HANDLE sleepObj = NULL;
  29925. #endif
  29926. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  29927. #if SQLITE_OS_WINRT
  29928. if ( sleepObj==NULL ){
  29929. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  29930. SYNCHRONIZE);
  29931. }
  29932. assert( sleepObj!=NULL );
  29933. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  29934. #else
  29935. osSleep(milliseconds);
  29936. #endif
  29937. }
  29938. /*
  29939. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  29940. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  29941. **
  29942. ** Here is an interesting observation: Win95, Win98, and WinME lack
  29943. ** the LockFileEx() API. But we can still statically link against that
  29944. ** API as long as we don't call it when running Win95/98/ME. A call to
  29945. ** this routine is used to determine if the host is Win95/98/ME or
  29946. ** WinNT/2K/XP so that we will know whether or not we can safely call
  29947. ** the LockFileEx() API.
  29948. */
  29949. #ifndef NTDDI_WIN8
  29950. # define NTDDI_WIN8 0x06020000
  29951. #endif
  29952. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  29953. # define osIsNT() (1)
  29954. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  29955. # define osIsNT() (0)
  29956. #else
  29957. static int osIsNT(void){
  29958. if( sqlite3_os_type==0 ){
  29959. #if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
  29960. OSVERSIONINFOW sInfo;
  29961. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  29962. osGetVersionExW(&sInfo);
  29963. #else
  29964. OSVERSIONINFOA sInfo;
  29965. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  29966. osGetVersionExA(&sInfo);
  29967. #endif
  29968. sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  29969. }
  29970. return sqlite3_os_type==2;
  29971. }
  29972. #endif
  29973. #ifdef SQLITE_WIN32_MALLOC
  29974. /*
  29975. ** Allocate nBytes of memory.
  29976. */
  29977. static void *winMemMalloc(int nBytes){
  29978. HANDLE hHeap;
  29979. void *p;
  29980. winMemAssertMagic();
  29981. hHeap = winMemGetHeap();
  29982. assert( hHeap!=0 );
  29983. assert( hHeap!=INVALID_HANDLE_VALUE );
  29984. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29985. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  29986. #endif
  29987. assert( nBytes>=0 );
  29988. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  29989. if( !p ){
  29990. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  29991. nBytes, osGetLastError(), (void*)hHeap);
  29992. }
  29993. return p;
  29994. }
  29995. /*
  29996. ** Free memory.
  29997. */
  29998. static void winMemFree(void *pPrior){
  29999. HANDLE hHeap;
  30000. winMemAssertMagic();
  30001. hHeap = winMemGetHeap();
  30002. assert( hHeap!=0 );
  30003. assert( hHeap!=INVALID_HANDLE_VALUE );
  30004. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30005. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  30006. #endif
  30007. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  30008. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  30009. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  30010. pPrior, osGetLastError(), (void*)hHeap);
  30011. }
  30012. }
  30013. /*
  30014. ** Change the size of an existing memory allocation
  30015. */
  30016. static void *winMemRealloc(void *pPrior, int nBytes){
  30017. HANDLE hHeap;
  30018. void *p;
  30019. winMemAssertMagic();
  30020. hHeap = winMemGetHeap();
  30021. assert( hHeap!=0 );
  30022. assert( hHeap!=INVALID_HANDLE_VALUE );
  30023. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30024. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  30025. #endif
  30026. assert( nBytes>=0 );
  30027. if( !pPrior ){
  30028. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  30029. }else{
  30030. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  30031. }
  30032. if( !p ){
  30033. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  30034. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  30035. (void*)hHeap);
  30036. }
  30037. return p;
  30038. }
  30039. /*
  30040. ** Return the size of an outstanding allocation, in bytes.
  30041. */
  30042. static int winMemSize(void *p){
  30043. HANDLE hHeap;
  30044. SIZE_T n;
  30045. winMemAssertMagic();
  30046. hHeap = winMemGetHeap();
  30047. assert( hHeap!=0 );
  30048. assert( hHeap!=INVALID_HANDLE_VALUE );
  30049. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30050. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  30051. #endif
  30052. if( !p ) return 0;
  30053. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  30054. if( n==(SIZE_T)-1 ){
  30055. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  30056. p, osGetLastError(), (void*)hHeap);
  30057. return 0;
  30058. }
  30059. return (int)n;
  30060. }
  30061. /*
  30062. ** Round up a request size to the next valid allocation size.
  30063. */
  30064. static int winMemRoundup(int n){
  30065. return n;
  30066. }
  30067. /*
  30068. ** Initialize this module.
  30069. */
  30070. static int winMemInit(void *pAppData){
  30071. winMemData *pWinMemData = (winMemData *)pAppData;
  30072. if( !pWinMemData ) return SQLITE_ERROR;
  30073. assert( pWinMemData->magic==WINMEM_MAGIC );
  30074. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  30075. if( !pWinMemData->hHeap ){
  30076. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  30077. SQLITE_WIN32_HEAP_INIT_SIZE,
  30078. SQLITE_WIN32_HEAP_MAX_SIZE);
  30079. if( !pWinMemData->hHeap ){
  30080. sqlite3_log(SQLITE_NOMEM,
  30081. "failed to HeapCreate (%lu), flags=%u, initSize=%u, maxSize=%u",
  30082. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
  30083. SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
  30084. return SQLITE_NOMEM;
  30085. }
  30086. pWinMemData->bOwned = TRUE;
  30087. assert( pWinMemData->bOwned );
  30088. }
  30089. #else
  30090. pWinMemData->hHeap = osGetProcessHeap();
  30091. if( !pWinMemData->hHeap ){
  30092. sqlite3_log(SQLITE_NOMEM,
  30093. "failed to GetProcessHeap (%lu)", osGetLastError());
  30094. return SQLITE_NOMEM;
  30095. }
  30096. pWinMemData->bOwned = FALSE;
  30097. assert( !pWinMemData->bOwned );
  30098. #endif
  30099. assert( pWinMemData->hHeap!=0 );
  30100. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  30101. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30102. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  30103. #endif
  30104. return SQLITE_OK;
  30105. }
  30106. /*
  30107. ** Deinitialize this module.
  30108. */
  30109. static void winMemShutdown(void *pAppData){
  30110. winMemData *pWinMemData = (winMemData *)pAppData;
  30111. if( !pWinMemData ) return;
  30112. if( pWinMemData->hHeap ){
  30113. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  30114. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30115. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  30116. #endif
  30117. if( pWinMemData->bOwned ){
  30118. if( !osHeapDestroy(pWinMemData->hHeap) ){
  30119. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  30120. osGetLastError(), (void*)pWinMemData->hHeap);
  30121. }
  30122. pWinMemData->bOwned = FALSE;
  30123. }
  30124. pWinMemData->hHeap = NULL;
  30125. }
  30126. }
  30127. /*
  30128. ** Populate the low-level memory allocation function pointers in
  30129. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  30130. ** arguments specify the block of memory to manage.
  30131. **
  30132. ** This routine is only called by sqlite3_config(), and therefore
  30133. ** is not required to be threadsafe (it is not).
  30134. */
  30135. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  30136. static const sqlite3_mem_methods winMemMethods = {
  30137. winMemMalloc,
  30138. winMemFree,
  30139. winMemRealloc,
  30140. winMemSize,
  30141. winMemRoundup,
  30142. winMemInit,
  30143. winMemShutdown,
  30144. &win_mem_data
  30145. };
  30146. return &winMemMethods;
  30147. }
  30148. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  30149. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  30150. }
  30151. #endif /* SQLITE_WIN32_MALLOC */
  30152. /*
  30153. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  30154. **
  30155. ** Space to hold the returned string is obtained from malloc.
  30156. */
  30157. static LPWSTR winUtf8ToUnicode(const char *zFilename){
  30158. int nChar;
  30159. LPWSTR zWideFilename;
  30160. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  30161. if( nChar==0 ){
  30162. return 0;
  30163. }
  30164. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  30165. if( zWideFilename==0 ){
  30166. return 0;
  30167. }
  30168. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  30169. nChar);
  30170. if( nChar==0 ){
  30171. sqlite3_free(zWideFilename);
  30172. zWideFilename = 0;
  30173. }
  30174. return zWideFilename;
  30175. }
  30176. /*
  30177. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  30178. ** obtained from sqlite3_malloc().
  30179. */
  30180. static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
  30181. int nByte;
  30182. char *zFilename;
  30183. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  30184. if( nByte == 0 ){
  30185. return 0;
  30186. }
  30187. zFilename = sqlite3MallocZero( nByte );
  30188. if( zFilename==0 ){
  30189. return 0;
  30190. }
  30191. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  30192. 0, 0);
  30193. if( nByte == 0 ){
  30194. sqlite3_free(zFilename);
  30195. zFilename = 0;
  30196. }
  30197. return zFilename;
  30198. }
  30199. /*
  30200. ** Convert an ANSI string to Microsoft Unicode, based on the
  30201. ** current codepage settings for file apis.
  30202. **
  30203. ** Space to hold the returned string is obtained
  30204. ** from sqlite3_malloc.
  30205. */
  30206. static LPWSTR winMbcsToUnicode(const char *zFilename){
  30207. int nByte;
  30208. LPWSTR zMbcsFilename;
  30209. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  30210. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  30211. 0)*sizeof(WCHAR);
  30212. if( nByte==0 ){
  30213. return 0;
  30214. }
  30215. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  30216. if( zMbcsFilename==0 ){
  30217. return 0;
  30218. }
  30219. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  30220. nByte);
  30221. if( nByte==0 ){
  30222. sqlite3_free(zMbcsFilename);
  30223. zMbcsFilename = 0;
  30224. }
  30225. return zMbcsFilename;
  30226. }
  30227. /*
  30228. ** Convert Microsoft Unicode to multi-byte character string, based on the
  30229. ** user's ANSI codepage.
  30230. **
  30231. ** Space to hold the returned string is obtained from
  30232. ** sqlite3_malloc().
  30233. */
  30234. static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
  30235. int nByte;
  30236. char *zFilename;
  30237. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  30238. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  30239. if( nByte == 0 ){
  30240. return 0;
  30241. }
  30242. zFilename = sqlite3MallocZero( nByte );
  30243. if( zFilename==0 ){
  30244. return 0;
  30245. }
  30246. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  30247. nByte, 0, 0);
  30248. if( nByte == 0 ){
  30249. sqlite3_free(zFilename);
  30250. zFilename = 0;
  30251. }
  30252. return zFilename;
  30253. }
  30254. /*
  30255. ** Convert multibyte character string to UTF-8. Space to hold the
  30256. ** returned string is obtained from sqlite3_malloc().
  30257. */
  30258. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  30259. char *zFilenameUtf8;
  30260. LPWSTR zTmpWide;
  30261. zTmpWide = winMbcsToUnicode(zFilename);
  30262. if( zTmpWide==0 ){
  30263. return 0;
  30264. }
  30265. zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  30266. sqlite3_free(zTmpWide);
  30267. return zFilenameUtf8;
  30268. }
  30269. /*
  30270. ** Convert UTF-8 to multibyte character string. Space to hold the
  30271. ** returned string is obtained from sqlite3_malloc().
  30272. */
  30273. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  30274. char *zFilenameMbcs;
  30275. LPWSTR zTmpWide;
  30276. zTmpWide = winUtf8ToUnicode(zFilename);
  30277. if( zTmpWide==0 ){
  30278. return 0;
  30279. }
  30280. zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
  30281. sqlite3_free(zTmpWide);
  30282. return zFilenameMbcs;
  30283. }
  30284. /*
  30285. ** This function sets the data directory or the temporary directory based on
  30286. ** the provided arguments. The type argument must be 1 in order to set the
  30287. ** data directory or 2 in order to set the temporary directory. The zValue
  30288. ** argument is the name of the directory to use. The return value will be
  30289. ** SQLITE_OK if successful.
  30290. */
  30291. SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  30292. char **ppDirectory = 0;
  30293. #ifndef SQLITE_OMIT_AUTOINIT
  30294. int rc = sqlite3_initialize();
  30295. if( rc ) return rc;
  30296. #endif
  30297. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  30298. ppDirectory = &sqlite3_data_directory;
  30299. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  30300. ppDirectory = &sqlite3_temp_directory;
  30301. }
  30302. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  30303. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  30304. );
  30305. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  30306. if( ppDirectory ){
  30307. char *zValueUtf8 = 0;
  30308. if( zValue && zValue[0] ){
  30309. zValueUtf8 = winUnicodeToUtf8(zValue);
  30310. if ( zValueUtf8==0 ){
  30311. return SQLITE_NOMEM;
  30312. }
  30313. }
  30314. sqlite3_free(*ppDirectory);
  30315. *ppDirectory = zValueUtf8;
  30316. return SQLITE_OK;
  30317. }
  30318. return SQLITE_ERROR;
  30319. }
  30320. /*
  30321. ** The return value of winGetLastErrorMsg
  30322. ** is zero if the error message fits in the buffer, or non-zero
  30323. ** otherwise (if the message was truncated).
  30324. */
  30325. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  30326. /* FormatMessage returns 0 on failure. Otherwise it
  30327. ** returns the number of TCHARs written to the output
  30328. ** buffer, excluding the terminating null char.
  30329. */
  30330. DWORD dwLen = 0;
  30331. char *zOut = 0;
  30332. if( osIsNT() ){
  30333. #if SQLITE_OS_WINRT
  30334. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  30335. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  30336. FORMAT_MESSAGE_IGNORE_INSERTS,
  30337. NULL,
  30338. lastErrno,
  30339. 0,
  30340. zTempWide,
  30341. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  30342. 0);
  30343. #else
  30344. LPWSTR zTempWide = NULL;
  30345. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  30346. FORMAT_MESSAGE_FROM_SYSTEM |
  30347. FORMAT_MESSAGE_IGNORE_INSERTS,
  30348. NULL,
  30349. lastErrno,
  30350. 0,
  30351. (LPWSTR) &zTempWide,
  30352. 0,
  30353. 0);
  30354. #endif
  30355. if( dwLen > 0 ){
  30356. /* allocate a buffer and convert to UTF8 */
  30357. sqlite3BeginBenignMalloc();
  30358. zOut = winUnicodeToUtf8(zTempWide);
  30359. sqlite3EndBenignMalloc();
  30360. #if !SQLITE_OS_WINRT
  30361. /* free the system buffer allocated by FormatMessage */
  30362. osLocalFree(zTempWide);
  30363. #endif
  30364. }
  30365. }
  30366. #ifdef SQLITE_WIN32_HAS_ANSI
  30367. else{
  30368. char *zTemp = NULL;
  30369. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  30370. FORMAT_MESSAGE_FROM_SYSTEM |
  30371. FORMAT_MESSAGE_IGNORE_INSERTS,
  30372. NULL,
  30373. lastErrno,
  30374. 0,
  30375. (LPSTR) &zTemp,
  30376. 0,
  30377. 0);
  30378. if( dwLen > 0 ){
  30379. /* allocate a buffer and convert to UTF8 */
  30380. sqlite3BeginBenignMalloc();
  30381. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  30382. sqlite3EndBenignMalloc();
  30383. /* free the system buffer allocated by FormatMessage */
  30384. osLocalFree(zTemp);
  30385. }
  30386. }
  30387. #endif
  30388. if( 0 == dwLen ){
  30389. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  30390. }else{
  30391. /* copy a maximum of nBuf chars to output buffer */
  30392. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  30393. /* free the UTF8 buffer */
  30394. sqlite3_free(zOut);
  30395. }
  30396. return 0;
  30397. }
  30398. /*
  30399. **
  30400. ** This function - winLogErrorAtLine() - is only ever called via the macro
  30401. ** winLogError().
  30402. **
  30403. ** This routine is invoked after an error occurs in an OS function.
  30404. ** It logs a message using sqlite3_log() containing the current value of
  30405. ** error code and, if possible, the human-readable equivalent from
  30406. ** FormatMessage.
  30407. **
  30408. ** The first argument passed to the macro should be the error code that
  30409. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  30410. ** The two subsequent arguments should be the name of the OS function that
  30411. ** failed and the associated file-system path, if any.
  30412. */
  30413. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  30414. static int winLogErrorAtLine(
  30415. int errcode, /* SQLite error code */
  30416. DWORD lastErrno, /* Win32 last error */
  30417. const char *zFunc, /* Name of OS function that failed */
  30418. const char *zPath, /* File path associated with error */
  30419. int iLine /* Source line number where error occurred */
  30420. ){
  30421. char zMsg[500]; /* Human readable error text */
  30422. int i; /* Loop counter */
  30423. zMsg[0] = 0;
  30424. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  30425. assert( errcode!=SQLITE_OK );
  30426. if( zPath==0 ) zPath = "";
  30427. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  30428. zMsg[i] = 0;
  30429. sqlite3_log(errcode,
  30430. "os_win.c:%d: (%lu) %s(%s) - %s",
  30431. iLine, lastErrno, zFunc, zPath, zMsg
  30432. );
  30433. return errcode;
  30434. }
  30435. /*
  30436. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  30437. ** will be retried following a locking error - probably caused by
  30438. ** antivirus software. Also the initial delay before the first retry.
  30439. ** The delay increases linearly with each retry.
  30440. */
  30441. #ifndef SQLITE_WIN32_IOERR_RETRY
  30442. # define SQLITE_WIN32_IOERR_RETRY 10
  30443. #endif
  30444. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  30445. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  30446. #endif
  30447. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  30448. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  30449. /*
  30450. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  30451. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  30452. ** to give up with an error.
  30453. */
  30454. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  30455. DWORD e = osGetLastError();
  30456. if( *pnRetry>=winIoerrRetry ){
  30457. if( pError ){
  30458. *pError = e;
  30459. }
  30460. return 0;
  30461. }
  30462. if( e==ERROR_ACCESS_DENIED ||
  30463. e==ERROR_LOCK_VIOLATION ||
  30464. e==ERROR_SHARING_VIOLATION ){
  30465. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  30466. ++*pnRetry;
  30467. return 1;
  30468. }
  30469. if( pError ){
  30470. *pError = e;
  30471. }
  30472. return 0;
  30473. }
  30474. /*
  30475. ** Log a I/O error retry episode.
  30476. */
  30477. static void winLogIoerr(int nRetry){
  30478. if( nRetry ){
  30479. sqlite3_log(SQLITE_IOERR,
  30480. "delayed %dms for lock/sharing conflict",
  30481. winIoerrRetryDelay*nRetry*(nRetry+1)/2
  30482. );
  30483. }
  30484. }
  30485. #if SQLITE_OS_WINCE
  30486. /*************************************************************************
  30487. ** This section contains code for WinCE only.
  30488. */
  30489. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  30490. /*
  30491. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  30492. ** create a substitute.
  30493. */
  30494. /* #include <time.h> */
  30495. struct tm *__cdecl localtime(const time_t *t)
  30496. {
  30497. static struct tm y;
  30498. FILETIME uTm, lTm;
  30499. SYSTEMTIME pTm;
  30500. sqlite3_int64 t64;
  30501. t64 = *t;
  30502. t64 = (t64 + 11644473600)*10000000;
  30503. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  30504. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  30505. osFileTimeToLocalFileTime(&uTm,&lTm);
  30506. osFileTimeToSystemTime(&lTm,&pTm);
  30507. y.tm_year = pTm.wYear - 1900;
  30508. y.tm_mon = pTm.wMonth - 1;
  30509. y.tm_wday = pTm.wDayOfWeek;
  30510. y.tm_mday = pTm.wDay;
  30511. y.tm_hour = pTm.wHour;
  30512. y.tm_min = pTm.wMinute;
  30513. y.tm_sec = pTm.wSecond;
  30514. return &y;
  30515. }
  30516. #endif
  30517. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  30518. /*
  30519. ** Acquire a lock on the handle h
  30520. */
  30521. static void winceMutexAcquire(HANDLE h){
  30522. DWORD dwErr;
  30523. do {
  30524. dwErr = osWaitForSingleObject(h, INFINITE);
  30525. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  30526. }
  30527. /*
  30528. ** Release a lock acquired by winceMutexAcquire()
  30529. */
  30530. #define winceMutexRelease(h) ReleaseMutex(h)
  30531. /*
  30532. ** Create the mutex and shared memory used for locking in the file
  30533. ** descriptor pFile
  30534. */
  30535. static int winceCreateLock(const char *zFilename, winFile *pFile){
  30536. LPWSTR zTok;
  30537. LPWSTR zName;
  30538. DWORD lastErrno;
  30539. BOOL bLogged = FALSE;
  30540. BOOL bInit = TRUE;
  30541. zName = winUtf8ToUnicode(zFilename);
  30542. if( zName==0 ){
  30543. /* out of memory */
  30544. return SQLITE_IOERR_NOMEM;
  30545. }
  30546. /* Initialize the local lockdata */
  30547. memset(&pFile->local, 0, sizeof(pFile->local));
  30548. /* Replace the backslashes from the filename and lowercase it
  30549. ** to derive a mutex name. */
  30550. zTok = osCharLowerW(zName);
  30551. for (;*zTok;zTok++){
  30552. if (*zTok == '\\') *zTok = '_';
  30553. }
  30554. /* Create/open the named mutex */
  30555. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  30556. if (!pFile->hMutex){
  30557. pFile->lastErrno = osGetLastError();
  30558. sqlite3_free(zName);
  30559. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  30560. "winceCreateLock1", zFilename);
  30561. }
  30562. /* Acquire the mutex before continuing */
  30563. winceMutexAcquire(pFile->hMutex);
  30564. /* Since the names of named mutexes, semaphores, file mappings etc are
  30565. ** case-sensitive, take advantage of that by uppercasing the mutex name
  30566. ** and using that as the shared filemapping name.
  30567. */
  30568. osCharUpperW(zName);
  30569. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  30570. PAGE_READWRITE, 0, sizeof(winceLock),
  30571. zName);
  30572. /* Set a flag that indicates we're the first to create the memory so it
  30573. ** must be zero-initialized */
  30574. lastErrno = osGetLastError();
  30575. if (lastErrno == ERROR_ALREADY_EXISTS){
  30576. bInit = FALSE;
  30577. }
  30578. sqlite3_free(zName);
  30579. /* If we succeeded in making the shared memory handle, map it. */
  30580. if( pFile->hShared ){
  30581. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  30582. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  30583. /* If mapping failed, close the shared memory handle and erase it */
  30584. if( !pFile->shared ){
  30585. pFile->lastErrno = osGetLastError();
  30586. winLogError(SQLITE_IOERR, pFile->lastErrno,
  30587. "winceCreateLock2", zFilename);
  30588. bLogged = TRUE;
  30589. osCloseHandle(pFile->hShared);
  30590. pFile->hShared = NULL;
  30591. }
  30592. }
  30593. /* If shared memory could not be created, then close the mutex and fail */
  30594. if( pFile->hShared==NULL ){
  30595. if( !bLogged ){
  30596. pFile->lastErrno = lastErrno;
  30597. winLogError(SQLITE_IOERR, pFile->lastErrno,
  30598. "winceCreateLock3", zFilename);
  30599. bLogged = TRUE;
  30600. }
  30601. winceMutexRelease(pFile->hMutex);
  30602. osCloseHandle(pFile->hMutex);
  30603. pFile->hMutex = NULL;
  30604. return SQLITE_IOERR;
  30605. }
  30606. /* Initialize the shared memory if we're supposed to */
  30607. if( bInit ){
  30608. memset(pFile->shared, 0, sizeof(winceLock));
  30609. }
  30610. winceMutexRelease(pFile->hMutex);
  30611. return SQLITE_OK;
  30612. }
  30613. /*
  30614. ** Destroy the part of winFile that deals with wince locks
  30615. */
  30616. static void winceDestroyLock(winFile *pFile){
  30617. if (pFile->hMutex){
  30618. /* Acquire the mutex */
  30619. winceMutexAcquire(pFile->hMutex);
  30620. /* The following blocks should probably assert in debug mode, but they
  30621. are to cleanup in case any locks remained open */
  30622. if (pFile->local.nReaders){
  30623. pFile->shared->nReaders --;
  30624. }
  30625. if (pFile->local.bReserved){
  30626. pFile->shared->bReserved = FALSE;
  30627. }
  30628. if (pFile->local.bPending){
  30629. pFile->shared->bPending = FALSE;
  30630. }
  30631. if (pFile->local.bExclusive){
  30632. pFile->shared->bExclusive = FALSE;
  30633. }
  30634. /* De-reference and close our copy of the shared memory handle */
  30635. osUnmapViewOfFile(pFile->shared);
  30636. osCloseHandle(pFile->hShared);
  30637. /* Done with the mutex */
  30638. winceMutexRelease(pFile->hMutex);
  30639. osCloseHandle(pFile->hMutex);
  30640. pFile->hMutex = NULL;
  30641. }
  30642. }
  30643. /*
  30644. ** An implementation of the LockFile() API of Windows for CE
  30645. */
  30646. static BOOL winceLockFile(
  30647. LPHANDLE phFile,
  30648. DWORD dwFileOffsetLow,
  30649. DWORD dwFileOffsetHigh,
  30650. DWORD nNumberOfBytesToLockLow,
  30651. DWORD nNumberOfBytesToLockHigh
  30652. ){
  30653. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  30654. BOOL bReturn = FALSE;
  30655. UNUSED_PARAMETER(dwFileOffsetHigh);
  30656. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  30657. if (!pFile->hMutex) return TRUE;
  30658. winceMutexAcquire(pFile->hMutex);
  30659. /* Wanting an exclusive lock? */
  30660. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  30661. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  30662. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  30663. pFile->shared->bExclusive = TRUE;
  30664. pFile->local.bExclusive = TRUE;
  30665. bReturn = TRUE;
  30666. }
  30667. }
  30668. /* Want a read-only lock? */
  30669. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  30670. nNumberOfBytesToLockLow == 1){
  30671. if (pFile->shared->bExclusive == 0){
  30672. pFile->local.nReaders ++;
  30673. if (pFile->local.nReaders == 1){
  30674. pFile->shared->nReaders ++;
  30675. }
  30676. bReturn = TRUE;
  30677. }
  30678. }
  30679. /* Want a pending lock? */
  30680. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  30681. && nNumberOfBytesToLockLow == 1){
  30682. /* If no pending lock has been acquired, then acquire it */
  30683. if (pFile->shared->bPending == 0) {
  30684. pFile->shared->bPending = TRUE;
  30685. pFile->local.bPending = TRUE;
  30686. bReturn = TRUE;
  30687. }
  30688. }
  30689. /* Want a reserved lock? */
  30690. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  30691. && nNumberOfBytesToLockLow == 1){
  30692. if (pFile->shared->bReserved == 0) {
  30693. pFile->shared->bReserved = TRUE;
  30694. pFile->local.bReserved = TRUE;
  30695. bReturn = TRUE;
  30696. }
  30697. }
  30698. winceMutexRelease(pFile->hMutex);
  30699. return bReturn;
  30700. }
  30701. /*
  30702. ** An implementation of the UnlockFile API of Windows for CE
  30703. */
  30704. static BOOL winceUnlockFile(
  30705. LPHANDLE phFile,
  30706. DWORD dwFileOffsetLow,
  30707. DWORD dwFileOffsetHigh,
  30708. DWORD nNumberOfBytesToUnlockLow,
  30709. DWORD nNumberOfBytesToUnlockHigh
  30710. ){
  30711. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  30712. BOOL bReturn = FALSE;
  30713. UNUSED_PARAMETER(dwFileOffsetHigh);
  30714. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  30715. if (!pFile->hMutex) return TRUE;
  30716. winceMutexAcquire(pFile->hMutex);
  30717. /* Releasing a reader lock or an exclusive lock */
  30718. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  30719. /* Did we have an exclusive lock? */
  30720. if (pFile->local.bExclusive){
  30721. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  30722. pFile->local.bExclusive = FALSE;
  30723. pFile->shared->bExclusive = FALSE;
  30724. bReturn = TRUE;
  30725. }
  30726. /* Did we just have a reader lock? */
  30727. else if (pFile->local.nReaders){
  30728. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  30729. || nNumberOfBytesToUnlockLow == 1);
  30730. pFile->local.nReaders --;
  30731. if (pFile->local.nReaders == 0)
  30732. {
  30733. pFile->shared->nReaders --;
  30734. }
  30735. bReturn = TRUE;
  30736. }
  30737. }
  30738. /* Releasing a pending lock */
  30739. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  30740. && nNumberOfBytesToUnlockLow == 1){
  30741. if (pFile->local.bPending){
  30742. pFile->local.bPending = FALSE;
  30743. pFile->shared->bPending = FALSE;
  30744. bReturn = TRUE;
  30745. }
  30746. }
  30747. /* Releasing a reserved lock */
  30748. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  30749. && nNumberOfBytesToUnlockLow == 1){
  30750. if (pFile->local.bReserved) {
  30751. pFile->local.bReserved = FALSE;
  30752. pFile->shared->bReserved = FALSE;
  30753. bReturn = TRUE;
  30754. }
  30755. }
  30756. winceMutexRelease(pFile->hMutex);
  30757. return bReturn;
  30758. }
  30759. /*
  30760. ** End of the special code for wince
  30761. *****************************************************************************/
  30762. #endif /* SQLITE_OS_WINCE */
  30763. /*
  30764. ** Lock a file region.
  30765. */
  30766. static BOOL winLockFile(
  30767. LPHANDLE phFile,
  30768. DWORD flags,
  30769. DWORD offsetLow,
  30770. DWORD offsetHigh,
  30771. DWORD numBytesLow,
  30772. DWORD numBytesHigh
  30773. ){
  30774. #if SQLITE_OS_WINCE
  30775. /*
  30776. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  30777. ** API LockFile.
  30778. */
  30779. return winceLockFile(phFile, offsetLow, offsetHigh,
  30780. numBytesLow, numBytesHigh);
  30781. #else
  30782. if( osIsNT() ){
  30783. OVERLAPPED ovlp;
  30784. memset(&ovlp, 0, sizeof(OVERLAPPED));
  30785. ovlp.Offset = offsetLow;
  30786. ovlp.OffsetHigh = offsetHigh;
  30787. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  30788. }else{
  30789. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  30790. numBytesHigh);
  30791. }
  30792. #endif
  30793. }
  30794. /*
  30795. ** Unlock a file region.
  30796. */
  30797. static BOOL winUnlockFile(
  30798. LPHANDLE phFile,
  30799. DWORD offsetLow,
  30800. DWORD offsetHigh,
  30801. DWORD numBytesLow,
  30802. DWORD numBytesHigh
  30803. ){
  30804. #if SQLITE_OS_WINCE
  30805. /*
  30806. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  30807. ** API UnlockFile.
  30808. */
  30809. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  30810. numBytesLow, numBytesHigh);
  30811. #else
  30812. if( osIsNT() ){
  30813. OVERLAPPED ovlp;
  30814. memset(&ovlp, 0, sizeof(OVERLAPPED));
  30815. ovlp.Offset = offsetLow;
  30816. ovlp.OffsetHigh = offsetHigh;
  30817. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  30818. }else{
  30819. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  30820. numBytesHigh);
  30821. }
  30822. #endif
  30823. }
  30824. /*****************************************************************************
  30825. ** The next group of routines implement the I/O methods specified
  30826. ** by the sqlite3_io_methods object.
  30827. ******************************************************************************/
  30828. /*
  30829. ** Some Microsoft compilers lack this definition.
  30830. */
  30831. #ifndef INVALID_SET_FILE_POINTER
  30832. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  30833. #endif
  30834. /*
  30835. ** Move the current position of the file handle passed as the first
  30836. ** argument to offset iOffset within the file. If successful, return 0.
  30837. ** Otherwise, set pFile->lastErrno and return non-zero.
  30838. */
  30839. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  30840. #if !SQLITE_OS_WINRT
  30841. LONG upperBits; /* Most sig. 32 bits of new offset */
  30842. LONG lowerBits; /* Least sig. 32 bits of new offset */
  30843. DWORD dwRet; /* Value returned by SetFilePointer() */
  30844. DWORD lastErrno; /* Value returned by GetLastError() */
  30845. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  30846. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  30847. lowerBits = (LONG)(iOffset & 0xffffffff);
  30848. /* API oddity: If successful, SetFilePointer() returns a dword
  30849. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  30850. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  30851. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  30852. ** whether an error has actually occurred, it is also necessary to call
  30853. ** GetLastError().
  30854. */
  30855. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  30856. if( (dwRet==INVALID_SET_FILE_POINTER
  30857. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  30858. pFile->lastErrno = lastErrno;
  30859. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  30860. "winSeekFile", pFile->zPath);
  30861. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  30862. return 1;
  30863. }
  30864. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  30865. return 0;
  30866. #else
  30867. /*
  30868. ** Same as above, except that this implementation works for WinRT.
  30869. */
  30870. LARGE_INTEGER x; /* The new offset */
  30871. BOOL bRet; /* Value returned by SetFilePointerEx() */
  30872. x.QuadPart = iOffset;
  30873. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  30874. if(!bRet){
  30875. pFile->lastErrno = osGetLastError();
  30876. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  30877. "winSeekFile", pFile->zPath);
  30878. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  30879. return 1;
  30880. }
  30881. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  30882. return 0;
  30883. #endif
  30884. }
  30885. #if SQLITE_MAX_MMAP_SIZE>0
  30886. /* Forward references to VFS helper methods used for memory mapped files */
  30887. static int winMapfile(winFile*, sqlite3_int64);
  30888. static int winUnmapfile(winFile*);
  30889. #endif
  30890. /*
  30891. ** Close a file.
  30892. **
  30893. ** It is reported that an attempt to close a handle might sometimes
  30894. ** fail. This is a very unreasonable result, but Windows is notorious
  30895. ** for being unreasonable so I do not doubt that it might happen. If
  30896. ** the close fails, we pause for 100 milliseconds and try again. As
  30897. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  30898. ** giving up and returning an error.
  30899. */
  30900. #define MX_CLOSE_ATTEMPT 3
  30901. static int winClose(sqlite3_file *id){
  30902. int rc, cnt = 0;
  30903. winFile *pFile = (winFile*)id;
  30904. assert( id!=0 );
  30905. #ifndef SQLITE_OMIT_WAL
  30906. assert( pFile->pShm==0 );
  30907. #endif
  30908. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  30909. OSTRACE(("CLOSE file=%p\n", pFile->h));
  30910. #if SQLITE_MAX_MMAP_SIZE>0
  30911. winUnmapfile(pFile);
  30912. #endif
  30913. do{
  30914. rc = osCloseHandle(pFile->h);
  30915. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  30916. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  30917. #if SQLITE_OS_WINCE
  30918. #define WINCE_DELETION_ATTEMPTS 3
  30919. winceDestroyLock(pFile);
  30920. if( pFile->zDeleteOnClose ){
  30921. int cnt = 0;
  30922. while(
  30923. osDeleteFileW(pFile->zDeleteOnClose)==0
  30924. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  30925. && cnt++ < WINCE_DELETION_ATTEMPTS
  30926. ){
  30927. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  30928. }
  30929. sqlite3_free(pFile->zDeleteOnClose);
  30930. }
  30931. #endif
  30932. if( rc ){
  30933. pFile->h = NULL;
  30934. }
  30935. OpenCounter(-1);
  30936. OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
  30937. return rc ? SQLITE_OK
  30938. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  30939. "winClose", pFile->zPath);
  30940. }
  30941. /*
  30942. ** Read data from a file into a buffer. Return SQLITE_OK if all
  30943. ** bytes were read successfully and SQLITE_IOERR if anything goes
  30944. ** wrong.
  30945. */
  30946. static int winRead(
  30947. sqlite3_file *id, /* File to read from */
  30948. void *pBuf, /* Write content into this buffer */
  30949. int amt, /* Number of bytes to read */
  30950. sqlite3_int64 offset /* Begin reading at this offset */
  30951. ){
  30952. #if !SQLITE_OS_WINCE
  30953. OVERLAPPED overlapped; /* The offset for ReadFile. */
  30954. #endif
  30955. winFile *pFile = (winFile*)id; /* file handle */
  30956. DWORD nRead; /* Number of bytes actually read from file */
  30957. int nRetry = 0; /* Number of retrys */
  30958. assert( id!=0 );
  30959. assert( amt>0 );
  30960. assert( offset>=0 );
  30961. SimulateIOError(return SQLITE_IOERR_READ);
  30962. OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  30963. pFile->h, pBuf, amt, offset, pFile->locktype));
  30964. #if SQLITE_MAX_MMAP_SIZE>0
  30965. /* Deal with as much of this read request as possible by transfering
  30966. ** data from the memory mapping using memcpy(). */
  30967. if( offset<pFile->mmapSize ){
  30968. if( offset+amt <= pFile->mmapSize ){
  30969. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  30970. OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  30971. return SQLITE_OK;
  30972. }else{
  30973. int nCopy = (int)(pFile->mmapSize - offset);
  30974. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  30975. pBuf = &((u8 *)pBuf)[nCopy];
  30976. amt -= nCopy;
  30977. offset += nCopy;
  30978. }
  30979. }
  30980. #endif
  30981. #if SQLITE_OS_WINCE
  30982. if( winSeekFile(pFile, offset) ){
  30983. OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
  30984. return SQLITE_FULL;
  30985. }
  30986. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  30987. #else
  30988. memset(&overlapped, 0, sizeof(OVERLAPPED));
  30989. overlapped.Offset = (LONG)(offset & 0xffffffff);
  30990. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  30991. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  30992. osGetLastError()!=ERROR_HANDLE_EOF ){
  30993. #endif
  30994. DWORD lastErrno;
  30995. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  30996. pFile->lastErrno = lastErrno;
  30997. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
  30998. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  30999. "winRead", pFile->zPath);
  31000. }
  31001. winLogIoerr(nRetry);
  31002. if( nRead<(DWORD)amt ){
  31003. /* Unread parts of the buffer must be zero-filled */
  31004. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  31005. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
  31006. return SQLITE_IOERR_SHORT_READ;
  31007. }
  31008. OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
  31009. return SQLITE_OK;
  31010. }
  31011. /*
  31012. ** Write data from a buffer into a file. Return SQLITE_OK on success
  31013. ** or some other error code on failure.
  31014. */
  31015. static int winWrite(
  31016. sqlite3_file *id, /* File to write into */
  31017. const void *pBuf, /* The bytes to be written */
  31018. int amt, /* Number of bytes to write */
  31019. sqlite3_int64 offset /* Offset into the file to begin writing at */
  31020. ){
  31021. int rc = 0; /* True if error has occurred, else false */
  31022. winFile *pFile = (winFile*)id; /* File handle */
  31023. int nRetry = 0; /* Number of retries */
  31024. assert( amt>0 );
  31025. assert( pFile );
  31026. SimulateIOError(return SQLITE_IOERR_WRITE);
  31027. SimulateDiskfullError(return SQLITE_FULL);
  31028. OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  31029. pFile->h, pBuf, amt, offset, pFile->locktype));
  31030. #if SQLITE_MAX_MMAP_SIZE>0
  31031. /* Deal with as much of this write request as possible by transfering
  31032. ** data from the memory mapping using memcpy(). */
  31033. if( offset<pFile->mmapSize ){
  31034. if( offset+amt <= pFile->mmapSize ){
  31035. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  31036. OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  31037. return SQLITE_OK;
  31038. }else{
  31039. int nCopy = (int)(pFile->mmapSize - offset);
  31040. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  31041. pBuf = &((u8 *)pBuf)[nCopy];
  31042. amt -= nCopy;
  31043. offset += nCopy;
  31044. }
  31045. }
  31046. #endif
  31047. #if SQLITE_OS_WINCE
  31048. rc = winSeekFile(pFile, offset);
  31049. if( rc==0 ){
  31050. #else
  31051. {
  31052. #endif
  31053. #if !SQLITE_OS_WINCE
  31054. OVERLAPPED overlapped; /* The offset for WriteFile. */
  31055. #endif
  31056. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  31057. int nRem = amt; /* Number of bytes yet to be written */
  31058. DWORD nWrite; /* Bytes written by each WriteFile() call */
  31059. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  31060. #if !SQLITE_OS_WINCE
  31061. memset(&overlapped, 0, sizeof(OVERLAPPED));
  31062. overlapped.Offset = (LONG)(offset & 0xffffffff);
  31063. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  31064. #endif
  31065. while( nRem>0 ){
  31066. #if SQLITE_OS_WINCE
  31067. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  31068. #else
  31069. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  31070. #endif
  31071. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  31072. break;
  31073. }
  31074. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  31075. if( nWrite==0 || nWrite>(DWORD)nRem ){
  31076. lastErrno = osGetLastError();
  31077. break;
  31078. }
  31079. #if !SQLITE_OS_WINCE
  31080. offset += nWrite;
  31081. overlapped.Offset = (LONG)(offset & 0xffffffff);
  31082. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  31083. #endif
  31084. aRem += nWrite;
  31085. nRem -= nWrite;
  31086. }
  31087. if( nRem>0 ){
  31088. pFile->lastErrno = lastErrno;
  31089. rc = 1;
  31090. }
  31091. }
  31092. if( rc ){
  31093. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  31094. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  31095. OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
  31096. return winLogError(SQLITE_FULL, pFile->lastErrno,
  31097. "winWrite1", pFile->zPath);
  31098. }
  31099. OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
  31100. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  31101. "winWrite2", pFile->zPath);
  31102. }else{
  31103. winLogIoerr(nRetry);
  31104. }
  31105. OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
  31106. return SQLITE_OK;
  31107. }
  31108. /*
  31109. ** Truncate an open file to a specified size
  31110. */
  31111. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  31112. winFile *pFile = (winFile*)id; /* File handle object */
  31113. int rc = SQLITE_OK; /* Return code for this function */
  31114. DWORD lastErrno;
  31115. assert( pFile );
  31116. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  31117. OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
  31118. pFile->h, nByte, pFile->locktype));
  31119. /* If the user has configured a chunk-size for this file, truncate the
  31120. ** file so that it consists of an integer number of chunks (i.e. the
  31121. ** actual file size after the operation may be larger than the requested
  31122. ** size).
  31123. */
  31124. if( pFile->szChunk>0 ){
  31125. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  31126. }
  31127. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  31128. if( winSeekFile(pFile, nByte) ){
  31129. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  31130. "winTruncate1", pFile->zPath);
  31131. }else if( 0==osSetEndOfFile(pFile->h) &&
  31132. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  31133. pFile->lastErrno = lastErrno;
  31134. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  31135. "winTruncate2", pFile->zPath);
  31136. }
  31137. #if SQLITE_MAX_MMAP_SIZE>0
  31138. /* If the file was truncated to a size smaller than the currently
  31139. ** mapped region, reduce the effective mapping size as well. SQLite will
  31140. ** use read() and write() to access data beyond this point from now on.
  31141. */
  31142. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  31143. pFile->mmapSize = nByte;
  31144. }
  31145. #endif
  31146. OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  31147. return rc;
  31148. }
  31149. #ifdef SQLITE_TEST
  31150. /*
  31151. ** Count the number of fullsyncs and normal syncs. This is used to test
  31152. ** that syncs and fullsyncs are occuring at the right times.
  31153. */
  31154. SQLITE_API int sqlite3_sync_count = 0;
  31155. SQLITE_API int sqlite3_fullsync_count = 0;
  31156. #endif
  31157. /*
  31158. ** Make sure all writes to a particular file are committed to disk.
  31159. */
  31160. static int winSync(sqlite3_file *id, int flags){
  31161. #ifndef SQLITE_NO_SYNC
  31162. /*
  31163. ** Used only when SQLITE_NO_SYNC is not defined.
  31164. */
  31165. BOOL rc;
  31166. #endif
  31167. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  31168. (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
  31169. /*
  31170. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  31171. ** OSTRACE() macros.
  31172. */
  31173. winFile *pFile = (winFile*)id;
  31174. #else
  31175. UNUSED_PARAMETER(id);
  31176. #endif
  31177. assert( pFile );
  31178. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  31179. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  31180. || (flags&0x0F)==SQLITE_SYNC_FULL
  31181. );
  31182. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  31183. ** line is to test that doing so does not cause any problems.
  31184. */
  31185. SimulateDiskfullError( return SQLITE_FULL );
  31186. OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
  31187. pFile->h, flags, pFile->locktype));
  31188. #ifndef SQLITE_TEST
  31189. UNUSED_PARAMETER(flags);
  31190. #else
  31191. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  31192. sqlite3_fullsync_count++;
  31193. }
  31194. sqlite3_sync_count++;
  31195. #endif
  31196. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  31197. ** no-op
  31198. */
  31199. #ifdef SQLITE_NO_SYNC
  31200. OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
  31201. return SQLITE_OK;
  31202. #else
  31203. rc = osFlushFileBuffers(pFile->h);
  31204. SimulateIOError( rc=FALSE );
  31205. if( rc ){
  31206. OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
  31207. return SQLITE_OK;
  31208. }else{
  31209. pFile->lastErrno = osGetLastError();
  31210. OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
  31211. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  31212. "winSync", pFile->zPath);
  31213. }
  31214. #endif
  31215. }
  31216. /*
  31217. ** Determine the current size of a file in bytes
  31218. */
  31219. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  31220. winFile *pFile = (winFile*)id;
  31221. int rc = SQLITE_OK;
  31222. assert( id!=0 );
  31223. assert( pSize!=0 );
  31224. SimulateIOError(return SQLITE_IOERR_FSTAT);
  31225. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  31226. #if SQLITE_OS_WINRT
  31227. {
  31228. FILE_STANDARD_INFO info;
  31229. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  31230. &info, sizeof(info)) ){
  31231. *pSize = info.EndOfFile.QuadPart;
  31232. }else{
  31233. pFile->lastErrno = osGetLastError();
  31234. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  31235. "winFileSize", pFile->zPath);
  31236. }
  31237. }
  31238. #else
  31239. {
  31240. DWORD upperBits;
  31241. DWORD lowerBits;
  31242. DWORD lastErrno;
  31243. lowerBits = osGetFileSize(pFile->h, &upperBits);
  31244. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  31245. if( (lowerBits == INVALID_FILE_SIZE)
  31246. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  31247. pFile->lastErrno = lastErrno;
  31248. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  31249. "winFileSize", pFile->zPath);
  31250. }
  31251. }
  31252. #endif
  31253. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  31254. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  31255. return rc;
  31256. }
  31257. /*
  31258. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  31259. */
  31260. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  31261. # define LOCKFILE_FAIL_IMMEDIATELY 1
  31262. #endif
  31263. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  31264. # define LOCKFILE_EXCLUSIVE_LOCK 2
  31265. #endif
  31266. /*
  31267. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  31268. ** When the LockFile function was used, it was always expected to fail
  31269. ** immediately if the lock could not be obtained. Also, it always expected to
  31270. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  31271. ** and reflect those expectations; therefore, they should not be changed.
  31272. */
  31273. #ifndef SQLITE_LOCKFILE_FLAGS
  31274. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  31275. LOCKFILE_EXCLUSIVE_LOCK)
  31276. #endif
  31277. /*
  31278. ** Currently, SQLite never calls the LockFileEx function without wanting the
  31279. ** call to fail immediately if the lock cannot be obtained.
  31280. */
  31281. #ifndef SQLITE_LOCKFILEEX_FLAGS
  31282. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  31283. #endif
  31284. /*
  31285. ** Acquire a reader lock.
  31286. ** Different API routines are called depending on whether or not this
  31287. ** is Win9x or WinNT.
  31288. */
  31289. static int winGetReadLock(winFile *pFile){
  31290. int res;
  31291. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  31292. if( osIsNT() ){
  31293. #if SQLITE_OS_WINCE
  31294. /*
  31295. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  31296. ** API LockFileEx.
  31297. */
  31298. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  31299. #else
  31300. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  31301. SHARED_SIZE, 0);
  31302. #endif
  31303. }
  31304. #ifdef SQLITE_WIN32_HAS_ANSI
  31305. else{
  31306. int lk;
  31307. sqlite3_randomness(sizeof(lk), &lk);
  31308. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  31309. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  31310. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  31311. }
  31312. #endif
  31313. if( res == 0 ){
  31314. pFile->lastErrno = osGetLastError();
  31315. /* No need to log a failure to lock */
  31316. }
  31317. OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
  31318. return res;
  31319. }
  31320. /*
  31321. ** Undo a readlock
  31322. */
  31323. static int winUnlockReadLock(winFile *pFile){
  31324. int res;
  31325. DWORD lastErrno;
  31326. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  31327. if( osIsNT() ){
  31328. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  31329. }
  31330. #ifdef SQLITE_WIN32_HAS_ANSI
  31331. else{
  31332. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  31333. }
  31334. #endif
  31335. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  31336. pFile->lastErrno = lastErrno;
  31337. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  31338. "winUnlockReadLock", pFile->zPath);
  31339. }
  31340. OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
  31341. return res;
  31342. }
  31343. /*
  31344. ** Lock the file with the lock specified by parameter locktype - one
  31345. ** of the following:
  31346. **
  31347. ** (1) SHARED_LOCK
  31348. ** (2) RESERVED_LOCK
  31349. ** (3) PENDING_LOCK
  31350. ** (4) EXCLUSIVE_LOCK
  31351. **
  31352. ** Sometimes when requesting one lock state, additional lock states
  31353. ** are inserted in between. The locking might fail on one of the later
  31354. ** transitions leaving the lock state different from what it started but
  31355. ** still short of its goal. The following chart shows the allowed
  31356. ** transitions and the inserted intermediate states:
  31357. **
  31358. ** UNLOCKED -> SHARED
  31359. ** SHARED -> RESERVED
  31360. ** SHARED -> (PENDING) -> EXCLUSIVE
  31361. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31362. ** PENDING -> EXCLUSIVE
  31363. **
  31364. ** This routine will only increase a lock. The winUnlock() routine
  31365. ** erases all locks at once and returns us immediately to locking level 0.
  31366. ** It is not possible to lower the locking level one step at a time. You
  31367. ** must go straight to locking level 0.
  31368. */
  31369. static int winLock(sqlite3_file *id, int locktype){
  31370. int rc = SQLITE_OK; /* Return code from subroutines */
  31371. int res = 1; /* Result of a Windows lock call */
  31372. int newLocktype; /* Set pFile->locktype to this value before exiting */
  31373. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  31374. winFile *pFile = (winFile*)id;
  31375. DWORD lastErrno = NO_ERROR;
  31376. assert( id!=0 );
  31377. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  31378. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  31379. /* If there is already a lock of this type or more restrictive on the
  31380. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  31381. ** sqlite3OsEnterMutex() hasn't been called yet.
  31382. */
  31383. if( pFile->locktype>=locktype ){
  31384. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  31385. return SQLITE_OK;
  31386. }
  31387. /* Make sure the locking sequence is correct
  31388. */
  31389. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  31390. assert( locktype!=PENDING_LOCK );
  31391. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  31392. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  31393. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  31394. ** the PENDING_LOCK byte is temporary.
  31395. */
  31396. newLocktype = pFile->locktype;
  31397. if( (pFile->locktype==NO_LOCK)
  31398. || ( (locktype==EXCLUSIVE_LOCK)
  31399. && (pFile->locktype==RESERVED_LOCK))
  31400. ){
  31401. int cnt = 3;
  31402. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  31403. PENDING_BYTE, 0, 1, 0))==0 ){
  31404. /* Try 3 times to get the pending lock. This is needed to work
  31405. ** around problems caused by indexing and/or anti-virus software on
  31406. ** Windows systems.
  31407. ** If you are using this code as a model for alternative VFSes, do not
  31408. ** copy this retry logic. It is a hack intended for Windows only.
  31409. */
  31410. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n",
  31411. pFile->h, cnt, sqlite3ErrName(res)));
  31412. if( cnt ) sqlite3_win32_sleep(1);
  31413. }
  31414. gotPendingLock = res;
  31415. if( !res ){
  31416. lastErrno = osGetLastError();
  31417. }
  31418. }
  31419. /* Acquire a shared lock
  31420. */
  31421. if( locktype==SHARED_LOCK && res ){
  31422. assert( pFile->locktype==NO_LOCK );
  31423. res = winGetReadLock(pFile);
  31424. if( res ){
  31425. newLocktype = SHARED_LOCK;
  31426. }else{
  31427. lastErrno = osGetLastError();
  31428. }
  31429. }
  31430. /* Acquire a RESERVED lock
  31431. */
  31432. if( locktype==RESERVED_LOCK && res ){
  31433. assert( pFile->locktype==SHARED_LOCK );
  31434. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  31435. if( res ){
  31436. newLocktype = RESERVED_LOCK;
  31437. }else{
  31438. lastErrno = osGetLastError();
  31439. }
  31440. }
  31441. /* Acquire a PENDING lock
  31442. */
  31443. if( locktype==EXCLUSIVE_LOCK && res ){
  31444. newLocktype = PENDING_LOCK;
  31445. gotPendingLock = 0;
  31446. }
  31447. /* Acquire an EXCLUSIVE lock
  31448. */
  31449. if( locktype==EXCLUSIVE_LOCK && res ){
  31450. assert( pFile->locktype>=SHARED_LOCK );
  31451. res = winUnlockReadLock(pFile);
  31452. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  31453. SHARED_SIZE, 0);
  31454. if( res ){
  31455. newLocktype = EXCLUSIVE_LOCK;
  31456. }else{
  31457. lastErrno = osGetLastError();
  31458. winGetReadLock(pFile);
  31459. }
  31460. }
  31461. /* If we are holding a PENDING lock that ought to be released, then
  31462. ** release it now.
  31463. */
  31464. if( gotPendingLock && locktype==SHARED_LOCK ){
  31465. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  31466. }
  31467. /* Update the state of the lock has held in the file descriptor then
  31468. ** return the appropriate result code.
  31469. */
  31470. if( res ){
  31471. rc = SQLITE_OK;
  31472. }else{
  31473. pFile->lastErrno = lastErrno;
  31474. rc = SQLITE_BUSY;
  31475. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  31476. pFile->h, locktype, newLocktype));
  31477. }
  31478. pFile->locktype = (u8)newLocktype;
  31479. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  31480. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  31481. return rc;
  31482. }
  31483. /*
  31484. ** This routine checks if there is a RESERVED lock held on the specified
  31485. ** file by this or any other process. If such a lock is held, return
  31486. ** non-zero, otherwise zero.
  31487. */
  31488. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  31489. int rc;
  31490. winFile *pFile = (winFile*)id;
  31491. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  31492. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  31493. assert( id!=0 );
  31494. if( pFile->locktype>=RESERVED_LOCK ){
  31495. rc = 1;
  31496. OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc));
  31497. }else{
  31498. rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
  31499. if( rc ){
  31500. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  31501. }
  31502. rc = !rc;
  31503. OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc));
  31504. }
  31505. *pResOut = rc;
  31506. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  31507. pFile->h, pResOut, *pResOut));
  31508. return SQLITE_OK;
  31509. }
  31510. /*
  31511. ** Lower the locking level on file descriptor id to locktype. locktype
  31512. ** must be either NO_LOCK or SHARED_LOCK.
  31513. **
  31514. ** If the locking level of the file descriptor is already at or below
  31515. ** the requested locking level, this routine is a no-op.
  31516. **
  31517. ** It is not possible for this routine to fail if the second argument
  31518. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  31519. ** might return SQLITE_IOERR;
  31520. */
  31521. static int winUnlock(sqlite3_file *id, int locktype){
  31522. int type;
  31523. winFile *pFile = (winFile*)id;
  31524. int rc = SQLITE_OK;
  31525. assert( pFile!=0 );
  31526. assert( locktype<=SHARED_LOCK );
  31527. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  31528. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  31529. type = pFile->locktype;
  31530. if( type>=EXCLUSIVE_LOCK ){
  31531. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  31532. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  31533. /* This should never happen. We should always be able to
  31534. ** reacquire the read lock */
  31535. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  31536. "winUnlock", pFile->zPath);
  31537. }
  31538. }
  31539. if( type>=RESERVED_LOCK ){
  31540. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  31541. }
  31542. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  31543. winUnlockReadLock(pFile);
  31544. }
  31545. if( type>=PENDING_LOCK ){
  31546. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  31547. }
  31548. pFile->locktype = (u8)locktype;
  31549. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  31550. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  31551. return rc;
  31552. }
  31553. /*
  31554. ** If *pArg is inititially negative then this is a query. Set *pArg to
  31555. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  31556. **
  31557. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  31558. */
  31559. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  31560. if( *pArg<0 ){
  31561. *pArg = (pFile->ctrlFlags & mask)!=0;
  31562. }else if( (*pArg)==0 ){
  31563. pFile->ctrlFlags &= ~mask;
  31564. }else{
  31565. pFile->ctrlFlags |= mask;
  31566. }
  31567. }
  31568. /* Forward references to VFS helper methods used for temporary files */
  31569. static int winGetTempname(sqlite3_vfs *, char **);
  31570. static int winIsDir(const void *);
  31571. static BOOL winIsDriveLetterAndColon(const char *);
  31572. /*
  31573. ** Control and query of the open file handle.
  31574. */
  31575. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  31576. winFile *pFile = (winFile*)id;
  31577. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  31578. switch( op ){
  31579. case SQLITE_FCNTL_LOCKSTATE: {
  31580. *(int*)pArg = pFile->locktype;
  31581. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31582. return SQLITE_OK;
  31583. }
  31584. case SQLITE_LAST_ERRNO: {
  31585. *(int*)pArg = (int)pFile->lastErrno;
  31586. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31587. return SQLITE_OK;
  31588. }
  31589. case SQLITE_FCNTL_CHUNK_SIZE: {
  31590. pFile->szChunk = *(int *)pArg;
  31591. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31592. return SQLITE_OK;
  31593. }
  31594. case SQLITE_FCNTL_SIZE_HINT: {
  31595. if( pFile->szChunk>0 ){
  31596. sqlite3_int64 oldSz;
  31597. int rc = winFileSize(id, &oldSz);
  31598. if( rc==SQLITE_OK ){
  31599. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  31600. if( newSz>oldSz ){
  31601. SimulateIOErrorBenign(1);
  31602. rc = winTruncate(id, newSz);
  31603. SimulateIOErrorBenign(0);
  31604. }
  31605. }
  31606. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  31607. return rc;
  31608. }
  31609. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31610. return SQLITE_OK;
  31611. }
  31612. case SQLITE_FCNTL_PERSIST_WAL: {
  31613. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  31614. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31615. return SQLITE_OK;
  31616. }
  31617. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  31618. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  31619. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31620. return SQLITE_OK;
  31621. }
  31622. case SQLITE_FCNTL_VFSNAME: {
  31623. *(char**)pArg = sqlite3_mprintf("win32");
  31624. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31625. return SQLITE_OK;
  31626. }
  31627. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  31628. int *a = (int*)pArg;
  31629. if( a[0]>0 ){
  31630. winIoerrRetry = a[0];
  31631. }else{
  31632. a[0] = winIoerrRetry;
  31633. }
  31634. if( a[1]>0 ){
  31635. winIoerrRetryDelay = a[1];
  31636. }else{
  31637. a[1] = winIoerrRetryDelay;
  31638. }
  31639. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31640. return SQLITE_OK;
  31641. }
  31642. case SQLITE_FCNTL_TEMPFILENAME: {
  31643. char *zTFile = 0;
  31644. int rc = winGetTempname(pFile->pVfs, &zTFile);
  31645. if( rc==SQLITE_OK ){
  31646. *(char**)pArg = zTFile;
  31647. }
  31648. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  31649. return rc;
  31650. }
  31651. #if SQLITE_MAX_MMAP_SIZE>0
  31652. case SQLITE_FCNTL_MMAP_SIZE: {
  31653. i64 newLimit = *(i64*)pArg;
  31654. int rc = SQLITE_OK;
  31655. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  31656. newLimit = sqlite3GlobalConfig.mxMmap;
  31657. }
  31658. *(i64*)pArg = pFile->mmapSizeMax;
  31659. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  31660. pFile->mmapSizeMax = newLimit;
  31661. if( pFile->mmapSize>0 ){
  31662. winUnmapfile(pFile);
  31663. rc = winMapfile(pFile, -1);
  31664. }
  31665. }
  31666. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  31667. return rc;
  31668. }
  31669. #endif
  31670. }
  31671. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  31672. return SQLITE_NOTFOUND;
  31673. }
  31674. /*
  31675. ** Return the sector size in bytes of the underlying block device for
  31676. ** the specified file. This is almost always 512 bytes, but may be
  31677. ** larger for some devices.
  31678. **
  31679. ** SQLite code assumes this function cannot fail. It also assumes that
  31680. ** if two files are created in the same file-system directory (i.e.
  31681. ** a database and its journal file) that the sector size will be the
  31682. ** same for both.
  31683. */
  31684. static int winSectorSize(sqlite3_file *id){
  31685. (void)id;
  31686. return SQLITE_DEFAULT_SECTOR_SIZE;
  31687. }
  31688. /*
  31689. ** Return a vector of device characteristics.
  31690. */
  31691. static int winDeviceCharacteristics(sqlite3_file *id){
  31692. winFile *p = (winFile*)id;
  31693. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  31694. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  31695. }
  31696. /*
  31697. ** Windows will only let you create file view mappings
  31698. ** on allocation size granularity boundaries.
  31699. ** During sqlite3_os_init() we do a GetSystemInfo()
  31700. ** to get the granularity size.
  31701. */
  31702. SYSTEM_INFO winSysInfo;
  31703. #ifndef SQLITE_OMIT_WAL
  31704. /*
  31705. ** Helper functions to obtain and relinquish the global mutex. The
  31706. ** global mutex is used to protect the winLockInfo objects used by
  31707. ** this file, all of which may be shared by multiple threads.
  31708. **
  31709. ** Function winShmMutexHeld() is used to assert() that the global mutex
  31710. ** is held when required. This function is only used as part of assert()
  31711. ** statements. e.g.
  31712. **
  31713. ** winShmEnterMutex()
  31714. ** assert( winShmMutexHeld() );
  31715. ** winShmLeaveMutex()
  31716. */
  31717. static void winShmEnterMutex(void){
  31718. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  31719. }
  31720. static void winShmLeaveMutex(void){
  31721. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  31722. }
  31723. #ifdef SQLITE_DEBUG
  31724. static int winShmMutexHeld(void) {
  31725. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  31726. }
  31727. #endif
  31728. /*
  31729. ** Object used to represent a single file opened and mmapped to provide
  31730. ** shared memory. When multiple threads all reference the same
  31731. ** log-summary, each thread has its own winFile object, but they all
  31732. ** point to a single instance of this object. In other words, each
  31733. ** log-summary is opened only once per process.
  31734. **
  31735. ** winShmMutexHeld() must be true when creating or destroying
  31736. ** this object or while reading or writing the following fields:
  31737. **
  31738. ** nRef
  31739. ** pNext
  31740. **
  31741. ** The following fields are read-only after the object is created:
  31742. **
  31743. ** fid
  31744. ** zFilename
  31745. **
  31746. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  31747. ** winShmMutexHeld() is true when reading or writing any other field
  31748. ** in this structure.
  31749. **
  31750. */
  31751. struct winShmNode {
  31752. sqlite3_mutex *mutex; /* Mutex to access this object */
  31753. char *zFilename; /* Name of the file */
  31754. winFile hFile; /* File handle from winOpen */
  31755. int szRegion; /* Size of shared-memory regions */
  31756. int nRegion; /* Size of array apRegion */
  31757. struct ShmRegion {
  31758. HANDLE hMap; /* File handle from CreateFileMapping */
  31759. void *pMap;
  31760. } *aRegion;
  31761. DWORD lastErrno; /* The Windows errno from the last I/O error */
  31762. int nRef; /* Number of winShm objects pointing to this */
  31763. winShm *pFirst; /* All winShm objects pointing to this */
  31764. winShmNode *pNext; /* Next in list of all winShmNode objects */
  31765. #ifdef SQLITE_DEBUG
  31766. u8 nextShmId; /* Next available winShm.id value */
  31767. #endif
  31768. };
  31769. /*
  31770. ** A global array of all winShmNode objects.
  31771. **
  31772. ** The winShmMutexHeld() must be true while reading or writing this list.
  31773. */
  31774. static winShmNode *winShmNodeList = 0;
  31775. /*
  31776. ** Structure used internally by this VFS to record the state of an
  31777. ** open shared memory connection.
  31778. **
  31779. ** The following fields are initialized when this object is created and
  31780. ** are read-only thereafter:
  31781. **
  31782. ** winShm.pShmNode
  31783. ** winShm.id
  31784. **
  31785. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  31786. ** while accessing any read/write fields.
  31787. */
  31788. struct winShm {
  31789. winShmNode *pShmNode; /* The underlying winShmNode object */
  31790. winShm *pNext; /* Next winShm with the same winShmNode */
  31791. u8 hasMutex; /* True if holding the winShmNode mutex */
  31792. u16 sharedMask; /* Mask of shared locks held */
  31793. u16 exclMask; /* Mask of exclusive locks held */
  31794. #ifdef SQLITE_DEBUG
  31795. u8 id; /* Id of this connection with its winShmNode */
  31796. #endif
  31797. };
  31798. /*
  31799. ** Constants used for locking
  31800. */
  31801. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  31802. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  31803. /*
  31804. ** Apply advisory locks for all n bytes beginning at ofst.
  31805. */
  31806. #define _SHM_UNLCK 1
  31807. #define _SHM_RDLCK 2
  31808. #define _SHM_WRLCK 3
  31809. static int winShmSystemLock(
  31810. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  31811. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  31812. int ofst, /* Offset to first byte to be locked/unlocked */
  31813. int nByte /* Number of bytes to lock or unlock */
  31814. ){
  31815. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  31816. /* Access to the winShmNode object is serialized by the caller */
  31817. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  31818. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  31819. pFile->hFile.h, lockType, ofst, nByte));
  31820. /* Release/Acquire the system-level lock */
  31821. if( lockType==_SHM_UNLCK ){
  31822. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  31823. }else{
  31824. /* Initialize the locking parameters */
  31825. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  31826. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  31827. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  31828. }
  31829. if( rc!= 0 ){
  31830. rc = SQLITE_OK;
  31831. }else{
  31832. pFile->lastErrno = osGetLastError();
  31833. rc = SQLITE_BUSY;
  31834. }
  31835. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  31836. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  31837. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  31838. return rc;
  31839. }
  31840. /* Forward references to VFS methods */
  31841. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  31842. static int winDelete(sqlite3_vfs *,const char*,int);
  31843. /*
  31844. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  31845. **
  31846. ** This is not a VFS shared-memory method; it is a utility function called
  31847. ** by VFS shared-memory methods.
  31848. */
  31849. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  31850. winShmNode **pp;
  31851. winShmNode *p;
  31852. assert( winShmMutexHeld() );
  31853. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  31854. osGetCurrentProcessId(), deleteFlag));
  31855. pp = &winShmNodeList;
  31856. while( (p = *pp)!=0 ){
  31857. if( p->nRef==0 ){
  31858. int i;
  31859. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  31860. for(i=0; i<p->nRegion; i++){
  31861. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  31862. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  31863. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  31864. UNUSED_VARIABLE_VALUE(bRc);
  31865. bRc = osCloseHandle(p->aRegion[i].hMap);
  31866. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  31867. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  31868. UNUSED_VARIABLE_VALUE(bRc);
  31869. }
  31870. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  31871. SimulateIOErrorBenign(1);
  31872. winClose((sqlite3_file *)&p->hFile);
  31873. SimulateIOErrorBenign(0);
  31874. }
  31875. if( deleteFlag ){
  31876. SimulateIOErrorBenign(1);
  31877. sqlite3BeginBenignMalloc();
  31878. winDelete(pVfs, p->zFilename, 0);
  31879. sqlite3EndBenignMalloc();
  31880. SimulateIOErrorBenign(0);
  31881. }
  31882. *pp = p->pNext;
  31883. sqlite3_free(p->aRegion);
  31884. sqlite3_free(p);
  31885. }else{
  31886. pp = &p->pNext;
  31887. }
  31888. }
  31889. }
  31890. /*
  31891. ** Open the shared-memory area associated with database file pDbFd.
  31892. **
  31893. ** When opening a new shared-memory file, if no other instances of that
  31894. ** file are currently open, in this process or in other processes, then
  31895. ** the file must be truncated to zero length or have its header cleared.
  31896. */
  31897. static int winOpenSharedMemory(winFile *pDbFd){
  31898. struct winShm *p; /* The connection to be opened */
  31899. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  31900. int rc; /* Result code */
  31901. struct winShmNode *pNew; /* Newly allocated winShmNode */
  31902. int nName; /* Size of zName in bytes */
  31903. assert( pDbFd->pShm==0 ); /* Not previously opened */
  31904. /* Allocate space for the new sqlite3_shm object. Also speculatively
  31905. ** allocate space for a new winShmNode and filename.
  31906. */
  31907. p = sqlite3MallocZero( sizeof(*p) );
  31908. if( p==0 ) return SQLITE_IOERR_NOMEM;
  31909. nName = sqlite3Strlen30(pDbFd->zPath);
  31910. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  31911. if( pNew==0 ){
  31912. sqlite3_free(p);
  31913. return SQLITE_IOERR_NOMEM;
  31914. }
  31915. pNew->zFilename = (char*)&pNew[1];
  31916. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  31917. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  31918. /* Look to see if there is an existing winShmNode that can be used.
  31919. ** If no matching winShmNode currently exists, create a new one.
  31920. */
  31921. winShmEnterMutex();
  31922. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  31923. /* TBD need to come up with better match here. Perhaps
  31924. ** use FILE_ID_BOTH_DIR_INFO Structure.
  31925. */
  31926. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  31927. }
  31928. if( pShmNode ){
  31929. sqlite3_free(pNew);
  31930. }else{
  31931. pShmNode = pNew;
  31932. pNew = 0;
  31933. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  31934. pShmNode->pNext = winShmNodeList;
  31935. winShmNodeList = pShmNode;
  31936. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  31937. if( pShmNode->mutex==0 ){
  31938. rc = SQLITE_IOERR_NOMEM;
  31939. goto shm_open_err;
  31940. }
  31941. rc = winOpen(pDbFd->pVfs,
  31942. pShmNode->zFilename, /* Name of the file (UTF-8) */
  31943. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  31944. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  31945. 0);
  31946. if( SQLITE_OK!=rc ){
  31947. goto shm_open_err;
  31948. }
  31949. /* Check to see if another process is holding the dead-man switch.
  31950. ** If not, truncate the file to zero length.
  31951. */
  31952. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  31953. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  31954. if( rc!=SQLITE_OK ){
  31955. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  31956. "winOpenShm", pDbFd->zPath);
  31957. }
  31958. }
  31959. if( rc==SQLITE_OK ){
  31960. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  31961. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  31962. }
  31963. if( rc ) goto shm_open_err;
  31964. }
  31965. /* Make the new connection a child of the winShmNode */
  31966. p->pShmNode = pShmNode;
  31967. #ifdef SQLITE_DEBUG
  31968. p->id = pShmNode->nextShmId++;
  31969. #endif
  31970. pShmNode->nRef++;
  31971. pDbFd->pShm = p;
  31972. winShmLeaveMutex();
  31973. /* The reference count on pShmNode has already been incremented under
  31974. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  31975. ** new (struct winShm) object to the pShmNode has been set. All that is
  31976. ** left to do is to link the new object into the linked list starting
  31977. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  31978. ** mutex.
  31979. */
  31980. sqlite3_mutex_enter(pShmNode->mutex);
  31981. p->pNext = pShmNode->pFirst;
  31982. pShmNode->pFirst = p;
  31983. sqlite3_mutex_leave(pShmNode->mutex);
  31984. return SQLITE_OK;
  31985. /* Jump here on any error */
  31986. shm_open_err:
  31987. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  31988. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  31989. sqlite3_free(p);
  31990. sqlite3_free(pNew);
  31991. winShmLeaveMutex();
  31992. return rc;
  31993. }
  31994. /*
  31995. ** Close a connection to shared-memory. Delete the underlying
  31996. ** storage if deleteFlag is true.
  31997. */
  31998. static int winShmUnmap(
  31999. sqlite3_file *fd, /* Database holding shared memory */
  32000. int deleteFlag /* Delete after closing if true */
  32001. ){
  32002. winFile *pDbFd; /* Database holding shared-memory */
  32003. winShm *p; /* The connection to be closed */
  32004. winShmNode *pShmNode; /* The underlying shared-memory file */
  32005. winShm **pp; /* For looping over sibling connections */
  32006. pDbFd = (winFile*)fd;
  32007. p = pDbFd->pShm;
  32008. if( p==0 ) return SQLITE_OK;
  32009. pShmNode = p->pShmNode;
  32010. /* Remove connection p from the set of connections associated
  32011. ** with pShmNode */
  32012. sqlite3_mutex_enter(pShmNode->mutex);
  32013. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  32014. *pp = p->pNext;
  32015. /* Free the connection p */
  32016. sqlite3_free(p);
  32017. pDbFd->pShm = 0;
  32018. sqlite3_mutex_leave(pShmNode->mutex);
  32019. /* If pShmNode->nRef has reached 0, then close the underlying
  32020. ** shared-memory file, too */
  32021. winShmEnterMutex();
  32022. assert( pShmNode->nRef>0 );
  32023. pShmNode->nRef--;
  32024. if( pShmNode->nRef==0 ){
  32025. winShmPurge(pDbFd->pVfs, deleteFlag);
  32026. }
  32027. winShmLeaveMutex();
  32028. return SQLITE_OK;
  32029. }
  32030. /*
  32031. ** Change the lock state for a shared-memory segment.
  32032. */
  32033. static int winShmLock(
  32034. sqlite3_file *fd, /* Database file holding the shared memory */
  32035. int ofst, /* First lock to acquire or release */
  32036. int n, /* Number of locks to acquire or release */
  32037. int flags /* What to do with the lock */
  32038. ){
  32039. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  32040. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  32041. winShm *pX; /* For looping over all siblings */
  32042. winShmNode *pShmNode = p->pShmNode;
  32043. int rc = SQLITE_OK; /* Result code */
  32044. u16 mask; /* Mask of locks to take or release */
  32045. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  32046. assert( n>=1 );
  32047. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  32048. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  32049. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  32050. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  32051. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  32052. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  32053. assert( n>1 || mask==(1<<ofst) );
  32054. sqlite3_mutex_enter(pShmNode->mutex);
  32055. if( flags & SQLITE_SHM_UNLOCK ){
  32056. u16 allMask = 0; /* Mask of locks held by siblings */
  32057. /* See if any siblings hold this same lock */
  32058. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32059. if( pX==p ) continue;
  32060. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  32061. allMask |= pX->sharedMask;
  32062. }
  32063. /* Unlock the system-level locks */
  32064. if( (mask & allMask)==0 ){
  32065. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  32066. }else{
  32067. rc = SQLITE_OK;
  32068. }
  32069. /* Undo the local locks */
  32070. if( rc==SQLITE_OK ){
  32071. p->exclMask &= ~mask;
  32072. p->sharedMask &= ~mask;
  32073. }
  32074. }else if( flags & SQLITE_SHM_SHARED ){
  32075. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  32076. /* Find out which shared locks are already held by sibling connections.
  32077. ** If any sibling already holds an exclusive lock, go ahead and return
  32078. ** SQLITE_BUSY.
  32079. */
  32080. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32081. if( (pX->exclMask & mask)!=0 ){
  32082. rc = SQLITE_BUSY;
  32083. break;
  32084. }
  32085. allShared |= pX->sharedMask;
  32086. }
  32087. /* Get shared locks at the system level, if necessary */
  32088. if( rc==SQLITE_OK ){
  32089. if( (allShared & mask)==0 ){
  32090. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  32091. }else{
  32092. rc = SQLITE_OK;
  32093. }
  32094. }
  32095. /* Get the local shared locks */
  32096. if( rc==SQLITE_OK ){
  32097. p->sharedMask |= mask;
  32098. }
  32099. }else{
  32100. /* Make sure no sibling connections hold locks that will block this
  32101. ** lock. If any do, return SQLITE_BUSY right away.
  32102. */
  32103. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32104. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  32105. rc = SQLITE_BUSY;
  32106. break;
  32107. }
  32108. }
  32109. /* Get the exclusive locks at the system level. Then if successful
  32110. ** also mark the local connection as being locked.
  32111. */
  32112. if( rc==SQLITE_OK ){
  32113. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  32114. if( rc==SQLITE_OK ){
  32115. assert( (p->sharedMask & mask)==0 );
  32116. p->exclMask |= mask;
  32117. }
  32118. }
  32119. }
  32120. sqlite3_mutex_leave(pShmNode->mutex);
  32121. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  32122. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  32123. sqlite3ErrName(rc)));
  32124. return rc;
  32125. }
  32126. /*
  32127. ** Implement a memory barrier or memory fence on shared memory.
  32128. **
  32129. ** All loads and stores begun before the barrier must complete before
  32130. ** any load or store begun after the barrier.
  32131. */
  32132. static void winShmBarrier(
  32133. sqlite3_file *fd /* Database holding the shared memory */
  32134. ){
  32135. UNUSED_PARAMETER(fd);
  32136. /* MemoryBarrier(); // does not work -- do not know why not */
  32137. winShmEnterMutex();
  32138. winShmLeaveMutex();
  32139. }
  32140. /*
  32141. ** This function is called to obtain a pointer to region iRegion of the
  32142. ** shared-memory associated with the database file fd. Shared-memory regions
  32143. ** are numbered starting from zero. Each shared-memory region is szRegion
  32144. ** bytes in size.
  32145. **
  32146. ** If an error occurs, an error code is returned and *pp is set to NULL.
  32147. **
  32148. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  32149. ** region has not been allocated (by any client, including one running in a
  32150. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  32151. ** isWrite is non-zero and the requested shared-memory region has not yet
  32152. ** been allocated, it is allocated by this function.
  32153. **
  32154. ** If the shared-memory region has already been allocated or is allocated by
  32155. ** this call as described above, then it is mapped into this processes
  32156. ** address space (if it is not already), *pp is set to point to the mapped
  32157. ** memory and SQLITE_OK returned.
  32158. */
  32159. static int winShmMap(
  32160. sqlite3_file *fd, /* Handle open on database file */
  32161. int iRegion, /* Region to retrieve */
  32162. int szRegion, /* Size of regions */
  32163. int isWrite, /* True to extend file if necessary */
  32164. void volatile **pp /* OUT: Mapped memory */
  32165. ){
  32166. winFile *pDbFd = (winFile*)fd;
  32167. winShm *p = pDbFd->pShm;
  32168. winShmNode *pShmNode;
  32169. int rc = SQLITE_OK;
  32170. if( !p ){
  32171. rc = winOpenSharedMemory(pDbFd);
  32172. if( rc!=SQLITE_OK ) return rc;
  32173. p = pDbFd->pShm;
  32174. }
  32175. pShmNode = p->pShmNode;
  32176. sqlite3_mutex_enter(pShmNode->mutex);
  32177. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  32178. if( pShmNode->nRegion<=iRegion ){
  32179. struct ShmRegion *apNew; /* New aRegion[] array */
  32180. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  32181. sqlite3_int64 sz; /* Current size of wal-index file */
  32182. pShmNode->szRegion = szRegion;
  32183. /* The requested region is not mapped into this processes address space.
  32184. ** Check to see if it has been allocated (i.e. if the wal-index file is
  32185. ** large enough to contain the requested region).
  32186. */
  32187. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  32188. if( rc!=SQLITE_OK ){
  32189. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  32190. "winShmMap1", pDbFd->zPath);
  32191. goto shmpage_out;
  32192. }
  32193. if( sz<nByte ){
  32194. /* The requested memory region does not exist. If isWrite is set to
  32195. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  32196. **
  32197. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  32198. ** the requested memory region.
  32199. */
  32200. if( !isWrite ) goto shmpage_out;
  32201. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  32202. if( rc!=SQLITE_OK ){
  32203. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  32204. "winShmMap2", pDbFd->zPath);
  32205. goto shmpage_out;
  32206. }
  32207. }
  32208. /* Map the requested memory region into this processes address space. */
  32209. apNew = (struct ShmRegion *)sqlite3_realloc(
  32210. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  32211. );
  32212. if( !apNew ){
  32213. rc = SQLITE_IOERR_NOMEM;
  32214. goto shmpage_out;
  32215. }
  32216. pShmNode->aRegion = apNew;
  32217. while( pShmNode->nRegion<=iRegion ){
  32218. HANDLE hMap = NULL; /* file-mapping handle */
  32219. void *pMap = 0; /* Mapped memory region */
  32220. #if SQLITE_OS_WINRT
  32221. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  32222. NULL, PAGE_READWRITE, nByte, NULL
  32223. );
  32224. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32225. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  32226. NULL, PAGE_READWRITE, 0, nByte, NULL
  32227. );
  32228. #elif defined(SQLITE_WIN32_HAS_ANSI)
  32229. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  32230. NULL, PAGE_READWRITE, 0, nByte, NULL
  32231. );
  32232. #endif
  32233. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  32234. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  32235. hMap ? "ok" : "failed"));
  32236. if( hMap ){
  32237. int iOffset = pShmNode->nRegion*szRegion;
  32238. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  32239. #if SQLITE_OS_WINRT
  32240. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  32241. iOffset - iOffsetShift, szRegion + iOffsetShift
  32242. );
  32243. #else
  32244. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  32245. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  32246. );
  32247. #endif
  32248. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  32249. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  32250. szRegion, pMap ? "ok" : "failed"));
  32251. }
  32252. if( !pMap ){
  32253. pShmNode->lastErrno = osGetLastError();
  32254. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  32255. "winShmMap3", pDbFd->zPath);
  32256. if( hMap ) osCloseHandle(hMap);
  32257. goto shmpage_out;
  32258. }
  32259. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  32260. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  32261. pShmNode->nRegion++;
  32262. }
  32263. }
  32264. shmpage_out:
  32265. if( pShmNode->nRegion>iRegion ){
  32266. int iOffset = iRegion*szRegion;
  32267. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  32268. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  32269. *pp = (void *)&p[iOffsetShift];
  32270. }else{
  32271. *pp = 0;
  32272. }
  32273. sqlite3_mutex_leave(pShmNode->mutex);
  32274. return rc;
  32275. }
  32276. #else
  32277. # define winShmMap 0
  32278. # define winShmLock 0
  32279. # define winShmBarrier 0
  32280. # define winShmUnmap 0
  32281. #endif /* #ifndef SQLITE_OMIT_WAL */
  32282. /*
  32283. ** Cleans up the mapped region of the specified file, if any.
  32284. */
  32285. #if SQLITE_MAX_MMAP_SIZE>0
  32286. static int winUnmapfile(winFile *pFile){
  32287. assert( pFile!=0 );
  32288. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  32289. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  32290. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  32291. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  32292. if( pFile->pMapRegion ){
  32293. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  32294. pFile->lastErrno = osGetLastError();
  32295. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  32296. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  32297. pFile->pMapRegion));
  32298. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  32299. "winUnmapfile1", pFile->zPath);
  32300. }
  32301. pFile->pMapRegion = 0;
  32302. pFile->mmapSize = 0;
  32303. pFile->mmapSizeActual = 0;
  32304. }
  32305. if( pFile->hMap!=NULL ){
  32306. if( !osCloseHandle(pFile->hMap) ){
  32307. pFile->lastErrno = osGetLastError();
  32308. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  32309. osGetCurrentProcessId(), pFile, pFile->hMap));
  32310. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  32311. "winUnmapfile2", pFile->zPath);
  32312. }
  32313. pFile->hMap = NULL;
  32314. }
  32315. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32316. osGetCurrentProcessId(), pFile));
  32317. return SQLITE_OK;
  32318. }
  32319. /*
  32320. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  32321. ** is already mapped, the existing mapping is replaced by the new). Or, if
  32322. ** there already exists a mapping for this file, and there are still
  32323. ** outstanding xFetch() references to it, this function is a no-op.
  32324. **
  32325. ** If parameter nByte is non-negative, then it is the requested size of
  32326. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  32327. ** requested size is the size of the file on disk. The actual size of the
  32328. ** created mapping is either the requested size or the value configured
  32329. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  32330. **
  32331. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  32332. ** recreated as a result of outstanding references) or an SQLite error
  32333. ** code otherwise.
  32334. */
  32335. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  32336. sqlite3_int64 nMap = nByte;
  32337. int rc;
  32338. assert( nMap>=0 || pFd->nFetchOut==0 );
  32339. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  32340. osGetCurrentProcessId(), pFd, nByte));
  32341. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  32342. if( nMap<0 ){
  32343. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  32344. if( rc ){
  32345. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  32346. osGetCurrentProcessId(), pFd));
  32347. return SQLITE_IOERR_FSTAT;
  32348. }
  32349. }
  32350. if( nMap>pFd->mmapSizeMax ){
  32351. nMap = pFd->mmapSizeMax;
  32352. }
  32353. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  32354. if( nMap==0 && pFd->mmapSize>0 ){
  32355. winUnmapfile(pFd);
  32356. }
  32357. if( nMap!=pFd->mmapSize ){
  32358. void *pNew = 0;
  32359. DWORD protect = PAGE_READONLY;
  32360. DWORD flags = FILE_MAP_READ;
  32361. winUnmapfile(pFd);
  32362. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  32363. protect = PAGE_READWRITE;
  32364. flags |= FILE_MAP_WRITE;
  32365. }
  32366. #if SQLITE_OS_WINRT
  32367. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  32368. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32369. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  32370. (DWORD)((nMap>>32) & 0xffffffff),
  32371. (DWORD)(nMap & 0xffffffff), NULL);
  32372. #elif defined(SQLITE_WIN32_HAS_ANSI)
  32373. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  32374. (DWORD)((nMap>>32) & 0xffffffff),
  32375. (DWORD)(nMap & 0xffffffff), NULL);
  32376. #endif
  32377. if( pFd->hMap==NULL ){
  32378. pFd->lastErrno = osGetLastError();
  32379. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  32380. "winMapfile1", pFd->zPath);
  32381. /* Log the error, but continue normal operation using xRead/xWrite */
  32382. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  32383. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  32384. return SQLITE_OK;
  32385. }
  32386. assert( (nMap % winSysInfo.dwPageSize)==0 );
  32387. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  32388. #if SQLITE_OS_WINRT
  32389. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  32390. #else
  32391. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  32392. #endif
  32393. if( pNew==NULL ){
  32394. osCloseHandle(pFd->hMap);
  32395. pFd->hMap = NULL;
  32396. pFd->lastErrno = osGetLastError();
  32397. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  32398. "winMapfile2", pFd->zPath);
  32399. /* Log the error, but continue normal operation using xRead/xWrite */
  32400. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  32401. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  32402. return SQLITE_OK;
  32403. }
  32404. pFd->pMapRegion = pNew;
  32405. pFd->mmapSize = nMap;
  32406. pFd->mmapSizeActual = nMap;
  32407. }
  32408. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32409. osGetCurrentProcessId(), pFd));
  32410. return SQLITE_OK;
  32411. }
  32412. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  32413. /*
  32414. ** If possible, return a pointer to a mapping of file fd starting at offset
  32415. ** iOff. The mapping must be valid for at least nAmt bytes.
  32416. **
  32417. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  32418. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  32419. ** Finally, if an error does occur, return an SQLite error code. The final
  32420. ** value of *pp is undefined in this case.
  32421. **
  32422. ** If this function does return a pointer, the caller must eventually
  32423. ** release the reference by calling winUnfetch().
  32424. */
  32425. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  32426. #if SQLITE_MAX_MMAP_SIZE>0
  32427. winFile *pFd = (winFile*)fd; /* The underlying database file */
  32428. #endif
  32429. *pp = 0;
  32430. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  32431. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  32432. #if SQLITE_MAX_MMAP_SIZE>0
  32433. if( pFd->mmapSizeMax>0 ){
  32434. if( pFd->pMapRegion==0 ){
  32435. int rc = winMapfile(pFd, -1);
  32436. if( rc!=SQLITE_OK ){
  32437. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  32438. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  32439. return rc;
  32440. }
  32441. }
  32442. if( pFd->mmapSize >= iOff+nAmt ){
  32443. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  32444. pFd->nFetchOut++;
  32445. }
  32446. }
  32447. #endif
  32448. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  32449. osGetCurrentProcessId(), fd, pp, *pp));
  32450. return SQLITE_OK;
  32451. }
  32452. /*
  32453. ** If the third argument is non-NULL, then this function releases a
  32454. ** reference obtained by an earlier call to winFetch(). The second
  32455. ** argument passed to this function must be the same as the corresponding
  32456. ** argument that was passed to the winFetch() invocation.
  32457. **
  32458. ** Or, if the third argument is NULL, then this function is being called
  32459. ** to inform the VFS layer that, according to POSIX, any existing mapping
  32460. ** may now be invalid and should be unmapped.
  32461. */
  32462. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  32463. #if SQLITE_MAX_MMAP_SIZE>0
  32464. winFile *pFd = (winFile*)fd; /* The underlying database file */
  32465. /* If p==0 (unmap the entire file) then there must be no outstanding
  32466. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  32467. ** then there must be at least one outstanding. */
  32468. assert( (p==0)==(pFd->nFetchOut==0) );
  32469. /* If p!=0, it must match the iOff value. */
  32470. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  32471. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  32472. osGetCurrentProcessId(), pFd, iOff, p));
  32473. if( p ){
  32474. pFd->nFetchOut--;
  32475. }else{
  32476. /* FIXME: If Windows truly always prevents truncating or deleting a
  32477. ** file while a mapping is held, then the following winUnmapfile() call
  32478. ** is unnecessary can can be omitted - potentially improving
  32479. ** performance. */
  32480. winUnmapfile(pFd);
  32481. }
  32482. assert( pFd->nFetchOut>=0 );
  32483. #endif
  32484. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32485. osGetCurrentProcessId(), fd));
  32486. return SQLITE_OK;
  32487. }
  32488. /*
  32489. ** Here ends the implementation of all sqlite3_file methods.
  32490. **
  32491. ********************** End sqlite3_file Methods *******************************
  32492. ******************************************************************************/
  32493. /*
  32494. ** This vector defines all the methods that can operate on an
  32495. ** sqlite3_file for win32.
  32496. */
  32497. static const sqlite3_io_methods winIoMethod = {
  32498. 3, /* iVersion */
  32499. winClose, /* xClose */
  32500. winRead, /* xRead */
  32501. winWrite, /* xWrite */
  32502. winTruncate, /* xTruncate */
  32503. winSync, /* xSync */
  32504. winFileSize, /* xFileSize */
  32505. winLock, /* xLock */
  32506. winUnlock, /* xUnlock */
  32507. winCheckReservedLock, /* xCheckReservedLock */
  32508. winFileControl, /* xFileControl */
  32509. winSectorSize, /* xSectorSize */
  32510. winDeviceCharacteristics, /* xDeviceCharacteristics */
  32511. winShmMap, /* xShmMap */
  32512. winShmLock, /* xShmLock */
  32513. winShmBarrier, /* xShmBarrier */
  32514. winShmUnmap, /* xShmUnmap */
  32515. winFetch, /* xFetch */
  32516. winUnfetch /* xUnfetch */
  32517. };
  32518. /****************************************************************************
  32519. **************************** sqlite3_vfs methods ****************************
  32520. **
  32521. ** This division contains the implementation of methods on the
  32522. ** sqlite3_vfs object.
  32523. */
  32524. #if 0
  32525. /*
  32526. ** Convert a filename from whatever the underlying operating system
  32527. ** supports for filenames into UTF-8. Space to hold the result is
  32528. ** obtained from malloc and must be freed by the calling function.
  32529. */
  32530. static char *winConvertToUtf8Filename(const void *zFilename){
  32531. char *zConverted = 0;
  32532. if( osIsNT() ){
  32533. zConverted = winUnicodeToUtf8(zFilename);
  32534. }
  32535. #ifdef SQLITE_WIN32_HAS_ANSI
  32536. else{
  32537. zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
  32538. }
  32539. #endif
  32540. /* caller will handle out of memory */
  32541. return zConverted;
  32542. }
  32543. #endif
  32544. /*
  32545. ** Convert a UTF-8 filename into whatever form the underlying
  32546. ** operating system wants filenames in. Space to hold the result
  32547. ** is obtained from malloc and must be freed by the calling
  32548. ** function.
  32549. */
  32550. static void *winConvertFromUtf8Filename(const char *zFilename){
  32551. void *zConverted = 0;
  32552. if( osIsNT() ){
  32553. zConverted = winUtf8ToUnicode(zFilename);
  32554. }
  32555. #ifdef SQLITE_WIN32_HAS_ANSI
  32556. else{
  32557. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  32558. }
  32559. #endif
  32560. /* caller will handle out of memory */
  32561. return zConverted;
  32562. }
  32563. /*
  32564. ** This function returns non-zero if the specified UTF-8 string buffer
  32565. ** ends with a directory separator character.
  32566. */
  32567. static int winEndsInDirSep(char *zBuf){
  32568. if( zBuf ){
  32569. int nLen = sqlite3Strlen30(zBuf);
  32570. return nLen>0 && winIsDirSep(zBuf[nLen-1]);
  32571. }
  32572. return 0;
  32573. }
  32574. /*
  32575. ** Create a temporary file name and store the resulting pointer into pzBuf.
  32576. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  32577. */
  32578. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  32579. static char zChars[] =
  32580. "abcdefghijklmnopqrstuvwxyz"
  32581. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  32582. "0123456789";
  32583. size_t i, j;
  32584. int nBuf, nLen;
  32585. char *zBuf;
  32586. /* It's odd to simulate an io-error here, but really this is just
  32587. ** using the io-error infrastructure to test that SQLite handles this
  32588. ** function failing.
  32589. */
  32590. SimulateIOError( return SQLITE_IOERR );
  32591. /* Allocate a temporary buffer to store the fully qualified file
  32592. ** name for the temporary file. If this fails, we cannot continue.
  32593. */
  32594. nBuf = pVfs->mxPathname;
  32595. zBuf = sqlite3MallocZero( nBuf+2 );
  32596. if( !zBuf ){
  32597. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32598. return SQLITE_IOERR_NOMEM;
  32599. }
  32600. /* Figure out the effective temporary directory. First, check if one
  32601. ** has been explicitly set by the application; otherwise, use the one
  32602. ** configured by the operating system.
  32603. */
  32604. assert( nBuf>30 );
  32605. if( sqlite3_temp_directory ){
  32606. sqlite3_snprintf(nBuf-30, zBuf, "%s%s", sqlite3_temp_directory,
  32607. winEndsInDirSep(sqlite3_temp_directory) ? "" :
  32608. winGetDirDep());
  32609. }
  32610. #if defined(__CYGWIN__)
  32611. else{
  32612. static const char *azDirs[] = {
  32613. 0, /* getenv("SQLITE_TMPDIR") */
  32614. 0, /* getenv("TMPDIR") */
  32615. 0, /* getenv("TMP") */
  32616. 0, /* getenv("TEMP") */
  32617. 0, /* getenv("USERPROFILE") */
  32618. "/var/tmp",
  32619. "/usr/tmp",
  32620. "/tmp",
  32621. ".",
  32622. 0 /* List terminator */
  32623. };
  32624. unsigned int i;
  32625. const char *zDir = 0;
  32626. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  32627. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  32628. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  32629. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  32630. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  32631. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  32632. void *zConverted;
  32633. if( zDir==0 ) continue;
  32634. /* If the path starts with a drive letter followed by the colon
  32635. ** character, assume it is already a native Win32 path; otherwise,
  32636. ** it must be converted to a native Win32 path prior via the Cygwin
  32637. ** API prior to using it.
  32638. */
  32639. if( winIsDriveLetterAndColon(zDir) ){
  32640. zConverted = winConvertFromUtf8Filename(zDir);
  32641. if( !zConverted ){
  32642. sqlite3_free(zBuf);
  32643. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32644. return SQLITE_IOERR_NOMEM;
  32645. }
  32646. if( winIsDir(zConverted) ){
  32647. sqlite3_snprintf(nBuf-30, zBuf, "%s", zDir);
  32648. sqlite3_free(zConverted);
  32649. break;
  32650. }
  32651. sqlite3_free(zConverted);
  32652. }else{
  32653. zConverted = sqlite3MallocZero( nBuf+1 );
  32654. if( !zConverted ){
  32655. sqlite3_free(zBuf);
  32656. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32657. return SQLITE_IOERR_NOMEM;
  32658. }
  32659. if( cygwin_conv_path(
  32660. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  32661. zConverted, nBuf+1)<0 ){
  32662. sqlite3_free(zConverted);
  32663. sqlite3_free(zBuf);
  32664. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  32665. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  32666. "winGetTempname1", zDir);
  32667. }
  32668. if( winIsDir(zConverted) ){
  32669. /* At this point, we know the candidate directory exists and should
  32670. ** be used. However, we may need to convert the string containing
  32671. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  32672. */
  32673. if( osIsNT() ){
  32674. char *zUtf8 = winUnicodeToUtf8(zConverted);
  32675. if( !zUtf8 ){
  32676. sqlite3_free(zConverted);
  32677. sqlite3_free(zBuf);
  32678. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32679. return SQLITE_IOERR_NOMEM;
  32680. }
  32681. sqlite3_snprintf(nBuf-30, zBuf, "%s", zUtf8);
  32682. sqlite3_free(zUtf8);
  32683. sqlite3_free(zConverted);
  32684. break;
  32685. }else{
  32686. sqlite3_snprintf(nBuf-30, zBuf, "%s", zConverted);
  32687. sqlite3_free(zConverted);
  32688. break;
  32689. }
  32690. }
  32691. sqlite3_free(zConverted);
  32692. }
  32693. }
  32694. }
  32695. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  32696. else if( osIsNT() ){
  32697. char *zMulti;
  32698. LPWSTR zWidePath = sqlite3MallocZero( nBuf*sizeof(WCHAR) );
  32699. if( !zWidePath ){
  32700. sqlite3_free(zBuf);
  32701. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32702. return SQLITE_IOERR_NOMEM;
  32703. }
  32704. if( osGetTempPathW(nBuf, zWidePath)==0 ){
  32705. sqlite3_free(zWidePath);
  32706. sqlite3_free(zBuf);
  32707. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  32708. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  32709. "winGetTempname1", 0);
  32710. }
  32711. zMulti = winUnicodeToUtf8(zWidePath);
  32712. if( zMulti ){
  32713. sqlite3_snprintf(nBuf-30, zBuf, "%s", zMulti);
  32714. sqlite3_free(zMulti);
  32715. sqlite3_free(zWidePath);
  32716. }else{
  32717. sqlite3_free(zWidePath);
  32718. sqlite3_free(zBuf);
  32719. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32720. return SQLITE_IOERR_NOMEM;
  32721. }
  32722. }
  32723. #ifdef SQLITE_WIN32_HAS_ANSI
  32724. else{
  32725. char *zUtf8;
  32726. char *zMbcsPath = sqlite3MallocZero( nBuf );
  32727. if( !zMbcsPath ){
  32728. sqlite3_free(zBuf);
  32729. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32730. return SQLITE_IOERR_NOMEM;
  32731. }
  32732. if( osGetTempPathA(nBuf, zMbcsPath)==0 ){
  32733. sqlite3_free(zBuf);
  32734. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  32735. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  32736. "winGetTempname2", 0);
  32737. }
  32738. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  32739. if( zUtf8 ){
  32740. sqlite3_snprintf(nBuf-30, zBuf, "%s", zUtf8);
  32741. sqlite3_free(zUtf8);
  32742. }else{
  32743. sqlite3_free(zBuf);
  32744. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32745. return SQLITE_IOERR_NOMEM;
  32746. }
  32747. }
  32748. #endif /* SQLITE_WIN32_HAS_ANSI */
  32749. #endif /* !SQLITE_OS_WINRT */
  32750. /* Check that the output buffer is large enough for the temporary file
  32751. ** name. If it is not, return SQLITE_ERROR.
  32752. */
  32753. nLen = sqlite3Strlen30(zBuf);
  32754. if( (nLen + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
  32755. sqlite3_free(zBuf);
  32756. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  32757. return winLogError(SQLITE_ERROR, 0, "winGetTempname3", 0);
  32758. }
  32759. sqlite3_snprintf(nBuf-18-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  32760. j = sqlite3Strlen30(zBuf);
  32761. sqlite3_randomness(15, &zBuf[j]);
  32762. for(i=0; i<15; i++, j++){
  32763. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  32764. }
  32765. zBuf[j] = 0;
  32766. zBuf[j+1] = 0;
  32767. *pzBuf = zBuf;
  32768. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  32769. return SQLITE_OK;
  32770. }
  32771. /*
  32772. ** Return TRUE if the named file is really a directory. Return false if
  32773. ** it is something other than a directory, or if there is any kind of memory
  32774. ** allocation failure.
  32775. */
  32776. static int winIsDir(const void *zConverted){
  32777. DWORD attr;
  32778. int rc = 0;
  32779. DWORD lastErrno;
  32780. if( osIsNT() ){
  32781. int cnt = 0;
  32782. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  32783. memset(&sAttrData, 0, sizeof(sAttrData));
  32784. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  32785. GetFileExInfoStandard,
  32786. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  32787. if( !rc ){
  32788. return 0; /* Invalid name? */
  32789. }
  32790. attr = sAttrData.dwFileAttributes;
  32791. #if SQLITE_OS_WINCE==0
  32792. }else{
  32793. attr = osGetFileAttributesA((char*)zConverted);
  32794. #endif
  32795. }
  32796. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  32797. }
  32798. /*
  32799. ** Open a file.
  32800. */
  32801. static int winOpen(
  32802. sqlite3_vfs *pVfs, /* Used to get maximum path name length */
  32803. const char *zName, /* Name of the file (UTF-8) */
  32804. sqlite3_file *id, /* Write the SQLite file handle here */
  32805. int flags, /* Open mode flags */
  32806. int *pOutFlags /* Status return flags */
  32807. ){
  32808. HANDLE h;
  32809. DWORD lastErrno;
  32810. DWORD dwDesiredAccess;
  32811. DWORD dwShareMode;
  32812. DWORD dwCreationDisposition;
  32813. DWORD dwFlagsAndAttributes = 0;
  32814. #if SQLITE_OS_WINCE
  32815. int isTemp = 0;
  32816. #endif
  32817. winFile *pFile = (winFile*)id;
  32818. void *zConverted; /* Filename in OS encoding */
  32819. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  32820. int cnt = 0;
  32821. /* If argument zPath is a NULL pointer, this function is required to open
  32822. ** a temporary file. Use this buffer to store the file name in.
  32823. */
  32824. char *zTmpname = 0; /* For temporary filename, if necessary. */
  32825. int rc = SQLITE_OK; /* Function Return Code */
  32826. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  32827. int eType = flags&0xFFFFFF00; /* Type of file to open */
  32828. #endif
  32829. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  32830. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  32831. int isCreate = (flags & SQLITE_OPEN_CREATE);
  32832. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  32833. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  32834. #ifndef NDEBUG
  32835. int isOpenJournal = (isCreate && (
  32836. eType==SQLITE_OPEN_MASTER_JOURNAL
  32837. || eType==SQLITE_OPEN_MAIN_JOURNAL
  32838. || eType==SQLITE_OPEN_WAL
  32839. ));
  32840. #endif
  32841. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  32842. zUtf8Name, id, flags, pOutFlags));
  32843. /* Check the following statements are true:
  32844. **
  32845. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  32846. ** (b) if CREATE is set, then READWRITE must also be set, and
  32847. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  32848. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  32849. */
  32850. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  32851. assert(isCreate==0 || isReadWrite);
  32852. assert(isExclusive==0 || isCreate);
  32853. assert(isDelete==0 || isCreate);
  32854. /* The main DB, main journal, WAL file and master journal are never
  32855. ** automatically deleted. Nor are they ever temporary files. */
  32856. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  32857. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  32858. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  32859. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  32860. /* Assert that the upper layer has set one of the "file-type" flags. */
  32861. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  32862. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  32863. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  32864. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  32865. );
  32866. assert( pFile!=0 );
  32867. memset(pFile, 0, sizeof(winFile));
  32868. pFile->h = INVALID_HANDLE_VALUE;
  32869. #if SQLITE_OS_WINRT
  32870. if( !zUtf8Name && !sqlite3_temp_directory ){
  32871. sqlite3_log(SQLITE_ERROR,
  32872. "sqlite3_temp_directory variable should be set for WinRT");
  32873. }
  32874. #endif
  32875. /* If the second argument to this function is NULL, generate a
  32876. ** temporary file name to use
  32877. */
  32878. if( !zUtf8Name ){
  32879. assert( isDelete && !isOpenJournal );
  32880. rc = winGetTempname(pVfs, &zTmpname);
  32881. if( rc!=SQLITE_OK ){
  32882. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  32883. return rc;
  32884. }
  32885. zUtf8Name = zTmpname;
  32886. }
  32887. /* Database filenames are double-zero terminated if they are not
  32888. ** URIs with parameters. Hence, they can always be passed into
  32889. ** sqlite3_uri_parameter().
  32890. */
  32891. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  32892. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  32893. /* Convert the filename to the system encoding. */
  32894. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  32895. if( zConverted==0 ){
  32896. sqlite3_free(zTmpname);
  32897. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  32898. return SQLITE_IOERR_NOMEM;
  32899. }
  32900. if( winIsDir(zConverted) ){
  32901. sqlite3_free(zConverted);
  32902. sqlite3_free(zTmpname);
  32903. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  32904. return SQLITE_CANTOPEN_ISDIR;
  32905. }
  32906. if( isReadWrite ){
  32907. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  32908. }else{
  32909. dwDesiredAccess = GENERIC_READ;
  32910. }
  32911. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  32912. ** created. SQLite doesn't use it to indicate "exclusive access"
  32913. ** as it is usually understood.
  32914. */
  32915. if( isExclusive ){
  32916. /* Creates a new file, only if it does not already exist. */
  32917. /* If the file exists, it fails. */
  32918. dwCreationDisposition = CREATE_NEW;
  32919. }else if( isCreate ){
  32920. /* Open existing file, or create if it doesn't exist */
  32921. dwCreationDisposition = OPEN_ALWAYS;
  32922. }else{
  32923. /* Opens a file, only if it exists. */
  32924. dwCreationDisposition = OPEN_EXISTING;
  32925. }
  32926. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  32927. if( isDelete ){
  32928. #if SQLITE_OS_WINCE
  32929. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  32930. isTemp = 1;
  32931. #else
  32932. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  32933. | FILE_ATTRIBUTE_HIDDEN
  32934. | FILE_FLAG_DELETE_ON_CLOSE;
  32935. #endif
  32936. }else{
  32937. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  32938. }
  32939. /* Reports from the internet are that performance is always
  32940. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  32941. #if SQLITE_OS_WINCE
  32942. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  32943. #endif
  32944. if( osIsNT() ){
  32945. #if SQLITE_OS_WINRT
  32946. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  32947. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  32948. extendedParameters.dwFileAttributes =
  32949. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  32950. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  32951. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  32952. extendedParameters.lpSecurityAttributes = NULL;
  32953. extendedParameters.hTemplateFile = NULL;
  32954. while( (h = osCreateFile2((LPCWSTR)zConverted,
  32955. dwDesiredAccess,
  32956. dwShareMode,
  32957. dwCreationDisposition,
  32958. &extendedParameters))==INVALID_HANDLE_VALUE &&
  32959. winRetryIoerr(&cnt, &lastErrno) ){
  32960. /* Noop */
  32961. }
  32962. #else
  32963. while( (h = osCreateFileW((LPCWSTR)zConverted,
  32964. dwDesiredAccess,
  32965. dwShareMode, NULL,
  32966. dwCreationDisposition,
  32967. dwFlagsAndAttributes,
  32968. NULL))==INVALID_HANDLE_VALUE &&
  32969. winRetryIoerr(&cnt, &lastErrno) ){
  32970. /* Noop */
  32971. }
  32972. #endif
  32973. }
  32974. #ifdef SQLITE_WIN32_HAS_ANSI
  32975. else{
  32976. while( (h = osCreateFileA((LPCSTR)zConverted,
  32977. dwDesiredAccess,
  32978. dwShareMode, NULL,
  32979. dwCreationDisposition,
  32980. dwFlagsAndAttributes,
  32981. NULL))==INVALID_HANDLE_VALUE &&
  32982. winRetryIoerr(&cnt, &lastErrno) ){
  32983. /* Noop */
  32984. }
  32985. }
  32986. #endif
  32987. winLogIoerr(cnt);
  32988. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  32989. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  32990. if( h==INVALID_HANDLE_VALUE ){
  32991. pFile->lastErrno = lastErrno;
  32992. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  32993. sqlite3_free(zConverted);
  32994. sqlite3_free(zTmpname);
  32995. if( isReadWrite && !isExclusive ){
  32996. return winOpen(pVfs, zName, id,
  32997. ((flags|SQLITE_OPEN_READONLY) &
  32998. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  32999. pOutFlags);
  33000. }else{
  33001. return SQLITE_CANTOPEN_BKPT;
  33002. }
  33003. }
  33004. if( pOutFlags ){
  33005. if( isReadWrite ){
  33006. *pOutFlags = SQLITE_OPEN_READWRITE;
  33007. }else{
  33008. *pOutFlags = SQLITE_OPEN_READONLY;
  33009. }
  33010. }
  33011. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  33012. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  33013. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  33014. #if SQLITE_OS_WINCE
  33015. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  33016. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  33017. ){
  33018. osCloseHandle(h);
  33019. sqlite3_free(zConverted);
  33020. sqlite3_free(zTmpname);
  33021. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  33022. return rc;
  33023. }
  33024. if( isTemp ){
  33025. pFile->zDeleteOnClose = zConverted;
  33026. }else
  33027. #endif
  33028. {
  33029. sqlite3_free(zConverted);
  33030. }
  33031. sqlite3_free(zTmpname);
  33032. pFile->pMethod = &winIoMethod;
  33033. pFile->pVfs = pVfs;
  33034. pFile->h = h;
  33035. if( isReadonly ){
  33036. pFile->ctrlFlags |= WINFILE_RDONLY;
  33037. }
  33038. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  33039. pFile->ctrlFlags |= WINFILE_PSOW;
  33040. }
  33041. pFile->lastErrno = NO_ERROR;
  33042. pFile->zPath = zName;
  33043. #if SQLITE_MAX_MMAP_SIZE>0
  33044. pFile->hMap = NULL;
  33045. pFile->pMapRegion = 0;
  33046. pFile->mmapSize = 0;
  33047. pFile->mmapSizeActual = 0;
  33048. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  33049. #endif
  33050. OpenCounter(+1);
  33051. return rc;
  33052. }
  33053. /*
  33054. ** Delete the named file.
  33055. **
  33056. ** Note that Windows does not allow a file to be deleted if some other
  33057. ** process has it open. Sometimes a virus scanner or indexing program
  33058. ** will open a journal file shortly after it is created in order to do
  33059. ** whatever it does. While this other process is holding the
  33060. ** file open, we will be unable to delete it. To work around this
  33061. ** problem, we delay 100 milliseconds and try to delete again. Up
  33062. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  33063. ** up and returning an error.
  33064. */
  33065. static int winDelete(
  33066. sqlite3_vfs *pVfs, /* Not used on win32 */
  33067. const char *zFilename, /* Name of file to delete */
  33068. int syncDir /* Not used on win32 */
  33069. ){
  33070. int cnt = 0;
  33071. int rc;
  33072. DWORD attr;
  33073. DWORD lastErrno;
  33074. void *zConverted;
  33075. UNUSED_PARAMETER(pVfs);
  33076. UNUSED_PARAMETER(syncDir);
  33077. SimulateIOError(return SQLITE_IOERR_DELETE);
  33078. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  33079. zConverted = winConvertFromUtf8Filename(zFilename);
  33080. if( zConverted==0 ){
  33081. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  33082. return SQLITE_IOERR_NOMEM;
  33083. }
  33084. if( osIsNT() ){
  33085. do {
  33086. #if SQLITE_OS_WINRT
  33087. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  33088. memset(&sAttrData, 0, sizeof(sAttrData));
  33089. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  33090. &sAttrData) ){
  33091. attr = sAttrData.dwFileAttributes;
  33092. }else{
  33093. lastErrno = osGetLastError();
  33094. if( lastErrno==ERROR_FILE_NOT_FOUND
  33095. || lastErrno==ERROR_PATH_NOT_FOUND ){
  33096. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  33097. }else{
  33098. rc = SQLITE_ERROR;
  33099. }
  33100. break;
  33101. }
  33102. #else
  33103. attr = osGetFileAttributesW(zConverted);
  33104. #endif
  33105. if ( attr==INVALID_FILE_ATTRIBUTES ){
  33106. lastErrno = osGetLastError();
  33107. if( lastErrno==ERROR_FILE_NOT_FOUND
  33108. || lastErrno==ERROR_PATH_NOT_FOUND ){
  33109. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  33110. }else{
  33111. rc = SQLITE_ERROR;
  33112. }
  33113. break;
  33114. }
  33115. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  33116. rc = SQLITE_ERROR; /* Files only. */
  33117. break;
  33118. }
  33119. if ( osDeleteFileW(zConverted) ){
  33120. rc = SQLITE_OK; /* Deleted OK. */
  33121. break;
  33122. }
  33123. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  33124. rc = SQLITE_ERROR; /* No more retries. */
  33125. break;
  33126. }
  33127. } while(1);
  33128. }
  33129. #ifdef SQLITE_WIN32_HAS_ANSI
  33130. else{
  33131. do {
  33132. attr = osGetFileAttributesA(zConverted);
  33133. if ( attr==INVALID_FILE_ATTRIBUTES ){
  33134. lastErrno = osGetLastError();
  33135. if( lastErrno==ERROR_FILE_NOT_FOUND
  33136. || lastErrno==ERROR_PATH_NOT_FOUND ){
  33137. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  33138. }else{
  33139. rc = SQLITE_ERROR;
  33140. }
  33141. break;
  33142. }
  33143. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  33144. rc = SQLITE_ERROR; /* Files only. */
  33145. break;
  33146. }
  33147. if ( osDeleteFileA(zConverted) ){
  33148. rc = SQLITE_OK; /* Deleted OK. */
  33149. break;
  33150. }
  33151. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  33152. rc = SQLITE_ERROR; /* No more retries. */
  33153. break;
  33154. }
  33155. } while(1);
  33156. }
  33157. #endif
  33158. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  33159. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  33160. }else{
  33161. winLogIoerr(cnt);
  33162. }
  33163. sqlite3_free(zConverted);
  33164. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  33165. return rc;
  33166. }
  33167. /*
  33168. ** Check the existence and status of a file.
  33169. */
  33170. static int winAccess(
  33171. sqlite3_vfs *pVfs, /* Not used on win32 */
  33172. const char *zFilename, /* Name of file to check */
  33173. int flags, /* Type of test to make on this file */
  33174. int *pResOut /* OUT: Result */
  33175. ){
  33176. DWORD attr;
  33177. int rc = 0;
  33178. DWORD lastErrno;
  33179. void *zConverted;
  33180. UNUSED_PARAMETER(pVfs);
  33181. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  33182. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  33183. zFilename, flags, pResOut));
  33184. zConverted = winConvertFromUtf8Filename(zFilename);
  33185. if( zConverted==0 ){
  33186. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  33187. return SQLITE_IOERR_NOMEM;
  33188. }
  33189. if( osIsNT() ){
  33190. int cnt = 0;
  33191. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  33192. memset(&sAttrData, 0, sizeof(sAttrData));
  33193. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  33194. GetFileExInfoStandard,
  33195. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  33196. if( rc ){
  33197. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  33198. ** as if it does not exist.
  33199. */
  33200. if( flags==SQLITE_ACCESS_EXISTS
  33201. && sAttrData.nFileSizeHigh==0
  33202. && sAttrData.nFileSizeLow==0 ){
  33203. attr = INVALID_FILE_ATTRIBUTES;
  33204. }else{
  33205. attr = sAttrData.dwFileAttributes;
  33206. }
  33207. }else{
  33208. winLogIoerr(cnt);
  33209. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  33210. sqlite3_free(zConverted);
  33211. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  33212. zFilename);
  33213. }else{
  33214. attr = INVALID_FILE_ATTRIBUTES;
  33215. }
  33216. }
  33217. }
  33218. #ifdef SQLITE_WIN32_HAS_ANSI
  33219. else{
  33220. attr = osGetFileAttributesA((char*)zConverted);
  33221. }
  33222. #endif
  33223. sqlite3_free(zConverted);
  33224. switch( flags ){
  33225. case SQLITE_ACCESS_READ:
  33226. case SQLITE_ACCESS_EXISTS:
  33227. rc = attr!=INVALID_FILE_ATTRIBUTES;
  33228. break;
  33229. case SQLITE_ACCESS_READWRITE:
  33230. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  33231. (attr & FILE_ATTRIBUTE_READONLY)==0;
  33232. break;
  33233. default:
  33234. assert(!"Invalid flags argument");
  33235. }
  33236. *pResOut = rc;
  33237. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  33238. zFilename, pResOut, *pResOut));
  33239. return SQLITE_OK;
  33240. }
  33241. /*
  33242. ** Returns non-zero if the specified path name starts with a drive letter
  33243. ** followed by a colon character.
  33244. */
  33245. static BOOL winIsDriveLetterAndColon(
  33246. const char *zPathname
  33247. ){
  33248. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  33249. }
  33250. /*
  33251. ** Returns non-zero if the specified path name should be used verbatim. If
  33252. ** non-zero is returned from this function, the calling function must simply
  33253. ** use the provided path name verbatim -OR- resolve it into a full path name
  33254. ** using the GetFullPathName Win32 API function (if available).
  33255. */
  33256. static BOOL winIsVerbatimPathname(
  33257. const char *zPathname
  33258. ){
  33259. /*
  33260. ** If the path name starts with a forward slash or a backslash, it is either
  33261. ** a legal UNC name, a volume relative path, or an absolute path name in the
  33262. ** "Unix" format on Windows. There is no easy way to differentiate between
  33263. ** the final two cases; therefore, we return the safer return value of TRUE
  33264. ** so that callers of this function will simply use it verbatim.
  33265. */
  33266. if ( winIsDirSep(zPathname[0]) ){
  33267. return TRUE;
  33268. }
  33269. /*
  33270. ** If the path name starts with a letter and a colon it is either a volume
  33271. ** relative path or an absolute path. Callers of this function must not
  33272. ** attempt to treat it as a relative path name (i.e. they should simply use
  33273. ** it verbatim).
  33274. */
  33275. if ( winIsDriveLetterAndColon(zPathname) ){
  33276. return TRUE;
  33277. }
  33278. /*
  33279. ** If we get to this point, the path name should almost certainly be a purely
  33280. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  33281. */
  33282. return FALSE;
  33283. }
  33284. /*
  33285. ** Turn a relative pathname into a full pathname. Write the full
  33286. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  33287. ** bytes in size.
  33288. */
  33289. static int winFullPathname(
  33290. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  33291. const char *zRelative, /* Possibly relative input path */
  33292. int nFull, /* Size of output buffer in bytes */
  33293. char *zFull /* Output buffer */
  33294. ){
  33295. #if defined(__CYGWIN__)
  33296. SimulateIOError( return SQLITE_ERROR );
  33297. UNUSED_PARAMETER(nFull);
  33298. assert( nFull>=pVfs->mxPathname );
  33299. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  33300. /*
  33301. ** NOTE: We are dealing with a relative path name and the data
  33302. ** directory has been set. Therefore, use it as the basis
  33303. ** for converting the relative path name to an absolute
  33304. ** one by prepending the data directory and a slash.
  33305. */
  33306. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  33307. if( !zOut ){
  33308. return SQLITE_IOERR_NOMEM;
  33309. }
  33310. if( cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
  33311. pVfs->mxPathname+1)<0 ){
  33312. sqlite3_free(zOut);
  33313. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  33314. "winFullPathname1", zRelative);
  33315. }
  33316. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  33317. sqlite3_data_directory, winGetDirDep(), zOut);
  33318. sqlite3_free(zOut);
  33319. }else{
  33320. if( cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull)<0 ){
  33321. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  33322. "winFullPathname2", zRelative);
  33323. }
  33324. }
  33325. return SQLITE_OK;
  33326. #endif
  33327. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  33328. SimulateIOError( return SQLITE_ERROR );
  33329. /* WinCE has no concept of a relative pathname, or so I am told. */
  33330. /* WinRT has no way to convert a relative path to an absolute one. */
  33331. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  33332. /*
  33333. ** NOTE: We are dealing with a relative path name and the data
  33334. ** directory has been set. Therefore, use it as the basis
  33335. ** for converting the relative path name to an absolute
  33336. ** one by prepending the data directory and a backslash.
  33337. */
  33338. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  33339. sqlite3_data_directory, winGetDirDep(), zRelative);
  33340. }else{
  33341. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  33342. }
  33343. return SQLITE_OK;
  33344. #endif
  33345. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  33346. DWORD nByte;
  33347. void *zConverted;
  33348. char *zOut;
  33349. /* If this path name begins with "/X:", where "X" is any alphabetic
  33350. ** character, discard the initial "/" from the pathname.
  33351. */
  33352. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  33353. zRelative++;
  33354. }
  33355. /* It's odd to simulate an io-error here, but really this is just
  33356. ** using the io-error infrastructure to test that SQLite handles this
  33357. ** function failing. This function could fail if, for example, the
  33358. ** current working directory has been unlinked.
  33359. */
  33360. SimulateIOError( return SQLITE_ERROR );
  33361. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  33362. /*
  33363. ** NOTE: We are dealing with a relative path name and the data
  33364. ** directory has been set. Therefore, use it as the basis
  33365. ** for converting the relative path name to an absolute
  33366. ** one by prepending the data directory and a backslash.
  33367. */
  33368. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  33369. sqlite3_data_directory, winGetDirDep(), zRelative);
  33370. return SQLITE_OK;
  33371. }
  33372. zConverted = winConvertFromUtf8Filename(zRelative);
  33373. if( zConverted==0 ){
  33374. return SQLITE_IOERR_NOMEM;
  33375. }
  33376. if( osIsNT() ){
  33377. LPWSTR zTemp;
  33378. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  33379. if( nByte==0 ){
  33380. sqlite3_free(zConverted);
  33381. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33382. "winFullPathname1", zRelative);
  33383. }
  33384. nByte += 3;
  33385. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  33386. if( zTemp==0 ){
  33387. sqlite3_free(zConverted);
  33388. return SQLITE_IOERR_NOMEM;
  33389. }
  33390. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  33391. if( nByte==0 ){
  33392. sqlite3_free(zConverted);
  33393. sqlite3_free(zTemp);
  33394. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33395. "winFullPathname2", zRelative);
  33396. }
  33397. sqlite3_free(zConverted);
  33398. zOut = winUnicodeToUtf8(zTemp);
  33399. sqlite3_free(zTemp);
  33400. }
  33401. #ifdef SQLITE_WIN32_HAS_ANSI
  33402. else{
  33403. char *zTemp;
  33404. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  33405. if( nByte==0 ){
  33406. sqlite3_free(zConverted);
  33407. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33408. "winFullPathname3", zRelative);
  33409. }
  33410. nByte += 3;
  33411. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  33412. if( zTemp==0 ){
  33413. sqlite3_free(zConverted);
  33414. return SQLITE_IOERR_NOMEM;
  33415. }
  33416. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  33417. if( nByte==0 ){
  33418. sqlite3_free(zConverted);
  33419. sqlite3_free(zTemp);
  33420. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33421. "winFullPathname4", zRelative);
  33422. }
  33423. sqlite3_free(zConverted);
  33424. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  33425. sqlite3_free(zTemp);
  33426. }
  33427. #endif
  33428. if( zOut ){
  33429. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  33430. sqlite3_free(zOut);
  33431. return SQLITE_OK;
  33432. }else{
  33433. return SQLITE_IOERR_NOMEM;
  33434. }
  33435. #endif
  33436. }
  33437. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  33438. /*
  33439. ** Interfaces for opening a shared library, finding entry points
  33440. ** within the shared library, and closing the shared library.
  33441. */
  33442. /*
  33443. ** Interfaces for opening a shared library, finding entry points
  33444. ** within the shared library, and closing the shared library.
  33445. */
  33446. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  33447. HANDLE h;
  33448. void *zConverted = winConvertFromUtf8Filename(zFilename);
  33449. UNUSED_PARAMETER(pVfs);
  33450. if( zConverted==0 ){
  33451. return 0;
  33452. }
  33453. if( osIsNT() ){
  33454. #if SQLITE_OS_WINRT
  33455. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  33456. #else
  33457. h = osLoadLibraryW((LPCWSTR)zConverted);
  33458. #endif
  33459. }
  33460. #ifdef SQLITE_WIN32_HAS_ANSI
  33461. else{
  33462. h = osLoadLibraryA((char*)zConverted);
  33463. }
  33464. #endif
  33465. sqlite3_free(zConverted);
  33466. return (void*)h;
  33467. }
  33468. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  33469. UNUSED_PARAMETER(pVfs);
  33470. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  33471. }
  33472. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  33473. UNUSED_PARAMETER(pVfs);
  33474. return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
  33475. }
  33476. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  33477. UNUSED_PARAMETER(pVfs);
  33478. osFreeLibrary((HANDLE)pHandle);
  33479. }
  33480. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  33481. #define winDlOpen 0
  33482. #define winDlError 0
  33483. #define winDlSym 0
  33484. #define winDlClose 0
  33485. #endif
  33486. /*
  33487. ** Write up to nBuf bytes of randomness into zBuf.
  33488. */
  33489. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33490. int n = 0;
  33491. UNUSED_PARAMETER(pVfs);
  33492. #if defined(SQLITE_TEST)
  33493. n = nBuf;
  33494. memset(zBuf, 0, nBuf);
  33495. #else
  33496. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  33497. SYSTEMTIME x;
  33498. osGetSystemTime(&x);
  33499. memcpy(&zBuf[n], &x, sizeof(x));
  33500. n += sizeof(x);
  33501. }
  33502. if( sizeof(DWORD)<=nBuf-n ){
  33503. DWORD pid = osGetCurrentProcessId();
  33504. memcpy(&zBuf[n], &pid, sizeof(pid));
  33505. n += sizeof(pid);
  33506. }
  33507. #if SQLITE_OS_WINRT
  33508. if( sizeof(ULONGLONG)<=nBuf-n ){
  33509. ULONGLONG cnt = osGetTickCount64();
  33510. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  33511. n += sizeof(cnt);
  33512. }
  33513. #else
  33514. if( sizeof(DWORD)<=nBuf-n ){
  33515. DWORD cnt = osGetTickCount();
  33516. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  33517. n += sizeof(cnt);
  33518. }
  33519. #endif
  33520. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  33521. LARGE_INTEGER i;
  33522. osQueryPerformanceCounter(&i);
  33523. memcpy(&zBuf[n], &i, sizeof(i));
  33524. n += sizeof(i);
  33525. }
  33526. #endif
  33527. return n;
  33528. }
  33529. /*
  33530. ** Sleep for a little while. Return the amount of time slept.
  33531. */
  33532. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  33533. sqlite3_win32_sleep((microsec+999)/1000);
  33534. UNUSED_PARAMETER(pVfs);
  33535. return ((microsec+999)/1000)*1000;
  33536. }
  33537. /*
  33538. ** The following variable, if set to a non-zero value, is interpreted as
  33539. ** the number of seconds since 1970 and is used to set the result of
  33540. ** sqlite3OsCurrentTime() during testing.
  33541. */
  33542. #ifdef SQLITE_TEST
  33543. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  33544. #endif
  33545. /*
  33546. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  33547. ** the current time and date as a Julian Day number times 86_400_000. In
  33548. ** other words, write into *piNow the number of milliseconds since the Julian
  33549. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  33550. ** proleptic Gregorian calendar.
  33551. **
  33552. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  33553. ** cannot be found.
  33554. */
  33555. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  33556. /* FILETIME structure is a 64-bit value representing the number of
  33557. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  33558. */
  33559. FILETIME ft;
  33560. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  33561. #ifdef SQLITE_TEST
  33562. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  33563. #endif
  33564. /* 2^32 - to avoid use of LL and warnings in gcc */
  33565. static const sqlite3_int64 max32BitValue =
  33566. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  33567. (sqlite3_int64)294967296;
  33568. #if SQLITE_OS_WINCE
  33569. SYSTEMTIME time;
  33570. osGetSystemTime(&time);
  33571. /* if SystemTimeToFileTime() fails, it returns zero. */
  33572. if (!osSystemTimeToFileTime(&time,&ft)){
  33573. return SQLITE_ERROR;
  33574. }
  33575. #else
  33576. osGetSystemTimeAsFileTime( &ft );
  33577. #endif
  33578. *piNow = winFiletimeEpoch +
  33579. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  33580. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  33581. #ifdef SQLITE_TEST
  33582. if( sqlite3_current_time ){
  33583. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  33584. }
  33585. #endif
  33586. UNUSED_PARAMETER(pVfs);
  33587. return SQLITE_OK;
  33588. }
  33589. /*
  33590. ** Find the current time (in Universal Coordinated Time). Write the
  33591. ** current time and date as a Julian Day number into *prNow and
  33592. ** return 0. Return 1 if the time and date cannot be found.
  33593. */
  33594. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  33595. int rc;
  33596. sqlite3_int64 i;
  33597. rc = winCurrentTimeInt64(pVfs, &i);
  33598. if( !rc ){
  33599. *prNow = i/86400000.0;
  33600. }
  33601. return rc;
  33602. }
  33603. /*
  33604. ** The idea is that this function works like a combination of
  33605. ** GetLastError() and FormatMessage() on Windows (or errno and
  33606. ** strerror_r() on Unix). After an error is returned by an OS
  33607. ** function, SQLite calls this function with zBuf pointing to
  33608. ** a buffer of nBuf bytes. The OS layer should populate the
  33609. ** buffer with a nul-terminated UTF-8 encoded error message
  33610. ** describing the last IO error to have occurred within the calling
  33611. ** thread.
  33612. **
  33613. ** If the error message is too large for the supplied buffer,
  33614. ** it should be truncated. The return value of xGetLastError
  33615. ** is zero if the error message fits in the buffer, or non-zero
  33616. ** otherwise (if the message was truncated). If non-zero is returned,
  33617. ** then it is not necessary to include the nul-terminator character
  33618. ** in the output buffer.
  33619. **
  33620. ** Not supplying an error message will have no adverse effect
  33621. ** on SQLite. It is fine to have an implementation that never
  33622. ** returns an error message:
  33623. **
  33624. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33625. ** assert(zBuf[0]=='\0');
  33626. ** return 0;
  33627. ** }
  33628. **
  33629. ** However if an error message is supplied, it will be incorporated
  33630. ** by sqlite into the error message available to the user using
  33631. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  33632. */
  33633. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33634. UNUSED_PARAMETER(pVfs);
  33635. return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
  33636. }
  33637. /*
  33638. ** Initialize and deinitialize the operating system interface.
  33639. */
  33640. SQLITE_API int sqlite3_os_init(void){
  33641. static sqlite3_vfs winVfs = {
  33642. 3, /* iVersion */
  33643. sizeof(winFile), /* szOsFile */
  33644. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  33645. 0, /* pNext */
  33646. "win32", /* zName */
  33647. 0, /* pAppData */
  33648. winOpen, /* xOpen */
  33649. winDelete, /* xDelete */
  33650. winAccess, /* xAccess */
  33651. winFullPathname, /* xFullPathname */
  33652. winDlOpen, /* xDlOpen */
  33653. winDlError, /* xDlError */
  33654. winDlSym, /* xDlSym */
  33655. winDlClose, /* xDlClose */
  33656. winRandomness, /* xRandomness */
  33657. winSleep, /* xSleep */
  33658. winCurrentTime, /* xCurrentTime */
  33659. winGetLastError, /* xGetLastError */
  33660. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  33661. winSetSystemCall, /* xSetSystemCall */
  33662. winGetSystemCall, /* xGetSystemCall */
  33663. winNextSystemCall, /* xNextSystemCall */
  33664. };
  33665. #if defined(SQLITE_WIN32_HAS_WIDE)
  33666. static sqlite3_vfs winLongPathVfs = {
  33667. 3, /* iVersion */
  33668. sizeof(winFile), /* szOsFile */
  33669. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  33670. 0, /* pNext */
  33671. "win32-longpath", /* zName */
  33672. 0, /* pAppData */
  33673. winOpen, /* xOpen */
  33674. winDelete, /* xDelete */
  33675. winAccess, /* xAccess */
  33676. winFullPathname, /* xFullPathname */
  33677. winDlOpen, /* xDlOpen */
  33678. winDlError, /* xDlError */
  33679. winDlSym, /* xDlSym */
  33680. winDlClose, /* xDlClose */
  33681. winRandomness, /* xRandomness */
  33682. winSleep, /* xSleep */
  33683. winCurrentTime, /* xCurrentTime */
  33684. winGetLastError, /* xGetLastError */
  33685. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  33686. winSetSystemCall, /* xSetSystemCall */
  33687. winGetSystemCall, /* xGetSystemCall */
  33688. winNextSystemCall, /* xNextSystemCall */
  33689. };
  33690. #endif
  33691. /* Double-check that the aSyscall[] array has been constructed
  33692. ** correctly. See ticket [bb3a86e890c8e96ab] */
  33693. assert( ArraySize(aSyscall)==75 );
  33694. /* get memory map allocation granularity */
  33695. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  33696. #if SQLITE_OS_WINRT
  33697. osGetNativeSystemInfo(&winSysInfo);
  33698. #else
  33699. osGetSystemInfo(&winSysInfo);
  33700. #endif
  33701. assert( winSysInfo.dwAllocationGranularity>0 );
  33702. assert( winSysInfo.dwPageSize>0 );
  33703. sqlite3_vfs_register(&winVfs, 1);
  33704. #if defined(SQLITE_WIN32_HAS_WIDE)
  33705. sqlite3_vfs_register(&winLongPathVfs, 0);
  33706. #endif
  33707. return SQLITE_OK;
  33708. }
  33709. SQLITE_API int sqlite3_os_end(void){
  33710. #if SQLITE_OS_WINRT
  33711. if( sleepObj!=NULL ){
  33712. osCloseHandle(sleepObj);
  33713. sleepObj = NULL;
  33714. }
  33715. #endif
  33716. return SQLITE_OK;
  33717. }
  33718. #endif /* SQLITE_OS_WIN */
  33719. /************** End of os_win.c **********************************************/
  33720. /************** Begin file bitvec.c ******************************************/
  33721. /*
  33722. ** 2008 February 16
  33723. **
  33724. ** The author disclaims copyright to this source code. In place of
  33725. ** a legal notice, here is a blessing:
  33726. **
  33727. ** May you do good and not evil.
  33728. ** May you find forgiveness for yourself and forgive others.
  33729. ** May you share freely, never taking more than you give.
  33730. **
  33731. *************************************************************************
  33732. ** This file implements an object that represents a fixed-length
  33733. ** bitmap. Bits are numbered starting with 1.
  33734. **
  33735. ** A bitmap is used to record which pages of a database file have been
  33736. ** journalled during a transaction, or which pages have the "dont-write"
  33737. ** property. Usually only a few pages are meet either condition.
  33738. ** So the bitmap is usually sparse and has low cardinality.
  33739. ** But sometimes (for example when during a DROP of a large table) most
  33740. ** or all of the pages in a database can get journalled. In those cases,
  33741. ** the bitmap becomes dense with high cardinality. The algorithm needs
  33742. ** to handle both cases well.
  33743. **
  33744. ** The size of the bitmap is fixed when the object is created.
  33745. **
  33746. ** All bits are clear when the bitmap is created. Individual bits
  33747. ** may be set or cleared one at a time.
  33748. **
  33749. ** Test operations are about 100 times more common that set operations.
  33750. ** Clear operations are exceedingly rare. There are usually between
  33751. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  33752. ** sometimes grow into tens of thousands or larger. The size of the
  33753. ** Bitvec object is the number of pages in the database file at the
  33754. ** start of a transaction, and is thus usually less than a few thousand,
  33755. ** but can be as large as 2 billion for a really big database.
  33756. */
  33757. /* Size of the Bitvec structure in bytes. */
  33758. #define BITVEC_SZ 512
  33759. /* Round the union size down to the nearest pointer boundary, since that's how
  33760. ** it will be aligned within the Bitvec struct. */
  33761. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  33762. /* Type of the array "element" for the bitmap representation.
  33763. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  33764. ** Setting this to the "natural word" size of your CPU may improve
  33765. ** performance. */
  33766. #define BITVEC_TELEM u8
  33767. /* Size, in bits, of the bitmap element. */
  33768. #define BITVEC_SZELEM 8
  33769. /* Number of elements in a bitmap array. */
  33770. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  33771. /* Number of bits in the bitmap array. */
  33772. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  33773. /* Number of u32 values in hash table. */
  33774. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  33775. /* Maximum number of entries in hash table before
  33776. ** sub-dividing and re-hashing. */
  33777. #define BITVEC_MXHASH (BITVEC_NINT/2)
  33778. /* Hashing function for the aHash representation.
  33779. ** Empirical testing showed that the *37 multiplier
  33780. ** (an arbitrary prime)in the hash function provided
  33781. ** no fewer collisions than the no-op *1. */
  33782. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  33783. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  33784. /*
  33785. ** A bitmap is an instance of the following structure.
  33786. **
  33787. ** This bitmap records the existence of zero or more bits
  33788. ** with values between 1 and iSize, inclusive.
  33789. **
  33790. ** There are three possible representations of the bitmap.
  33791. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  33792. ** bitmap. The least significant bit is bit 1.
  33793. **
  33794. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  33795. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  33796. **
  33797. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  33798. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  33799. ** handles up to iDivisor separate values of i. apSub[0] holds
  33800. ** values between 1 and iDivisor. apSub[1] holds values between
  33801. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  33802. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  33803. ** to hold deal with values between 1 and iDivisor.
  33804. */
  33805. struct Bitvec {
  33806. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  33807. u32 nSet; /* Number of bits that are set - only valid for aHash
  33808. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  33809. ** this would be 125. */
  33810. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  33811. /* Should >=0 for apSub element. */
  33812. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  33813. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  33814. union {
  33815. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  33816. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  33817. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  33818. } u;
  33819. };
  33820. /*
  33821. ** Create a new bitmap object able to handle bits between 0 and iSize,
  33822. ** inclusive. Return a pointer to the new object. Return NULL if
  33823. ** malloc fails.
  33824. */
  33825. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  33826. Bitvec *p;
  33827. assert( sizeof(*p)==BITVEC_SZ );
  33828. p = sqlite3MallocZero( sizeof(*p) );
  33829. if( p ){
  33830. p->iSize = iSize;
  33831. }
  33832. return p;
  33833. }
  33834. /*
  33835. ** Check to see if the i-th bit is set. Return true or false.
  33836. ** If p is NULL (if the bitmap has not been created) or if
  33837. ** i is out of range, then return false.
  33838. */
  33839. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  33840. if( p==0 ) return 0;
  33841. if( i>p->iSize || i==0 ) return 0;
  33842. i--;
  33843. while( p->iDivisor ){
  33844. u32 bin = i/p->iDivisor;
  33845. i = i%p->iDivisor;
  33846. p = p->u.apSub[bin];
  33847. if (!p) {
  33848. return 0;
  33849. }
  33850. }
  33851. if( p->iSize<=BITVEC_NBIT ){
  33852. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  33853. } else{
  33854. u32 h = BITVEC_HASH(i++);
  33855. while( p->u.aHash[h] ){
  33856. if( p->u.aHash[h]==i ) return 1;
  33857. h = (h+1) % BITVEC_NINT;
  33858. }
  33859. return 0;
  33860. }
  33861. }
  33862. /*
  33863. ** Set the i-th bit. Return 0 on success and an error code if
  33864. ** anything goes wrong.
  33865. **
  33866. ** This routine might cause sub-bitmaps to be allocated. Failing
  33867. ** to get the memory needed to hold the sub-bitmap is the only
  33868. ** that can go wrong with an insert, assuming p and i are valid.
  33869. **
  33870. ** The calling function must ensure that p is a valid Bitvec object
  33871. ** and that the value for "i" is within range of the Bitvec object.
  33872. ** Otherwise the behavior is undefined.
  33873. */
  33874. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  33875. u32 h;
  33876. if( p==0 ) return SQLITE_OK;
  33877. assert( i>0 );
  33878. assert( i<=p->iSize );
  33879. i--;
  33880. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  33881. u32 bin = i/p->iDivisor;
  33882. i = i%p->iDivisor;
  33883. if( p->u.apSub[bin]==0 ){
  33884. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  33885. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  33886. }
  33887. p = p->u.apSub[bin];
  33888. }
  33889. if( p->iSize<=BITVEC_NBIT ){
  33890. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  33891. return SQLITE_OK;
  33892. }
  33893. h = BITVEC_HASH(i++);
  33894. /* if there wasn't a hash collision, and this doesn't */
  33895. /* completely fill the hash, then just add it without */
  33896. /* worring about sub-dividing and re-hashing. */
  33897. if( !p->u.aHash[h] ){
  33898. if (p->nSet<(BITVEC_NINT-1)) {
  33899. goto bitvec_set_end;
  33900. } else {
  33901. goto bitvec_set_rehash;
  33902. }
  33903. }
  33904. /* there was a collision, check to see if it's already */
  33905. /* in hash, if not, try to find a spot for it */
  33906. do {
  33907. if( p->u.aHash[h]==i ) return SQLITE_OK;
  33908. h++;
  33909. if( h>=BITVEC_NINT ) h = 0;
  33910. } while( p->u.aHash[h] );
  33911. /* we didn't find it in the hash. h points to the first */
  33912. /* available free spot. check to see if this is going to */
  33913. /* make our hash too "full". */
  33914. bitvec_set_rehash:
  33915. if( p->nSet>=BITVEC_MXHASH ){
  33916. unsigned int j;
  33917. int rc;
  33918. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  33919. if( aiValues==0 ){
  33920. return SQLITE_NOMEM;
  33921. }else{
  33922. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  33923. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  33924. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  33925. rc = sqlite3BitvecSet(p, i);
  33926. for(j=0; j<BITVEC_NINT; j++){
  33927. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  33928. }
  33929. sqlite3StackFree(0, aiValues);
  33930. return rc;
  33931. }
  33932. }
  33933. bitvec_set_end:
  33934. p->nSet++;
  33935. p->u.aHash[h] = i;
  33936. return SQLITE_OK;
  33937. }
  33938. /*
  33939. ** Clear the i-th bit.
  33940. **
  33941. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  33942. ** that BitvecClear can use to rebuilt its hash table.
  33943. */
  33944. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  33945. if( p==0 ) return;
  33946. assert( i>0 );
  33947. i--;
  33948. while( p->iDivisor ){
  33949. u32 bin = i/p->iDivisor;
  33950. i = i%p->iDivisor;
  33951. p = p->u.apSub[bin];
  33952. if (!p) {
  33953. return;
  33954. }
  33955. }
  33956. if( p->iSize<=BITVEC_NBIT ){
  33957. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  33958. }else{
  33959. unsigned int j;
  33960. u32 *aiValues = pBuf;
  33961. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  33962. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  33963. p->nSet = 0;
  33964. for(j=0; j<BITVEC_NINT; j++){
  33965. if( aiValues[j] && aiValues[j]!=(i+1) ){
  33966. u32 h = BITVEC_HASH(aiValues[j]-1);
  33967. p->nSet++;
  33968. while( p->u.aHash[h] ){
  33969. h++;
  33970. if( h>=BITVEC_NINT ) h = 0;
  33971. }
  33972. p->u.aHash[h] = aiValues[j];
  33973. }
  33974. }
  33975. }
  33976. }
  33977. /*
  33978. ** Destroy a bitmap object. Reclaim all memory used.
  33979. */
  33980. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  33981. if( p==0 ) return;
  33982. if( p->iDivisor ){
  33983. unsigned int i;
  33984. for(i=0; i<BITVEC_NPTR; i++){
  33985. sqlite3BitvecDestroy(p->u.apSub[i]);
  33986. }
  33987. }
  33988. sqlite3_free(p);
  33989. }
  33990. /*
  33991. ** Return the value of the iSize parameter specified when Bitvec *p
  33992. ** was created.
  33993. */
  33994. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  33995. return p->iSize;
  33996. }
  33997. #ifndef SQLITE_OMIT_BUILTIN_TEST
  33998. /*
  33999. ** Let V[] be an array of unsigned characters sufficient to hold
  34000. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  34001. ** Then the following macros can be used to set, clear, or test
  34002. ** individual bits within V.
  34003. */
  34004. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  34005. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  34006. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  34007. /*
  34008. ** This routine runs an extensive test of the Bitvec code.
  34009. **
  34010. ** The input is an array of integers that acts as a program
  34011. ** to test the Bitvec. The integers are opcodes followed
  34012. ** by 0, 1, or 3 operands, depending on the opcode. Another
  34013. ** opcode follows immediately after the last operand.
  34014. **
  34015. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  34016. ** "halt" opcode and causes the test to end.
  34017. **
  34018. ** 0 Halt and return the number of errors
  34019. ** 1 N S X Set N bits beginning with S and incrementing by X
  34020. ** 2 N S X Clear N bits beginning with S and incrementing by X
  34021. ** 3 N Set N randomly chosen bits
  34022. ** 4 N Clear N randomly chosen bits
  34023. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  34024. **
  34025. ** The opcodes 1 through 4 perform set and clear operations are performed
  34026. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  34027. ** Opcode 5 works on the linear array only, not on the Bitvec.
  34028. ** Opcode 5 is used to deliberately induce a fault in order to
  34029. ** confirm that error detection works.
  34030. **
  34031. ** At the conclusion of the test the linear array is compared
  34032. ** against the Bitvec object. If there are any differences,
  34033. ** an error is returned. If they are the same, zero is returned.
  34034. **
  34035. ** If a memory allocation error occurs, return -1.
  34036. */
  34037. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  34038. Bitvec *pBitvec = 0;
  34039. unsigned char *pV = 0;
  34040. int rc = -1;
  34041. int i, nx, pc, op;
  34042. void *pTmpSpace;
  34043. /* Allocate the Bitvec to be tested and a linear array of
  34044. ** bits to act as the reference */
  34045. pBitvec = sqlite3BitvecCreate( sz );
  34046. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  34047. pTmpSpace = sqlite3_malloc(BITVEC_SZ);
  34048. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  34049. /* NULL pBitvec tests */
  34050. sqlite3BitvecSet(0, 1);
  34051. sqlite3BitvecClear(0, 1, pTmpSpace);
  34052. /* Run the program */
  34053. pc = 0;
  34054. while( (op = aOp[pc])!=0 ){
  34055. switch( op ){
  34056. case 1:
  34057. case 2:
  34058. case 5: {
  34059. nx = 4;
  34060. i = aOp[pc+2] - 1;
  34061. aOp[pc+2] += aOp[pc+3];
  34062. break;
  34063. }
  34064. case 3:
  34065. case 4:
  34066. default: {
  34067. nx = 2;
  34068. sqlite3_randomness(sizeof(i), &i);
  34069. break;
  34070. }
  34071. }
  34072. if( (--aOp[pc+1]) > 0 ) nx = 0;
  34073. pc += nx;
  34074. i = (i & 0x7fffffff)%sz;
  34075. if( (op & 1)!=0 ){
  34076. SETBIT(pV, (i+1));
  34077. if( op!=5 ){
  34078. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  34079. }
  34080. }else{
  34081. CLEARBIT(pV, (i+1));
  34082. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  34083. }
  34084. }
  34085. /* Test to make sure the linear array exactly matches the
  34086. ** Bitvec object. Start with the assumption that they do
  34087. ** match (rc==0). Change rc to non-zero if a discrepancy
  34088. ** is found.
  34089. */
  34090. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  34091. + sqlite3BitvecTest(pBitvec, 0)
  34092. + (sqlite3BitvecSize(pBitvec) - sz);
  34093. for(i=1; i<=sz; i++){
  34094. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  34095. rc = i;
  34096. break;
  34097. }
  34098. }
  34099. /* Free allocated structure */
  34100. bitvec_end:
  34101. sqlite3_free(pTmpSpace);
  34102. sqlite3_free(pV);
  34103. sqlite3BitvecDestroy(pBitvec);
  34104. return rc;
  34105. }
  34106. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  34107. /************** End of bitvec.c **********************************************/
  34108. /************** Begin file pcache.c ******************************************/
  34109. /*
  34110. ** 2008 August 05
  34111. **
  34112. ** The author disclaims copyright to this source code. In place of
  34113. ** a legal notice, here is a blessing:
  34114. **
  34115. ** May you do good and not evil.
  34116. ** May you find forgiveness for yourself and forgive others.
  34117. ** May you share freely, never taking more than you give.
  34118. **
  34119. *************************************************************************
  34120. ** This file implements that page cache.
  34121. */
  34122. /*
  34123. ** A complete page cache is an instance of this structure.
  34124. */
  34125. struct PCache {
  34126. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  34127. PgHdr *pSynced; /* Last synced page in dirty page list */
  34128. int nRef; /* Number of referenced pages */
  34129. int szCache; /* Configured cache size */
  34130. int szPage; /* Size of every page in this cache */
  34131. int szExtra; /* Size of extra space for each page */
  34132. int bPurgeable; /* True if pages are on backing store */
  34133. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  34134. void *pStress; /* Argument to xStress */
  34135. sqlite3_pcache *pCache; /* Pluggable cache module */
  34136. PgHdr *pPage1; /* Reference to page 1 */
  34137. };
  34138. /*
  34139. ** Some of the assert() macros in this code are too expensive to run
  34140. ** even during normal debugging. Use them only rarely on long-running
  34141. ** tests. Enable the expensive asserts using the
  34142. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  34143. */
  34144. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  34145. # define expensive_assert(X) assert(X)
  34146. #else
  34147. # define expensive_assert(X)
  34148. #endif
  34149. /********************************** Linked List Management ********************/
  34150. #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
  34151. /*
  34152. ** Check that the pCache->pSynced variable is set correctly. If it
  34153. ** is not, either fail an assert or return zero. Otherwise, return
  34154. ** non-zero. This is only used in debugging builds, as follows:
  34155. **
  34156. ** expensive_assert( pcacheCheckSynced(pCache) );
  34157. */
  34158. static int pcacheCheckSynced(PCache *pCache){
  34159. PgHdr *p;
  34160. for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
  34161. assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
  34162. }
  34163. return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
  34164. }
  34165. #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
  34166. /*
  34167. ** Remove page pPage from the list of dirty pages.
  34168. */
  34169. static void pcacheRemoveFromDirtyList(PgHdr *pPage){
  34170. PCache *p = pPage->pCache;
  34171. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  34172. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  34173. /* Update the PCache1.pSynced variable if necessary. */
  34174. if( p->pSynced==pPage ){
  34175. PgHdr *pSynced = pPage->pDirtyPrev;
  34176. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  34177. pSynced = pSynced->pDirtyPrev;
  34178. }
  34179. p->pSynced = pSynced;
  34180. }
  34181. if( pPage->pDirtyNext ){
  34182. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  34183. }else{
  34184. assert( pPage==p->pDirtyTail );
  34185. p->pDirtyTail = pPage->pDirtyPrev;
  34186. }
  34187. if( pPage->pDirtyPrev ){
  34188. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  34189. }else{
  34190. assert( pPage==p->pDirty );
  34191. p->pDirty = pPage->pDirtyNext;
  34192. }
  34193. pPage->pDirtyNext = 0;
  34194. pPage->pDirtyPrev = 0;
  34195. expensive_assert( pcacheCheckSynced(p) );
  34196. }
  34197. /*
  34198. ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
  34199. ** pPage).
  34200. */
  34201. static void pcacheAddToDirtyList(PgHdr *pPage){
  34202. PCache *p = pPage->pCache;
  34203. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  34204. pPage->pDirtyNext = p->pDirty;
  34205. if( pPage->pDirtyNext ){
  34206. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  34207. pPage->pDirtyNext->pDirtyPrev = pPage;
  34208. }
  34209. p->pDirty = pPage;
  34210. if( !p->pDirtyTail ){
  34211. p->pDirtyTail = pPage;
  34212. }
  34213. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  34214. p->pSynced = pPage;
  34215. }
  34216. expensive_assert( pcacheCheckSynced(p) );
  34217. }
  34218. /*
  34219. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  34220. ** being used for an in-memory database, this function is a no-op.
  34221. */
  34222. static void pcacheUnpin(PgHdr *p){
  34223. PCache *pCache = p->pCache;
  34224. if( pCache->bPurgeable ){
  34225. if( p->pgno==1 ){
  34226. pCache->pPage1 = 0;
  34227. }
  34228. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
  34229. }
  34230. }
  34231. /*************************************************** General Interfaces ******
  34232. **
  34233. ** Initialize and shutdown the page cache subsystem. Neither of these
  34234. ** functions are threadsafe.
  34235. */
  34236. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  34237. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  34238. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  34239. ** built-in default page cache is used instead of the application defined
  34240. ** page cache. */
  34241. sqlite3PCacheSetDefault();
  34242. }
  34243. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  34244. }
  34245. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  34246. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  34247. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  34248. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  34249. }
  34250. }
  34251. /*
  34252. ** Return the size in bytes of a PCache object.
  34253. */
  34254. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  34255. /*
  34256. ** Create a new PCache object. Storage space to hold the object
  34257. ** has already been allocated and is passed in as the p pointer.
  34258. ** The caller discovers how much space needs to be allocated by
  34259. ** calling sqlite3PcacheSize().
  34260. */
  34261. SQLITE_PRIVATE void sqlite3PcacheOpen(
  34262. int szPage, /* Size of every page */
  34263. int szExtra, /* Extra space associated with each page */
  34264. int bPurgeable, /* True if pages are on backing store */
  34265. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  34266. void *pStress, /* Argument to xStress */
  34267. PCache *p /* Preallocated space for the PCache */
  34268. ){
  34269. memset(p, 0, sizeof(PCache));
  34270. p->szPage = szPage;
  34271. p->szExtra = szExtra;
  34272. p->bPurgeable = bPurgeable;
  34273. p->xStress = xStress;
  34274. p->pStress = pStress;
  34275. p->szCache = 100;
  34276. }
  34277. /*
  34278. ** Change the page size for PCache object. The caller must ensure that there
  34279. ** are no outstanding page references when this function is called.
  34280. */
  34281. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  34282. assert( pCache->nRef==0 && pCache->pDirty==0 );
  34283. if( pCache->pCache ){
  34284. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  34285. pCache->pCache = 0;
  34286. pCache->pPage1 = 0;
  34287. }
  34288. pCache->szPage = szPage;
  34289. }
  34290. /*
  34291. ** Compute the number of pages of cache requested.
  34292. */
  34293. static int numberOfCachePages(PCache *p){
  34294. if( p->szCache>=0 ){
  34295. return p->szCache;
  34296. }else{
  34297. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  34298. }
  34299. }
  34300. /*
  34301. ** Try to obtain a page from the cache.
  34302. */
  34303. SQLITE_PRIVATE int sqlite3PcacheFetch(
  34304. PCache *pCache, /* Obtain the page from this cache */
  34305. Pgno pgno, /* Page number to obtain */
  34306. int createFlag, /* If true, create page if it does not exist already */
  34307. PgHdr **ppPage /* Write the page here */
  34308. ){
  34309. sqlite3_pcache_page *pPage = 0;
  34310. PgHdr *pPgHdr = 0;
  34311. int eCreate;
  34312. assert( pCache!=0 );
  34313. assert( createFlag==1 || createFlag==0 );
  34314. assert( pgno>0 );
  34315. /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
  34316. ** allocate it now.
  34317. */
  34318. if( !pCache->pCache && createFlag ){
  34319. sqlite3_pcache *p;
  34320. p = sqlite3GlobalConfig.pcache2.xCreate(
  34321. pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
  34322. );
  34323. if( !p ){
  34324. return SQLITE_NOMEM;
  34325. }
  34326. sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
  34327. pCache->pCache = p;
  34328. }
  34329. eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
  34330. if( pCache->pCache ){
  34331. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  34332. }
  34333. if( !pPage && eCreate==1 ){
  34334. PgHdr *pPg;
  34335. /* Find a dirty page to write-out and recycle. First try to find a
  34336. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  34337. ** cleared), but if that is not possible settle for any other
  34338. ** unreferenced dirty page.
  34339. */
  34340. expensive_assert( pcacheCheckSynced(pCache) );
  34341. for(pPg=pCache->pSynced;
  34342. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  34343. pPg=pPg->pDirtyPrev
  34344. );
  34345. pCache->pSynced = pPg;
  34346. if( !pPg ){
  34347. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  34348. }
  34349. if( pPg ){
  34350. int rc;
  34351. #ifdef SQLITE_LOG_CACHE_SPILL
  34352. sqlite3_log(SQLITE_FULL,
  34353. "spill page %d making room for %d - cache used: %d/%d",
  34354. pPg->pgno, pgno,
  34355. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  34356. numberOfCachePages(pCache));
  34357. #endif
  34358. rc = pCache->xStress(pCache->pStress, pPg);
  34359. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  34360. return rc;
  34361. }
  34362. }
  34363. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  34364. }
  34365. if( pPage ){
  34366. pPgHdr = (PgHdr *)pPage->pExtra;
  34367. if( !pPgHdr->pPage ){
  34368. memset(pPgHdr, 0, sizeof(PgHdr));
  34369. pPgHdr->pPage = pPage;
  34370. pPgHdr->pData = pPage->pBuf;
  34371. pPgHdr->pExtra = (void *)&pPgHdr[1];
  34372. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  34373. pPgHdr->pCache = pCache;
  34374. pPgHdr->pgno = pgno;
  34375. }
  34376. assert( pPgHdr->pCache==pCache );
  34377. assert( pPgHdr->pgno==pgno );
  34378. assert( pPgHdr->pData==pPage->pBuf );
  34379. assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
  34380. if( 0==pPgHdr->nRef ){
  34381. pCache->nRef++;
  34382. }
  34383. pPgHdr->nRef++;
  34384. if( pgno==1 ){
  34385. pCache->pPage1 = pPgHdr;
  34386. }
  34387. }
  34388. *ppPage = pPgHdr;
  34389. return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
  34390. }
  34391. /*
  34392. ** Decrement the reference count on a page. If the page is clean and the
  34393. ** reference count drops to 0, then it is made elible for recycling.
  34394. */
  34395. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
  34396. assert( p->nRef>0 );
  34397. p->nRef--;
  34398. if( p->nRef==0 ){
  34399. PCache *pCache = p->pCache;
  34400. pCache->nRef--;
  34401. if( (p->flags&PGHDR_DIRTY)==0 ){
  34402. pcacheUnpin(p);
  34403. }else{
  34404. /* Move the page to the head of the dirty list. */
  34405. pcacheRemoveFromDirtyList(p);
  34406. pcacheAddToDirtyList(p);
  34407. }
  34408. }
  34409. }
  34410. /*
  34411. ** Increase the reference count of a supplied page by 1.
  34412. */
  34413. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  34414. assert(p->nRef>0);
  34415. p->nRef++;
  34416. }
  34417. /*
  34418. ** Drop a page from the cache. There must be exactly one reference to the
  34419. ** page. This function deletes that reference, so after it returns the
  34420. ** page pointed to by p is invalid.
  34421. */
  34422. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  34423. PCache *pCache;
  34424. assert( p->nRef==1 );
  34425. if( p->flags&PGHDR_DIRTY ){
  34426. pcacheRemoveFromDirtyList(p);
  34427. }
  34428. pCache = p->pCache;
  34429. pCache->nRef--;
  34430. if( p->pgno==1 ){
  34431. pCache->pPage1 = 0;
  34432. }
  34433. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
  34434. }
  34435. /*
  34436. ** Make sure the page is marked as dirty. If it isn't dirty already,
  34437. ** make it so.
  34438. */
  34439. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  34440. p->flags &= ~PGHDR_DONT_WRITE;
  34441. assert( p->nRef>0 );
  34442. if( 0==(p->flags & PGHDR_DIRTY) ){
  34443. p->flags |= PGHDR_DIRTY;
  34444. pcacheAddToDirtyList( p);
  34445. }
  34446. }
  34447. /*
  34448. ** Make sure the page is marked as clean. If it isn't clean already,
  34449. ** make it so.
  34450. */
  34451. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  34452. if( (p->flags & PGHDR_DIRTY) ){
  34453. pcacheRemoveFromDirtyList(p);
  34454. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  34455. if( p->nRef==0 ){
  34456. pcacheUnpin(p);
  34457. }
  34458. }
  34459. }
  34460. /*
  34461. ** Make every page in the cache clean.
  34462. */
  34463. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  34464. PgHdr *p;
  34465. while( (p = pCache->pDirty)!=0 ){
  34466. sqlite3PcacheMakeClean(p);
  34467. }
  34468. }
  34469. /*
  34470. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  34471. */
  34472. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  34473. PgHdr *p;
  34474. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  34475. p->flags &= ~PGHDR_NEED_SYNC;
  34476. }
  34477. pCache->pSynced = pCache->pDirtyTail;
  34478. }
  34479. /*
  34480. ** Change the page number of page p to newPgno.
  34481. */
  34482. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  34483. PCache *pCache = p->pCache;
  34484. assert( p->nRef>0 );
  34485. assert( newPgno>0 );
  34486. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  34487. p->pgno = newPgno;
  34488. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  34489. pcacheRemoveFromDirtyList(p);
  34490. pcacheAddToDirtyList(p);
  34491. }
  34492. }
  34493. /*
  34494. ** Drop every cache entry whose page number is greater than "pgno". The
  34495. ** caller must ensure that there are no outstanding references to any pages
  34496. ** other than page 1 with a page number greater than pgno.
  34497. **
  34498. ** If there is a reference to page 1 and the pgno parameter passed to this
  34499. ** function is 0, then the data area associated with page 1 is zeroed, but
  34500. ** the page object is not dropped.
  34501. */
  34502. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  34503. if( pCache->pCache ){
  34504. PgHdr *p;
  34505. PgHdr *pNext;
  34506. for(p=pCache->pDirty; p; p=pNext){
  34507. pNext = p->pDirtyNext;
  34508. /* This routine never gets call with a positive pgno except right
  34509. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  34510. ** it must be that pgno==0.
  34511. */
  34512. assert( p->pgno>0 );
  34513. if( ALWAYS(p->pgno>pgno) ){
  34514. assert( p->flags&PGHDR_DIRTY );
  34515. sqlite3PcacheMakeClean(p);
  34516. }
  34517. }
  34518. if( pgno==0 && pCache->pPage1 ){
  34519. memset(pCache->pPage1->pData, 0, pCache->szPage);
  34520. pgno = 1;
  34521. }
  34522. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  34523. }
  34524. }
  34525. /*
  34526. ** Close a cache.
  34527. */
  34528. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  34529. if( pCache->pCache ){
  34530. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  34531. }
  34532. }
  34533. /*
  34534. ** Discard the contents of the cache.
  34535. */
  34536. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  34537. sqlite3PcacheTruncate(pCache, 0);
  34538. }
  34539. /*
  34540. ** Merge two lists of pages connected by pDirty and in pgno order.
  34541. ** Do not both fixing the pDirtyPrev pointers.
  34542. */
  34543. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  34544. PgHdr result, *pTail;
  34545. pTail = &result;
  34546. while( pA && pB ){
  34547. if( pA->pgno<pB->pgno ){
  34548. pTail->pDirty = pA;
  34549. pTail = pA;
  34550. pA = pA->pDirty;
  34551. }else{
  34552. pTail->pDirty = pB;
  34553. pTail = pB;
  34554. pB = pB->pDirty;
  34555. }
  34556. }
  34557. if( pA ){
  34558. pTail->pDirty = pA;
  34559. }else if( pB ){
  34560. pTail->pDirty = pB;
  34561. }else{
  34562. pTail->pDirty = 0;
  34563. }
  34564. return result.pDirty;
  34565. }
  34566. /*
  34567. ** Sort the list of pages in accending order by pgno. Pages are
  34568. ** connected by pDirty pointers. The pDirtyPrev pointers are
  34569. ** corrupted by this sort.
  34570. **
  34571. ** Since there cannot be more than 2^31 distinct pages in a database,
  34572. ** there cannot be more than 31 buckets required by the merge sorter.
  34573. ** One extra bucket is added to catch overflow in case something
  34574. ** ever changes to make the previous sentence incorrect.
  34575. */
  34576. #define N_SORT_BUCKET 32
  34577. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  34578. PgHdr *a[N_SORT_BUCKET], *p;
  34579. int i;
  34580. memset(a, 0, sizeof(a));
  34581. while( pIn ){
  34582. p = pIn;
  34583. pIn = p->pDirty;
  34584. p->pDirty = 0;
  34585. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  34586. if( a[i]==0 ){
  34587. a[i] = p;
  34588. break;
  34589. }else{
  34590. p = pcacheMergeDirtyList(a[i], p);
  34591. a[i] = 0;
  34592. }
  34593. }
  34594. if( NEVER(i==N_SORT_BUCKET-1) ){
  34595. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  34596. ** the input list. But that is impossible.
  34597. */
  34598. a[i] = pcacheMergeDirtyList(a[i], p);
  34599. }
  34600. }
  34601. p = a[0];
  34602. for(i=1; i<N_SORT_BUCKET; i++){
  34603. p = pcacheMergeDirtyList(p, a[i]);
  34604. }
  34605. return p;
  34606. }
  34607. /*
  34608. ** Return a list of all dirty pages in the cache, sorted by page number.
  34609. */
  34610. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  34611. PgHdr *p;
  34612. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  34613. p->pDirty = p->pDirtyNext;
  34614. }
  34615. return pcacheSortDirtyList(pCache->pDirty);
  34616. }
  34617. /*
  34618. ** Return the total number of referenced pages held by the cache.
  34619. */
  34620. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  34621. return pCache->nRef;
  34622. }
  34623. /*
  34624. ** Return the number of references to the page supplied as an argument.
  34625. */
  34626. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  34627. return p->nRef;
  34628. }
  34629. /*
  34630. ** Return the total number of pages in the cache.
  34631. */
  34632. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  34633. int nPage = 0;
  34634. if( pCache->pCache ){
  34635. nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  34636. }
  34637. return nPage;
  34638. }
  34639. #ifdef SQLITE_TEST
  34640. /*
  34641. ** Get the suggested cache-size value.
  34642. */
  34643. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  34644. return numberOfCachePages(pCache);
  34645. }
  34646. #endif
  34647. /*
  34648. ** Set the suggested cache-size value.
  34649. */
  34650. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  34651. pCache->szCache = mxPage;
  34652. if( pCache->pCache ){
  34653. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  34654. numberOfCachePages(pCache));
  34655. }
  34656. }
  34657. /*
  34658. ** Free up as much memory as possible from the page cache.
  34659. */
  34660. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  34661. if( pCache->pCache ){
  34662. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  34663. }
  34664. }
  34665. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  34666. /*
  34667. ** For all dirty pages currently in the cache, invoke the specified
  34668. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  34669. ** defined.
  34670. */
  34671. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  34672. PgHdr *pDirty;
  34673. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  34674. xIter(pDirty);
  34675. }
  34676. }
  34677. #endif
  34678. /************** End of pcache.c **********************************************/
  34679. /************** Begin file pcache1.c *****************************************/
  34680. /*
  34681. ** 2008 November 05
  34682. **
  34683. ** The author disclaims copyright to this source code. In place of
  34684. ** a legal notice, here is a blessing:
  34685. **
  34686. ** May you do good and not evil.
  34687. ** May you find forgiveness for yourself and forgive others.
  34688. ** May you share freely, never taking more than you give.
  34689. **
  34690. *************************************************************************
  34691. **
  34692. ** This file implements the default page cache implementation (the
  34693. ** sqlite3_pcache interface). It also contains part of the implementation
  34694. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  34695. ** If the default page cache implementation is overriden, then neither of
  34696. ** these two features are available.
  34697. */
  34698. typedef struct PCache1 PCache1;
  34699. typedef struct PgHdr1 PgHdr1;
  34700. typedef struct PgFreeslot PgFreeslot;
  34701. typedef struct PGroup PGroup;
  34702. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  34703. ** of one or more PCaches that are able to recycle each others unpinned
  34704. ** pages when they are under memory pressure. A PGroup is an instance of
  34705. ** the following object.
  34706. **
  34707. ** This page cache implementation works in one of two modes:
  34708. **
  34709. ** (1) Every PCache is the sole member of its own PGroup. There is
  34710. ** one PGroup per PCache.
  34711. **
  34712. ** (2) There is a single global PGroup that all PCaches are a member
  34713. ** of.
  34714. **
  34715. ** Mode 1 uses more memory (since PCache instances are not able to rob
  34716. ** unused pages from other PCaches) but it also operates without a mutex,
  34717. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  34718. ** threadsafe, but recycles pages more efficiently.
  34719. **
  34720. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  34721. ** PGroup which is the pcache1.grp global variable and its mutex is
  34722. ** SQLITE_MUTEX_STATIC_LRU.
  34723. */
  34724. struct PGroup {
  34725. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  34726. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  34727. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  34728. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  34729. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  34730. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  34731. };
  34732. /* Each page cache is an instance of the following object. Every
  34733. ** open database file (including each in-memory database and each
  34734. ** temporary or transient database) has a single page cache which
  34735. ** is an instance of this object.
  34736. **
  34737. ** Pointers to structures of this type are cast and returned as
  34738. ** opaque sqlite3_pcache* handles.
  34739. */
  34740. struct PCache1 {
  34741. /* Cache configuration parameters. Page size (szPage) and the purgeable
  34742. ** flag (bPurgeable) are set when the cache is created. nMax may be
  34743. ** modified at any time by a call to the pcache1Cachesize() method.
  34744. ** The PGroup mutex must be held when accessing nMax.
  34745. */
  34746. PGroup *pGroup; /* PGroup this cache belongs to */
  34747. int szPage; /* Size of allocated pages in bytes */
  34748. int szExtra; /* Size of extra space in bytes */
  34749. int bPurgeable; /* True if cache is purgeable */
  34750. unsigned int nMin; /* Minimum number of pages reserved */
  34751. unsigned int nMax; /* Configured "cache_size" value */
  34752. unsigned int n90pct; /* nMax*9/10 */
  34753. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  34754. /* Hash table of all pages. The following variables may only be accessed
  34755. ** when the accessor is holding the PGroup mutex.
  34756. */
  34757. unsigned int nRecyclable; /* Number of pages in the LRU list */
  34758. unsigned int nPage; /* Total number of pages in apHash */
  34759. unsigned int nHash; /* Number of slots in apHash[] */
  34760. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  34761. };
  34762. /*
  34763. ** Each cache entry is represented by an instance of the following
  34764. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  34765. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  34766. ** in memory.
  34767. */
  34768. struct PgHdr1 {
  34769. sqlite3_pcache_page page;
  34770. unsigned int iKey; /* Key value (page number) */
  34771. PgHdr1 *pNext; /* Next in hash table chain */
  34772. PCache1 *pCache; /* Cache that currently owns this page */
  34773. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  34774. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  34775. };
  34776. /*
  34777. ** Free slots in the allocator used to divide up the buffer provided using
  34778. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  34779. */
  34780. struct PgFreeslot {
  34781. PgFreeslot *pNext; /* Next free slot */
  34782. };
  34783. /*
  34784. ** Global data used by this cache.
  34785. */
  34786. static SQLITE_WSD struct PCacheGlobal {
  34787. PGroup grp; /* The global PGroup for mode (2) */
  34788. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  34789. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  34790. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  34791. ** The nFreeSlot and pFree values do require mutex protection.
  34792. */
  34793. int isInit; /* True if initialized */
  34794. int szSlot; /* Size of each free slot */
  34795. int nSlot; /* The number of pcache slots */
  34796. int nReserve; /* Try to keep nFreeSlot above this */
  34797. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  34798. /* Above requires no mutex. Use mutex below for variable that follow. */
  34799. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  34800. PgFreeslot *pFree; /* Free page blocks */
  34801. int nFreeSlot; /* Number of unused pcache slots */
  34802. /* The following value requires a mutex to change. We skip the mutex on
  34803. ** reading because (1) most platforms read a 32-bit integer atomically and
  34804. ** (2) even if an incorrect value is read, no great harm is done since this
  34805. ** is really just an optimization. */
  34806. int bUnderPressure; /* True if low on PAGECACHE memory */
  34807. } pcache1_g;
  34808. /*
  34809. ** All code in this file should access the global structure above via the
  34810. ** alias "pcache1". This ensures that the WSD emulation is used when
  34811. ** compiling for systems that do not support real WSD.
  34812. */
  34813. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  34814. /*
  34815. ** Macros to enter and leave the PCache LRU mutex.
  34816. */
  34817. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  34818. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  34819. /******************************************************************************/
  34820. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  34821. /*
  34822. ** This function is called during initialization if a static buffer is
  34823. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  34824. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  34825. ** enough to contain 'n' buffers of 'sz' bytes each.
  34826. **
  34827. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  34828. ** to be serialized already. There is no need for further mutexing.
  34829. */
  34830. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  34831. if( pcache1.isInit ){
  34832. PgFreeslot *p;
  34833. sz = ROUNDDOWN8(sz);
  34834. pcache1.szSlot = sz;
  34835. pcache1.nSlot = pcache1.nFreeSlot = n;
  34836. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  34837. pcache1.pStart = pBuf;
  34838. pcache1.pFree = 0;
  34839. pcache1.bUnderPressure = 0;
  34840. while( n-- ){
  34841. p = (PgFreeslot*)pBuf;
  34842. p->pNext = pcache1.pFree;
  34843. pcache1.pFree = p;
  34844. pBuf = (void*)&((char*)pBuf)[sz];
  34845. }
  34846. pcache1.pEnd = pBuf;
  34847. }
  34848. }
  34849. /*
  34850. ** Malloc function used within this file to allocate space from the buffer
  34851. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  34852. ** such buffer exists or there is no space left in it, this function falls
  34853. ** back to sqlite3Malloc().
  34854. **
  34855. ** Multiple threads can run this routine at the same time. Global variables
  34856. ** in pcache1 need to be protected via mutex.
  34857. */
  34858. static void *pcache1Alloc(int nByte){
  34859. void *p = 0;
  34860. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  34861. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  34862. if( nByte<=pcache1.szSlot ){
  34863. sqlite3_mutex_enter(pcache1.mutex);
  34864. p = (PgHdr1 *)pcache1.pFree;
  34865. if( p ){
  34866. pcache1.pFree = pcache1.pFree->pNext;
  34867. pcache1.nFreeSlot--;
  34868. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  34869. assert( pcache1.nFreeSlot>=0 );
  34870. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  34871. }
  34872. sqlite3_mutex_leave(pcache1.mutex);
  34873. }
  34874. if( p==0 ){
  34875. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  34876. ** it from sqlite3Malloc instead.
  34877. */
  34878. p = sqlite3Malloc(nByte);
  34879. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  34880. if( p ){
  34881. int sz = sqlite3MallocSize(p);
  34882. sqlite3_mutex_enter(pcache1.mutex);
  34883. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  34884. sqlite3_mutex_leave(pcache1.mutex);
  34885. }
  34886. #endif
  34887. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  34888. }
  34889. return p;
  34890. }
  34891. /*
  34892. ** Free an allocated buffer obtained from pcache1Alloc().
  34893. */
  34894. static int pcache1Free(void *p){
  34895. int nFreed = 0;
  34896. if( p==0 ) return 0;
  34897. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  34898. PgFreeslot *pSlot;
  34899. sqlite3_mutex_enter(pcache1.mutex);
  34900. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  34901. pSlot = (PgFreeslot*)p;
  34902. pSlot->pNext = pcache1.pFree;
  34903. pcache1.pFree = pSlot;
  34904. pcache1.nFreeSlot++;
  34905. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  34906. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  34907. sqlite3_mutex_leave(pcache1.mutex);
  34908. }else{
  34909. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  34910. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  34911. nFreed = sqlite3MallocSize(p);
  34912. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  34913. sqlite3_mutex_enter(pcache1.mutex);
  34914. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
  34915. sqlite3_mutex_leave(pcache1.mutex);
  34916. #endif
  34917. sqlite3_free(p);
  34918. }
  34919. return nFreed;
  34920. }
  34921. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  34922. /*
  34923. ** Return the size of a pcache allocation
  34924. */
  34925. static int pcache1MemSize(void *p){
  34926. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  34927. return pcache1.szSlot;
  34928. }else{
  34929. int iSize;
  34930. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  34931. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  34932. iSize = sqlite3MallocSize(p);
  34933. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  34934. return iSize;
  34935. }
  34936. }
  34937. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  34938. /*
  34939. ** Allocate a new page object initially associated with cache pCache.
  34940. */
  34941. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  34942. PgHdr1 *p = 0;
  34943. void *pPg;
  34944. /* The group mutex must be released before pcache1Alloc() is called. This
  34945. ** is because it may call sqlite3_release_memory(), which assumes that
  34946. ** this mutex is not held. */
  34947. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  34948. pcache1LeaveMutex(pCache->pGroup);
  34949. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  34950. pPg = pcache1Alloc(pCache->szPage);
  34951. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  34952. if( !pPg || !p ){
  34953. pcache1Free(pPg);
  34954. sqlite3_free(p);
  34955. pPg = 0;
  34956. }
  34957. #else
  34958. pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
  34959. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  34960. #endif
  34961. pcache1EnterMutex(pCache->pGroup);
  34962. if( pPg ){
  34963. p->page.pBuf = pPg;
  34964. p->page.pExtra = &p[1];
  34965. if( pCache->bPurgeable ){
  34966. pCache->pGroup->nCurrentPage++;
  34967. }
  34968. return p;
  34969. }
  34970. return 0;
  34971. }
  34972. /*
  34973. ** Free a page object allocated by pcache1AllocPage().
  34974. **
  34975. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  34976. ** that the current implementation happens to never call this routine
  34977. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  34978. */
  34979. static void pcache1FreePage(PgHdr1 *p){
  34980. if( ALWAYS(p) ){
  34981. PCache1 *pCache = p->pCache;
  34982. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  34983. pcache1Free(p->page.pBuf);
  34984. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  34985. sqlite3_free(p);
  34986. #endif
  34987. if( pCache->bPurgeable ){
  34988. pCache->pGroup->nCurrentPage--;
  34989. }
  34990. }
  34991. }
  34992. /*
  34993. ** Malloc function used by SQLite to obtain space from the buffer configured
  34994. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  34995. ** exists, this function falls back to sqlite3Malloc().
  34996. */
  34997. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  34998. return pcache1Alloc(sz);
  34999. }
  35000. /*
  35001. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  35002. */
  35003. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  35004. pcache1Free(p);
  35005. }
  35006. /*
  35007. ** Return true if it desirable to avoid allocating a new page cache
  35008. ** entry.
  35009. **
  35010. ** If memory was allocated specifically to the page cache using
  35011. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  35012. ** it is desirable to avoid allocating a new page cache entry because
  35013. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  35014. ** for all page cache needs and we should not need to spill the
  35015. ** allocation onto the heap.
  35016. **
  35017. ** Or, the heap is used for all page cache memory but the heap is
  35018. ** under memory pressure, then again it is desirable to avoid
  35019. ** allocating a new page cache entry in order to avoid stressing
  35020. ** the heap even further.
  35021. */
  35022. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  35023. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  35024. return pcache1.bUnderPressure;
  35025. }else{
  35026. return sqlite3HeapNearlyFull();
  35027. }
  35028. }
  35029. /******************************************************************************/
  35030. /******** General Implementation Functions ************************************/
  35031. /*
  35032. ** This function is used to resize the hash table used by the cache passed
  35033. ** as the first argument.
  35034. **
  35035. ** The PCache mutex must be held when this function is called.
  35036. */
  35037. static int pcache1ResizeHash(PCache1 *p){
  35038. PgHdr1 **apNew;
  35039. unsigned int nNew;
  35040. unsigned int i;
  35041. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  35042. nNew = p->nHash*2;
  35043. if( nNew<256 ){
  35044. nNew = 256;
  35045. }
  35046. pcache1LeaveMutex(p->pGroup);
  35047. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  35048. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  35049. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  35050. pcache1EnterMutex(p->pGroup);
  35051. if( apNew ){
  35052. for(i=0; i<p->nHash; i++){
  35053. PgHdr1 *pPage;
  35054. PgHdr1 *pNext = p->apHash[i];
  35055. while( (pPage = pNext)!=0 ){
  35056. unsigned int h = pPage->iKey % nNew;
  35057. pNext = pPage->pNext;
  35058. pPage->pNext = apNew[h];
  35059. apNew[h] = pPage;
  35060. }
  35061. }
  35062. sqlite3_free(p->apHash);
  35063. p->apHash = apNew;
  35064. p->nHash = nNew;
  35065. }
  35066. return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
  35067. }
  35068. /*
  35069. ** This function is used internally to remove the page pPage from the
  35070. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  35071. ** LRU list, then this function is a no-op.
  35072. **
  35073. ** The PGroup mutex must be held when this function is called.
  35074. **
  35075. ** If pPage is NULL then this routine is a no-op.
  35076. */
  35077. static void pcache1PinPage(PgHdr1 *pPage){
  35078. PCache1 *pCache;
  35079. PGroup *pGroup;
  35080. if( pPage==0 ) return;
  35081. pCache = pPage->pCache;
  35082. pGroup = pCache->pGroup;
  35083. assert( sqlite3_mutex_held(pGroup->mutex) );
  35084. if( pPage->pLruNext || pPage==pGroup->pLruTail ){
  35085. if( pPage->pLruPrev ){
  35086. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  35087. }
  35088. if( pPage->pLruNext ){
  35089. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  35090. }
  35091. if( pGroup->pLruHead==pPage ){
  35092. pGroup->pLruHead = pPage->pLruNext;
  35093. }
  35094. if( pGroup->pLruTail==pPage ){
  35095. pGroup->pLruTail = pPage->pLruPrev;
  35096. }
  35097. pPage->pLruNext = 0;
  35098. pPage->pLruPrev = 0;
  35099. pPage->pCache->nRecyclable--;
  35100. }
  35101. }
  35102. /*
  35103. ** Remove the page supplied as an argument from the hash table
  35104. ** (PCache1.apHash structure) that it is currently stored in.
  35105. **
  35106. ** The PGroup mutex must be held when this function is called.
  35107. */
  35108. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  35109. unsigned int h;
  35110. PCache1 *pCache = pPage->pCache;
  35111. PgHdr1 **pp;
  35112. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  35113. h = pPage->iKey % pCache->nHash;
  35114. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  35115. *pp = (*pp)->pNext;
  35116. pCache->nPage--;
  35117. }
  35118. /*
  35119. ** If there are currently more than nMaxPage pages allocated, try
  35120. ** to recycle pages to reduce the number allocated to nMaxPage.
  35121. */
  35122. static void pcache1EnforceMaxPage(PGroup *pGroup){
  35123. assert( sqlite3_mutex_held(pGroup->mutex) );
  35124. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  35125. PgHdr1 *p = pGroup->pLruTail;
  35126. assert( p->pCache->pGroup==pGroup );
  35127. pcache1PinPage(p);
  35128. pcache1RemoveFromHash(p);
  35129. pcache1FreePage(p);
  35130. }
  35131. }
  35132. /*
  35133. ** Discard all pages from cache pCache with a page number (key value)
  35134. ** greater than or equal to iLimit. Any pinned pages that meet this
  35135. ** criteria are unpinned before they are discarded.
  35136. **
  35137. ** The PCache mutex must be held when this function is called.
  35138. */
  35139. static void pcache1TruncateUnsafe(
  35140. PCache1 *pCache, /* The cache to truncate */
  35141. unsigned int iLimit /* Drop pages with this pgno or larger */
  35142. ){
  35143. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  35144. unsigned int h;
  35145. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  35146. for(h=0; h<pCache->nHash; h++){
  35147. PgHdr1 **pp = &pCache->apHash[h];
  35148. PgHdr1 *pPage;
  35149. while( (pPage = *pp)!=0 ){
  35150. if( pPage->iKey>=iLimit ){
  35151. pCache->nPage--;
  35152. *pp = pPage->pNext;
  35153. pcache1PinPage(pPage);
  35154. pcache1FreePage(pPage);
  35155. }else{
  35156. pp = &pPage->pNext;
  35157. TESTONLY( nPage++; )
  35158. }
  35159. }
  35160. }
  35161. assert( pCache->nPage==nPage );
  35162. }
  35163. /******************************************************************************/
  35164. /******** sqlite3_pcache Methods **********************************************/
  35165. /*
  35166. ** Implementation of the sqlite3_pcache.xInit method.
  35167. */
  35168. static int pcache1Init(void *NotUsed){
  35169. UNUSED_PARAMETER(NotUsed);
  35170. assert( pcache1.isInit==0 );
  35171. memset(&pcache1, 0, sizeof(pcache1));
  35172. if( sqlite3GlobalConfig.bCoreMutex ){
  35173. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  35174. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  35175. }
  35176. pcache1.grp.mxPinned = 10;
  35177. pcache1.isInit = 1;
  35178. return SQLITE_OK;
  35179. }
  35180. /*
  35181. ** Implementation of the sqlite3_pcache.xShutdown method.
  35182. ** Note that the static mutex allocated in xInit does
  35183. ** not need to be freed.
  35184. */
  35185. static void pcache1Shutdown(void *NotUsed){
  35186. UNUSED_PARAMETER(NotUsed);
  35187. assert( pcache1.isInit!=0 );
  35188. memset(&pcache1, 0, sizeof(pcache1));
  35189. }
  35190. /*
  35191. ** Implementation of the sqlite3_pcache.xCreate method.
  35192. **
  35193. ** Allocate a new cache.
  35194. */
  35195. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  35196. PCache1 *pCache; /* The newly created page cache */
  35197. PGroup *pGroup; /* The group the new page cache will belong to */
  35198. int sz; /* Bytes of memory required to allocate the new cache */
  35199. /*
  35200. ** The separateCache variable is true if each PCache has its own private
  35201. ** PGroup. In other words, separateCache is true for mode (1) where no
  35202. ** mutexing is required.
  35203. **
  35204. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  35205. **
  35206. ** * Always use a unified cache in single-threaded applications
  35207. **
  35208. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  35209. ** use separate caches (mode-1)
  35210. */
  35211. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  35212. const int separateCache = 0;
  35213. #else
  35214. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  35215. #endif
  35216. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  35217. assert( szExtra < 300 );
  35218. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  35219. pCache = (PCache1 *)sqlite3MallocZero(sz);
  35220. if( pCache ){
  35221. if( separateCache ){
  35222. pGroup = (PGroup*)&pCache[1];
  35223. pGroup->mxPinned = 10;
  35224. }else{
  35225. pGroup = &pcache1.grp;
  35226. }
  35227. pCache->pGroup = pGroup;
  35228. pCache->szPage = szPage;
  35229. pCache->szExtra = szExtra;
  35230. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  35231. if( bPurgeable ){
  35232. pCache->nMin = 10;
  35233. pcache1EnterMutex(pGroup);
  35234. pGroup->nMinPage += pCache->nMin;
  35235. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  35236. pcache1LeaveMutex(pGroup);
  35237. }
  35238. }
  35239. return (sqlite3_pcache *)pCache;
  35240. }
  35241. /*
  35242. ** Implementation of the sqlite3_pcache.xCachesize method.
  35243. **
  35244. ** Configure the cache_size limit for a cache.
  35245. */
  35246. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  35247. PCache1 *pCache = (PCache1 *)p;
  35248. if( pCache->bPurgeable ){
  35249. PGroup *pGroup = pCache->pGroup;
  35250. pcache1EnterMutex(pGroup);
  35251. pGroup->nMaxPage += (nMax - pCache->nMax);
  35252. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  35253. pCache->nMax = nMax;
  35254. pCache->n90pct = pCache->nMax*9/10;
  35255. pcache1EnforceMaxPage(pGroup);
  35256. pcache1LeaveMutex(pGroup);
  35257. }
  35258. }
  35259. /*
  35260. ** Implementation of the sqlite3_pcache.xShrink method.
  35261. **
  35262. ** Free up as much memory as possible.
  35263. */
  35264. static void pcache1Shrink(sqlite3_pcache *p){
  35265. PCache1 *pCache = (PCache1*)p;
  35266. if( pCache->bPurgeable ){
  35267. PGroup *pGroup = pCache->pGroup;
  35268. int savedMaxPage;
  35269. pcache1EnterMutex(pGroup);
  35270. savedMaxPage = pGroup->nMaxPage;
  35271. pGroup->nMaxPage = 0;
  35272. pcache1EnforceMaxPage(pGroup);
  35273. pGroup->nMaxPage = savedMaxPage;
  35274. pcache1LeaveMutex(pGroup);
  35275. }
  35276. }
  35277. /*
  35278. ** Implementation of the sqlite3_pcache.xPagecount method.
  35279. */
  35280. static int pcache1Pagecount(sqlite3_pcache *p){
  35281. int n;
  35282. PCache1 *pCache = (PCache1*)p;
  35283. pcache1EnterMutex(pCache->pGroup);
  35284. n = pCache->nPage;
  35285. pcache1LeaveMutex(pCache->pGroup);
  35286. return n;
  35287. }
  35288. /*
  35289. ** Implementation of the sqlite3_pcache.xFetch method.
  35290. **
  35291. ** Fetch a page by key value.
  35292. **
  35293. ** Whether or not a new page may be allocated by this function depends on
  35294. ** the value of the createFlag argument. 0 means do not allocate a new
  35295. ** page. 1 means allocate a new page if space is easily available. 2
  35296. ** means to try really hard to allocate a new page.
  35297. **
  35298. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  35299. ** database) there is really no difference between createFlag 1 and 2. So
  35300. ** the calling function (pcache.c) will never have a createFlag of 1 on
  35301. ** a non-purgeable cache.
  35302. **
  35303. ** There are three different approaches to obtaining space for a page,
  35304. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  35305. **
  35306. ** 1. Regardless of the value of createFlag, the cache is searched for a
  35307. ** copy of the requested page. If one is found, it is returned.
  35308. **
  35309. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  35310. ** returned.
  35311. **
  35312. ** 3. If createFlag is 1, and the page is not already in the cache, then
  35313. ** return NULL (do not allocate a new page) if any of the following
  35314. ** conditions are true:
  35315. **
  35316. ** (a) the number of pages pinned by the cache is greater than
  35317. ** PCache1.nMax, or
  35318. **
  35319. ** (b) the number of pages pinned by the cache is greater than
  35320. ** the sum of nMax for all purgeable caches, less the sum of
  35321. ** nMin for all other purgeable caches, or
  35322. **
  35323. ** 4. If none of the first three conditions apply and the cache is marked
  35324. ** as purgeable, and if one of the following is true:
  35325. **
  35326. ** (a) The number of pages allocated for the cache is already
  35327. ** PCache1.nMax, or
  35328. **
  35329. ** (b) The number of pages allocated for all purgeable caches is
  35330. ** already equal to or greater than the sum of nMax for all
  35331. ** purgeable caches,
  35332. **
  35333. ** (c) The system is under memory pressure and wants to avoid
  35334. ** unnecessary pages cache entry allocations
  35335. **
  35336. ** then attempt to recycle a page from the LRU list. If it is the right
  35337. ** size, return the recycled buffer. Otherwise, free the buffer and
  35338. ** proceed to step 5.
  35339. **
  35340. ** 5. Otherwise, allocate and return a new page buffer.
  35341. */
  35342. static sqlite3_pcache_page *pcache1Fetch(
  35343. sqlite3_pcache *p,
  35344. unsigned int iKey,
  35345. int createFlag
  35346. ){
  35347. unsigned int nPinned;
  35348. PCache1 *pCache = (PCache1 *)p;
  35349. PGroup *pGroup;
  35350. PgHdr1 *pPage = 0;
  35351. assert( pCache->bPurgeable || createFlag!=1 );
  35352. assert( pCache->bPurgeable || pCache->nMin==0 );
  35353. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  35354. assert( pCache->nMin==0 || pCache->bPurgeable );
  35355. pcache1EnterMutex(pGroup = pCache->pGroup);
  35356. /* Step 1: Search the hash table for an existing entry. */
  35357. if( pCache->nHash>0 ){
  35358. unsigned int h = iKey % pCache->nHash;
  35359. for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  35360. }
  35361. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  35362. if( pPage || createFlag==0 ){
  35363. pcache1PinPage(pPage);
  35364. goto fetch_out;
  35365. }
  35366. /* The pGroup local variable will normally be initialized by the
  35367. ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
  35368. ** then pcache1EnterMutex() is a no-op, so we have to initialize the
  35369. ** local variable here. Delaying the initialization of pGroup is an
  35370. ** optimization: The common case is to exit the module before reaching
  35371. ** this point.
  35372. */
  35373. #ifdef SQLITE_MUTEX_OMIT
  35374. pGroup = pCache->pGroup;
  35375. #endif
  35376. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  35377. assert( pCache->nPage >= pCache->nRecyclable );
  35378. nPinned = pCache->nPage - pCache->nRecyclable;
  35379. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  35380. assert( pCache->n90pct == pCache->nMax*9/10 );
  35381. if( createFlag==1 && (
  35382. nPinned>=pGroup->mxPinned
  35383. || nPinned>=pCache->n90pct
  35384. || pcache1UnderMemoryPressure(pCache)
  35385. )){
  35386. goto fetch_out;
  35387. }
  35388. if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
  35389. goto fetch_out;
  35390. }
  35391. assert( pCache->nHash>0 && pCache->apHash );
  35392. /* Step 4. Try to recycle a page. */
  35393. if( pCache->bPurgeable && pGroup->pLruTail && (
  35394. (pCache->nPage+1>=pCache->nMax)
  35395. || pGroup->nCurrentPage>=pGroup->nMaxPage
  35396. || pcache1UnderMemoryPressure(pCache)
  35397. )){
  35398. PCache1 *pOther;
  35399. pPage = pGroup->pLruTail;
  35400. pcache1RemoveFromHash(pPage);
  35401. pcache1PinPage(pPage);
  35402. pOther = pPage->pCache;
  35403. /* We want to verify that szPage and szExtra are the same for pOther
  35404. ** and pCache. Assert that we can verify this by comparing sums. */
  35405. assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
  35406. assert( pCache->szExtra<512 );
  35407. assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
  35408. assert( pOther->szExtra<512 );
  35409. if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
  35410. pcache1FreePage(pPage);
  35411. pPage = 0;
  35412. }else{
  35413. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  35414. }
  35415. }
  35416. /* Step 5. If a usable page buffer has still not been found,
  35417. ** attempt to allocate a new one.
  35418. */
  35419. if( !pPage ){
  35420. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  35421. pPage = pcache1AllocPage(pCache);
  35422. if( createFlag==1 ) sqlite3EndBenignMalloc();
  35423. }
  35424. if( pPage ){
  35425. unsigned int h = iKey % pCache->nHash;
  35426. pCache->nPage++;
  35427. pPage->iKey = iKey;
  35428. pPage->pNext = pCache->apHash[h];
  35429. pPage->pCache = pCache;
  35430. pPage->pLruPrev = 0;
  35431. pPage->pLruNext = 0;
  35432. *(void **)pPage->page.pExtra = 0;
  35433. pCache->apHash[h] = pPage;
  35434. }
  35435. fetch_out:
  35436. if( pPage && iKey>pCache->iMaxKey ){
  35437. pCache->iMaxKey = iKey;
  35438. }
  35439. pcache1LeaveMutex(pGroup);
  35440. return &pPage->page;
  35441. }
  35442. /*
  35443. ** Implementation of the sqlite3_pcache.xUnpin method.
  35444. **
  35445. ** Mark a page as unpinned (eligible for asynchronous recycling).
  35446. */
  35447. static void pcache1Unpin(
  35448. sqlite3_pcache *p,
  35449. sqlite3_pcache_page *pPg,
  35450. int reuseUnlikely
  35451. ){
  35452. PCache1 *pCache = (PCache1 *)p;
  35453. PgHdr1 *pPage = (PgHdr1 *)pPg;
  35454. PGroup *pGroup = pCache->pGroup;
  35455. assert( pPage->pCache==pCache );
  35456. pcache1EnterMutex(pGroup);
  35457. /* It is an error to call this function if the page is already
  35458. ** part of the PGroup LRU list.
  35459. */
  35460. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  35461. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  35462. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  35463. pcache1RemoveFromHash(pPage);
  35464. pcache1FreePage(pPage);
  35465. }else{
  35466. /* Add the page to the PGroup LRU list. */
  35467. if( pGroup->pLruHead ){
  35468. pGroup->pLruHead->pLruPrev = pPage;
  35469. pPage->pLruNext = pGroup->pLruHead;
  35470. pGroup->pLruHead = pPage;
  35471. }else{
  35472. pGroup->pLruTail = pPage;
  35473. pGroup->pLruHead = pPage;
  35474. }
  35475. pCache->nRecyclable++;
  35476. }
  35477. pcache1LeaveMutex(pCache->pGroup);
  35478. }
  35479. /*
  35480. ** Implementation of the sqlite3_pcache.xRekey method.
  35481. */
  35482. static void pcache1Rekey(
  35483. sqlite3_pcache *p,
  35484. sqlite3_pcache_page *pPg,
  35485. unsigned int iOld,
  35486. unsigned int iNew
  35487. ){
  35488. PCache1 *pCache = (PCache1 *)p;
  35489. PgHdr1 *pPage = (PgHdr1 *)pPg;
  35490. PgHdr1 **pp;
  35491. unsigned int h;
  35492. assert( pPage->iKey==iOld );
  35493. assert( pPage->pCache==pCache );
  35494. pcache1EnterMutex(pCache->pGroup);
  35495. h = iOld%pCache->nHash;
  35496. pp = &pCache->apHash[h];
  35497. while( (*pp)!=pPage ){
  35498. pp = &(*pp)->pNext;
  35499. }
  35500. *pp = pPage->pNext;
  35501. h = iNew%pCache->nHash;
  35502. pPage->iKey = iNew;
  35503. pPage->pNext = pCache->apHash[h];
  35504. pCache->apHash[h] = pPage;
  35505. if( iNew>pCache->iMaxKey ){
  35506. pCache->iMaxKey = iNew;
  35507. }
  35508. pcache1LeaveMutex(pCache->pGroup);
  35509. }
  35510. /*
  35511. ** Implementation of the sqlite3_pcache.xTruncate method.
  35512. **
  35513. ** Discard all unpinned pages in the cache with a page number equal to
  35514. ** or greater than parameter iLimit. Any pinned pages with a page number
  35515. ** equal to or greater than iLimit are implicitly unpinned.
  35516. */
  35517. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  35518. PCache1 *pCache = (PCache1 *)p;
  35519. pcache1EnterMutex(pCache->pGroup);
  35520. if( iLimit<=pCache->iMaxKey ){
  35521. pcache1TruncateUnsafe(pCache, iLimit);
  35522. pCache->iMaxKey = iLimit-1;
  35523. }
  35524. pcache1LeaveMutex(pCache->pGroup);
  35525. }
  35526. /*
  35527. ** Implementation of the sqlite3_pcache.xDestroy method.
  35528. **
  35529. ** Destroy a cache allocated using pcache1Create().
  35530. */
  35531. static void pcache1Destroy(sqlite3_pcache *p){
  35532. PCache1 *pCache = (PCache1 *)p;
  35533. PGroup *pGroup = pCache->pGroup;
  35534. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  35535. pcache1EnterMutex(pGroup);
  35536. pcache1TruncateUnsafe(pCache, 0);
  35537. assert( pGroup->nMaxPage >= pCache->nMax );
  35538. pGroup->nMaxPage -= pCache->nMax;
  35539. assert( pGroup->nMinPage >= pCache->nMin );
  35540. pGroup->nMinPage -= pCache->nMin;
  35541. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  35542. pcache1EnforceMaxPage(pGroup);
  35543. pcache1LeaveMutex(pGroup);
  35544. sqlite3_free(pCache->apHash);
  35545. sqlite3_free(pCache);
  35546. }
  35547. /*
  35548. ** This function is called during initialization (sqlite3_initialize()) to
  35549. ** install the default pluggable cache module, assuming the user has not
  35550. ** already provided an alternative.
  35551. */
  35552. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  35553. static const sqlite3_pcache_methods2 defaultMethods = {
  35554. 1, /* iVersion */
  35555. 0, /* pArg */
  35556. pcache1Init, /* xInit */
  35557. pcache1Shutdown, /* xShutdown */
  35558. pcache1Create, /* xCreate */
  35559. pcache1Cachesize, /* xCachesize */
  35560. pcache1Pagecount, /* xPagecount */
  35561. pcache1Fetch, /* xFetch */
  35562. pcache1Unpin, /* xUnpin */
  35563. pcache1Rekey, /* xRekey */
  35564. pcache1Truncate, /* xTruncate */
  35565. pcache1Destroy, /* xDestroy */
  35566. pcache1Shrink /* xShrink */
  35567. };
  35568. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  35569. }
  35570. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  35571. /*
  35572. ** This function is called to free superfluous dynamically allocated memory
  35573. ** held by the pager system. Memory in use by any SQLite pager allocated
  35574. ** by the current thread may be sqlite3_free()ed.
  35575. **
  35576. ** nReq is the number of bytes of memory required. Once this much has
  35577. ** been released, the function returns. The return value is the total number
  35578. ** of bytes of memory released.
  35579. */
  35580. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  35581. int nFree = 0;
  35582. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  35583. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  35584. if( pcache1.pStart==0 ){
  35585. PgHdr1 *p;
  35586. pcache1EnterMutex(&pcache1.grp);
  35587. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  35588. nFree += pcache1MemSize(p->page.pBuf);
  35589. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  35590. nFree += sqlite3MemSize(p);
  35591. #endif
  35592. pcache1PinPage(p);
  35593. pcache1RemoveFromHash(p);
  35594. pcache1FreePage(p);
  35595. }
  35596. pcache1LeaveMutex(&pcache1.grp);
  35597. }
  35598. return nFree;
  35599. }
  35600. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  35601. #ifdef SQLITE_TEST
  35602. /*
  35603. ** This function is used by test procedures to inspect the internal state
  35604. ** of the global cache.
  35605. */
  35606. SQLITE_PRIVATE void sqlite3PcacheStats(
  35607. int *pnCurrent, /* OUT: Total number of pages cached */
  35608. int *pnMax, /* OUT: Global maximum cache size */
  35609. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  35610. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  35611. ){
  35612. PgHdr1 *p;
  35613. int nRecyclable = 0;
  35614. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  35615. nRecyclable++;
  35616. }
  35617. *pnCurrent = pcache1.grp.nCurrentPage;
  35618. *pnMax = (int)pcache1.grp.nMaxPage;
  35619. *pnMin = (int)pcache1.grp.nMinPage;
  35620. *pnRecyclable = nRecyclable;
  35621. }
  35622. #endif
  35623. /************** End of pcache1.c *********************************************/
  35624. /************** Begin file rowset.c ******************************************/
  35625. /*
  35626. ** 2008 December 3
  35627. **
  35628. ** The author disclaims copyright to this source code. In place of
  35629. ** a legal notice, here is a blessing:
  35630. **
  35631. ** May you do good and not evil.
  35632. ** May you find forgiveness for yourself and forgive others.
  35633. ** May you share freely, never taking more than you give.
  35634. **
  35635. *************************************************************************
  35636. **
  35637. ** This module implements an object we call a "RowSet".
  35638. **
  35639. ** The RowSet object is a collection of rowids. Rowids
  35640. ** are inserted into the RowSet in an arbitrary order. Inserts
  35641. ** can be intermixed with tests to see if a given rowid has been
  35642. ** previously inserted into the RowSet.
  35643. **
  35644. ** After all inserts are finished, it is possible to extract the
  35645. ** elements of the RowSet in sorted order. Once this extraction
  35646. ** process has started, no new elements may be inserted.
  35647. **
  35648. ** Hence, the primitive operations for a RowSet are:
  35649. **
  35650. ** CREATE
  35651. ** INSERT
  35652. ** TEST
  35653. ** SMALLEST
  35654. ** DESTROY
  35655. **
  35656. ** The CREATE and DESTROY primitives are the constructor and destructor,
  35657. ** obviously. The INSERT primitive adds a new element to the RowSet.
  35658. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  35659. ** extracts the least value from the RowSet.
  35660. **
  35661. ** The INSERT primitive might allocate additional memory. Memory is
  35662. ** allocated in chunks so most INSERTs do no allocation. There is an
  35663. ** upper bound on the size of allocated memory. No memory is freed
  35664. ** until DESTROY.
  35665. **
  35666. ** The TEST primitive includes a "batch" number. The TEST primitive
  35667. ** will only see elements that were inserted before the last change
  35668. ** in the batch number. In other words, if an INSERT occurs between
  35669. ** two TESTs where the TESTs have the same batch nubmer, then the
  35670. ** value added by the INSERT will not be visible to the second TEST.
  35671. ** The initial batch number is zero, so if the very first TEST contains
  35672. ** a non-zero batch number, it will see all prior INSERTs.
  35673. **
  35674. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  35675. ** that is attempted.
  35676. **
  35677. ** The cost of an INSERT is roughly constant. (Sometime new memory
  35678. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  35679. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  35680. ** The cost of a TEST using the same batch number is O(logN). The cost
  35681. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  35682. ** primitives are constant time. The cost of DESTROY is O(N).
  35683. **
  35684. ** There is an added cost of O(N) when switching between TEST and
  35685. ** SMALLEST primitives.
  35686. */
  35687. /*
  35688. ** Target size for allocation chunks.
  35689. */
  35690. #define ROWSET_ALLOCATION_SIZE 1024
  35691. /*
  35692. ** The number of rowset entries per allocation chunk.
  35693. */
  35694. #define ROWSET_ENTRY_PER_CHUNK \
  35695. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  35696. /*
  35697. ** Each entry in a RowSet is an instance of the following object.
  35698. **
  35699. ** This same object is reused to store a linked list of trees of RowSetEntry
  35700. ** objects. In that alternative use, pRight points to the next entry
  35701. ** in the list, pLeft points to the tree, and v is unused. The
  35702. ** RowSet.pForest value points to the head of this forest list.
  35703. */
  35704. struct RowSetEntry {
  35705. i64 v; /* ROWID value for this entry */
  35706. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  35707. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  35708. };
  35709. /*
  35710. ** RowSetEntry objects are allocated in large chunks (instances of the
  35711. ** following structure) to reduce memory allocation overhead. The
  35712. ** chunks are kept on a linked list so that they can be deallocated
  35713. ** when the RowSet is destroyed.
  35714. */
  35715. struct RowSetChunk {
  35716. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  35717. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  35718. };
  35719. /*
  35720. ** A RowSet in an instance of the following structure.
  35721. **
  35722. ** A typedef of this structure if found in sqliteInt.h.
  35723. */
  35724. struct RowSet {
  35725. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  35726. sqlite3 *db; /* The database connection */
  35727. struct RowSetEntry *pEntry; /* List of entries using pRight */
  35728. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  35729. struct RowSetEntry *pFresh; /* Source of new entry objects */
  35730. struct RowSetEntry *pForest; /* List of binary trees of entries */
  35731. u16 nFresh; /* Number of objects on pFresh */
  35732. u8 rsFlags; /* Various flags */
  35733. u8 iBatch; /* Current insert batch */
  35734. };
  35735. /*
  35736. ** Allowed values for RowSet.rsFlags
  35737. */
  35738. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  35739. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  35740. /*
  35741. ** Turn bulk memory into a RowSet object. N bytes of memory
  35742. ** are available at pSpace. The db pointer is used as a memory context
  35743. ** for any subsequent allocations that need to occur.
  35744. ** Return a pointer to the new RowSet object.
  35745. **
  35746. ** It must be the case that N is sufficient to make a Rowset. If not
  35747. ** an assertion fault occurs.
  35748. **
  35749. ** If N is larger than the minimum, use the surplus as an initial
  35750. ** allocation of entries available to be filled.
  35751. */
  35752. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  35753. RowSet *p;
  35754. assert( N >= ROUND8(sizeof(*p)) );
  35755. p = pSpace;
  35756. p->pChunk = 0;
  35757. p->db = db;
  35758. p->pEntry = 0;
  35759. p->pLast = 0;
  35760. p->pForest = 0;
  35761. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  35762. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  35763. p->rsFlags = ROWSET_SORTED;
  35764. p->iBatch = 0;
  35765. return p;
  35766. }
  35767. /*
  35768. ** Deallocate all chunks from a RowSet. This frees all memory that
  35769. ** the RowSet has allocated over its lifetime. This routine is
  35770. ** the destructor for the RowSet.
  35771. */
  35772. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  35773. struct RowSetChunk *pChunk, *pNextChunk;
  35774. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  35775. pNextChunk = pChunk->pNextChunk;
  35776. sqlite3DbFree(p->db, pChunk);
  35777. }
  35778. p->pChunk = 0;
  35779. p->nFresh = 0;
  35780. p->pEntry = 0;
  35781. p->pLast = 0;
  35782. p->pForest = 0;
  35783. p->rsFlags = ROWSET_SORTED;
  35784. }
  35785. /*
  35786. ** Allocate a new RowSetEntry object that is associated with the
  35787. ** given RowSet. Return a pointer to the new and completely uninitialized
  35788. ** objected.
  35789. **
  35790. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  35791. ** routine returns NULL.
  35792. */
  35793. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  35794. assert( p!=0 );
  35795. if( p->nFresh==0 ){
  35796. struct RowSetChunk *pNew;
  35797. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  35798. if( pNew==0 ){
  35799. return 0;
  35800. }
  35801. pNew->pNextChunk = p->pChunk;
  35802. p->pChunk = pNew;
  35803. p->pFresh = pNew->aEntry;
  35804. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  35805. }
  35806. p->nFresh--;
  35807. return p->pFresh++;
  35808. }
  35809. /*
  35810. ** Insert a new value into a RowSet.
  35811. **
  35812. ** The mallocFailed flag of the database connection is set if a
  35813. ** memory allocation fails.
  35814. */
  35815. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  35816. struct RowSetEntry *pEntry; /* The new entry */
  35817. struct RowSetEntry *pLast; /* The last prior entry */
  35818. /* This routine is never called after sqlite3RowSetNext() */
  35819. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  35820. pEntry = rowSetEntryAlloc(p);
  35821. if( pEntry==0 ) return;
  35822. pEntry->v = rowid;
  35823. pEntry->pRight = 0;
  35824. pLast = p->pLast;
  35825. if( pLast ){
  35826. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  35827. p->rsFlags &= ~ROWSET_SORTED;
  35828. }
  35829. pLast->pRight = pEntry;
  35830. }else{
  35831. p->pEntry = pEntry;
  35832. }
  35833. p->pLast = pEntry;
  35834. }
  35835. /*
  35836. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  35837. **
  35838. ** The input lists are connected via pRight pointers and are
  35839. ** assumed to each already be in sorted order.
  35840. */
  35841. static struct RowSetEntry *rowSetEntryMerge(
  35842. struct RowSetEntry *pA, /* First sorted list to be merged */
  35843. struct RowSetEntry *pB /* Second sorted list to be merged */
  35844. ){
  35845. struct RowSetEntry head;
  35846. struct RowSetEntry *pTail;
  35847. pTail = &head;
  35848. while( pA && pB ){
  35849. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  35850. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  35851. if( pA->v<pB->v ){
  35852. pTail->pRight = pA;
  35853. pA = pA->pRight;
  35854. pTail = pTail->pRight;
  35855. }else if( pB->v<pA->v ){
  35856. pTail->pRight = pB;
  35857. pB = pB->pRight;
  35858. pTail = pTail->pRight;
  35859. }else{
  35860. pA = pA->pRight;
  35861. }
  35862. }
  35863. if( pA ){
  35864. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  35865. pTail->pRight = pA;
  35866. }else{
  35867. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  35868. pTail->pRight = pB;
  35869. }
  35870. return head.pRight;
  35871. }
  35872. /*
  35873. ** Sort all elements on the list of RowSetEntry objects into order of
  35874. ** increasing v.
  35875. */
  35876. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  35877. unsigned int i;
  35878. struct RowSetEntry *pNext, *aBucket[40];
  35879. memset(aBucket, 0, sizeof(aBucket));
  35880. while( pIn ){
  35881. pNext = pIn->pRight;
  35882. pIn->pRight = 0;
  35883. for(i=0; aBucket[i]; i++){
  35884. pIn = rowSetEntryMerge(aBucket[i], pIn);
  35885. aBucket[i] = 0;
  35886. }
  35887. aBucket[i] = pIn;
  35888. pIn = pNext;
  35889. }
  35890. pIn = 0;
  35891. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  35892. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  35893. }
  35894. return pIn;
  35895. }
  35896. /*
  35897. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  35898. ** Convert this tree into a linked list connected by the pRight pointers
  35899. ** and return pointers to the first and last elements of the new list.
  35900. */
  35901. static void rowSetTreeToList(
  35902. struct RowSetEntry *pIn, /* Root of the input tree */
  35903. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  35904. struct RowSetEntry **ppLast /* Write tail of the output list here */
  35905. ){
  35906. assert( pIn!=0 );
  35907. if( pIn->pLeft ){
  35908. struct RowSetEntry *p;
  35909. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  35910. p->pRight = pIn;
  35911. }else{
  35912. *ppFirst = pIn;
  35913. }
  35914. if( pIn->pRight ){
  35915. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  35916. }else{
  35917. *ppLast = pIn;
  35918. }
  35919. assert( (*ppLast)->pRight==0 );
  35920. }
  35921. /*
  35922. ** Convert a sorted list of elements (connected by pRight) into a binary
  35923. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  35924. ** node taken from the head of *ppList. A depth of 2 means a tree with
  35925. ** three nodes. And so forth.
  35926. **
  35927. ** Use as many entries from the input list as required and update the
  35928. ** *ppList to point to the unused elements of the list. If the input
  35929. ** list contains too few elements, then construct an incomplete tree
  35930. ** and leave *ppList set to NULL.
  35931. **
  35932. ** Return a pointer to the root of the constructed binary tree.
  35933. */
  35934. static struct RowSetEntry *rowSetNDeepTree(
  35935. struct RowSetEntry **ppList,
  35936. int iDepth
  35937. ){
  35938. struct RowSetEntry *p; /* Root of the new tree */
  35939. struct RowSetEntry *pLeft; /* Left subtree */
  35940. if( *ppList==0 ){
  35941. return 0;
  35942. }
  35943. if( iDepth==1 ){
  35944. p = *ppList;
  35945. *ppList = p->pRight;
  35946. p->pLeft = p->pRight = 0;
  35947. return p;
  35948. }
  35949. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  35950. p = *ppList;
  35951. if( p==0 ){
  35952. return pLeft;
  35953. }
  35954. p->pLeft = pLeft;
  35955. *ppList = p->pRight;
  35956. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  35957. return p;
  35958. }
  35959. /*
  35960. ** Convert a sorted list of elements into a binary tree. Make the tree
  35961. ** as deep as it needs to be in order to contain the entire list.
  35962. */
  35963. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  35964. int iDepth; /* Depth of the tree so far */
  35965. struct RowSetEntry *p; /* Current tree root */
  35966. struct RowSetEntry *pLeft; /* Left subtree */
  35967. assert( pList!=0 );
  35968. p = pList;
  35969. pList = p->pRight;
  35970. p->pLeft = p->pRight = 0;
  35971. for(iDepth=1; pList; iDepth++){
  35972. pLeft = p;
  35973. p = pList;
  35974. pList = p->pRight;
  35975. p->pLeft = pLeft;
  35976. p->pRight = rowSetNDeepTree(&pList, iDepth);
  35977. }
  35978. return p;
  35979. }
  35980. /*
  35981. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  35982. ** sort them all together into one big ordered list on p->pEntry.
  35983. **
  35984. ** This routine should only be called once in the life of a RowSet.
  35985. */
  35986. static void rowSetToList(RowSet *p){
  35987. /* This routine is called only once */
  35988. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  35989. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  35990. p->pEntry = rowSetEntrySort(p->pEntry);
  35991. }
  35992. /* While this module could theoretically support it, sqlite3RowSetNext()
  35993. ** is never called after sqlite3RowSetText() for the same RowSet. So
  35994. ** there is never a forest to deal with. Should this change, simply
  35995. ** remove the assert() and the #if 0. */
  35996. assert( p->pForest==0 );
  35997. #if 0
  35998. while( p->pForest ){
  35999. struct RowSetEntry *pTree = p->pForest->pLeft;
  36000. if( pTree ){
  36001. struct RowSetEntry *pHead, *pTail;
  36002. rowSetTreeToList(pTree, &pHead, &pTail);
  36003. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  36004. }
  36005. p->pForest = p->pForest->pRight;
  36006. }
  36007. #endif
  36008. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  36009. }
  36010. /*
  36011. ** Extract the smallest element from the RowSet.
  36012. ** Write the element into *pRowid. Return 1 on success. Return
  36013. ** 0 if the RowSet is already empty.
  36014. **
  36015. ** After this routine has been called, the sqlite3RowSetInsert()
  36016. ** routine may not be called again.
  36017. */
  36018. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  36019. assert( p!=0 );
  36020. /* Merge the forest into a single sorted list on first call */
  36021. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  36022. /* Return the next entry on the list */
  36023. if( p->pEntry ){
  36024. *pRowid = p->pEntry->v;
  36025. p->pEntry = p->pEntry->pRight;
  36026. if( p->pEntry==0 ){
  36027. sqlite3RowSetClear(p);
  36028. }
  36029. return 1;
  36030. }else{
  36031. return 0;
  36032. }
  36033. }
  36034. /*
  36035. ** Check to see if element iRowid was inserted into the rowset as
  36036. ** part of any insert batch prior to iBatch. Return 1 or 0.
  36037. **
  36038. ** If this is the first test of a new batch and if there exist entires
  36039. ** on pRowSet->pEntry, then sort those entires into the forest at
  36040. ** pRowSet->pForest so that they can be tested.
  36041. */
  36042. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
  36043. struct RowSetEntry *p, *pTree;
  36044. /* This routine is never called after sqlite3RowSetNext() */
  36045. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  36046. /* Sort entries into the forest on the first test of a new batch
  36047. */
  36048. if( iBatch!=pRowSet->iBatch ){
  36049. p = pRowSet->pEntry;
  36050. if( p ){
  36051. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  36052. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  36053. p = rowSetEntrySort(p);
  36054. }
  36055. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  36056. ppPrevTree = &pTree->pRight;
  36057. if( pTree->pLeft==0 ){
  36058. pTree->pLeft = rowSetListToTree(p);
  36059. break;
  36060. }else{
  36061. struct RowSetEntry *pAux, *pTail;
  36062. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  36063. pTree->pLeft = 0;
  36064. p = rowSetEntryMerge(pAux, p);
  36065. }
  36066. }
  36067. if( pTree==0 ){
  36068. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  36069. if( pTree ){
  36070. pTree->v = 0;
  36071. pTree->pRight = 0;
  36072. pTree->pLeft = rowSetListToTree(p);
  36073. }
  36074. }
  36075. pRowSet->pEntry = 0;
  36076. pRowSet->pLast = 0;
  36077. pRowSet->rsFlags |= ROWSET_SORTED;
  36078. }
  36079. pRowSet->iBatch = iBatch;
  36080. }
  36081. /* Test to see if the iRowid value appears anywhere in the forest.
  36082. ** Return 1 if it does and 0 if not.
  36083. */
  36084. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  36085. p = pTree->pLeft;
  36086. while( p ){
  36087. if( p->v<iRowid ){
  36088. p = p->pRight;
  36089. }else if( p->v>iRowid ){
  36090. p = p->pLeft;
  36091. }else{
  36092. return 1;
  36093. }
  36094. }
  36095. }
  36096. return 0;
  36097. }
  36098. /************** End of rowset.c **********************************************/
  36099. /************** Begin file pager.c *******************************************/
  36100. /*
  36101. ** 2001 September 15
  36102. **
  36103. ** The author disclaims copyright to this source code. In place of
  36104. ** a legal notice, here is a blessing:
  36105. **
  36106. ** May you do good and not evil.
  36107. ** May you find forgiveness for yourself and forgive others.
  36108. ** May you share freely, never taking more than you give.
  36109. **
  36110. *************************************************************************
  36111. ** This is the implementation of the page cache subsystem or "pager".
  36112. **
  36113. ** The pager is used to access a database disk file. It implements
  36114. ** atomic commit and rollback through the use of a journal file that
  36115. ** is separate from the database file. The pager also implements file
  36116. ** locking to prevent two processes from writing the same database
  36117. ** file simultaneously, or one process from reading the database while
  36118. ** another is writing.
  36119. */
  36120. #ifndef SQLITE_OMIT_DISKIO
  36121. /************** Include wal.h in the middle of pager.c ***********************/
  36122. /************** Begin file wal.h *********************************************/
  36123. /*
  36124. ** 2010 February 1
  36125. **
  36126. ** The author disclaims copyright to this source code. In place of
  36127. ** a legal notice, here is a blessing:
  36128. **
  36129. ** May you do good and not evil.
  36130. ** May you find forgiveness for yourself and forgive others.
  36131. ** May you share freely, never taking more than you give.
  36132. **
  36133. *************************************************************************
  36134. ** This header file defines the interface to the write-ahead logging
  36135. ** system. Refer to the comments below and the header comment attached to
  36136. ** the implementation of each function in log.c for further details.
  36137. */
  36138. #ifndef _WAL_H_
  36139. #define _WAL_H_
  36140. /* Additional values that can be added to the sync_flags argument of
  36141. ** sqlite3WalFrames():
  36142. */
  36143. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  36144. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  36145. #ifdef SQLITE_OMIT_WAL
  36146. # define sqlite3WalOpen(x,y,z) 0
  36147. # define sqlite3WalLimit(x,y)
  36148. # define sqlite3WalClose(w,x,y,z) 0
  36149. # define sqlite3WalBeginReadTransaction(y,z) 0
  36150. # define sqlite3WalEndReadTransaction(z)
  36151. # define sqlite3WalDbsize(y) 0
  36152. # define sqlite3WalBeginWriteTransaction(y) 0
  36153. # define sqlite3WalEndWriteTransaction(x) 0
  36154. # define sqlite3WalUndo(x,y,z) 0
  36155. # define sqlite3WalSavepoint(y,z)
  36156. # define sqlite3WalSavepointUndo(y,z) 0
  36157. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  36158. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  36159. # define sqlite3WalCallback(z) 0
  36160. # define sqlite3WalExclusiveMode(y,z) 0
  36161. # define sqlite3WalHeapMemory(z) 0
  36162. # define sqlite3WalFramesize(z) 0
  36163. # define sqlite3WalFindFrame(x,y,z) 0
  36164. #else
  36165. #define WAL_SAVEPOINT_NDATA 4
  36166. /* Connection to a write-ahead log (WAL) file.
  36167. ** There is one object of this type for each pager.
  36168. */
  36169. typedef struct Wal Wal;
  36170. /* Open and close a connection to a write-ahead log. */
  36171. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  36172. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  36173. /* Set the limiting size of a WAL file. */
  36174. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  36175. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  36176. ** snapshot is like a read-transaction. It is the state of the database
  36177. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  36178. ** preserves the current state even if the other threads or processes
  36179. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  36180. ** transaction and releases the lock.
  36181. */
  36182. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  36183. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  36184. /* Read a page from the write-ahead log, if it is present. */
  36185. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  36186. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  36187. /* If the WAL is not empty, return the size of the database. */
  36188. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  36189. /* Obtain or release the WRITER lock. */
  36190. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  36191. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  36192. /* Undo any frames written (but not committed) to the log */
  36193. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  36194. /* Return an integer that records the current (uncommitted) write
  36195. ** position in the WAL */
  36196. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  36197. /* Move the write position of the WAL back to iFrame. Called in
  36198. ** response to a ROLLBACK TO command. */
  36199. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  36200. /* Write a frame or frames to the log. */
  36201. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  36202. /* Copy pages from the log to the database file */
  36203. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  36204. Wal *pWal, /* Write-ahead log connection */
  36205. int eMode, /* One of PASSIVE, FULL and RESTART */
  36206. int (*xBusy)(void*), /* Function to call when busy */
  36207. void *pBusyArg, /* Context argument for xBusyHandler */
  36208. int sync_flags, /* Flags to sync db file with (or 0) */
  36209. int nBuf, /* Size of buffer nBuf */
  36210. u8 *zBuf, /* Temporary buffer to use */
  36211. int *pnLog, /* OUT: Number of frames in WAL */
  36212. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  36213. );
  36214. /* Return the value to pass to a sqlite3_wal_hook callback, the
  36215. ** number of frames in the WAL at the point of the last commit since
  36216. ** sqlite3WalCallback() was called. If no commits have occurred since
  36217. ** the last call, then return 0.
  36218. */
  36219. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  36220. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  36221. ** by the pager layer on the database file.
  36222. */
  36223. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  36224. /* Return true if the argument is non-NULL and the WAL module is using
  36225. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  36226. ** WAL module is using shared-memory, return false.
  36227. */
  36228. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  36229. #ifdef SQLITE_ENABLE_ZIPVFS
  36230. /* If the WAL file is not empty, return the number of bytes of content
  36231. ** stored in each frame (i.e. the db page-size when the WAL was created).
  36232. */
  36233. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  36234. #endif
  36235. #endif /* ifndef SQLITE_OMIT_WAL */
  36236. #endif /* _WAL_H_ */
  36237. /************** End of wal.h *************************************************/
  36238. /************** Continuing where we left off in pager.c **********************/
  36239. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  36240. **
  36241. ** This comment block describes invariants that hold when using a rollback
  36242. ** journal. These invariants do not apply for journal_mode=WAL,
  36243. ** journal_mode=MEMORY, or journal_mode=OFF.
  36244. **
  36245. ** Within this comment block, a page is deemed to have been synced
  36246. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  36247. ** Otherwise, the page is not synced until the xSync method of the VFS
  36248. ** is called successfully on the file containing the page.
  36249. **
  36250. ** Definition: A page of the database file is said to be "overwriteable" if
  36251. ** one or more of the following are true about the page:
  36252. **
  36253. ** (a) The original content of the page as it was at the beginning of
  36254. ** the transaction has been written into the rollback journal and
  36255. ** synced.
  36256. **
  36257. ** (b) The page was a freelist leaf page at the start of the transaction.
  36258. **
  36259. ** (c) The page number is greater than the largest page that existed in
  36260. ** the database file at the start of the transaction.
  36261. **
  36262. ** (1) A page of the database file is never overwritten unless one of the
  36263. ** following are true:
  36264. **
  36265. ** (a) The page and all other pages on the same sector are overwriteable.
  36266. **
  36267. ** (b) The atomic page write optimization is enabled, and the entire
  36268. ** transaction other than the update of the transaction sequence
  36269. ** number consists of a single page change.
  36270. **
  36271. ** (2) The content of a page written into the rollback journal exactly matches
  36272. ** both the content in the database when the rollback journal was written
  36273. ** and the content in the database at the beginning of the current
  36274. ** transaction.
  36275. **
  36276. ** (3) Writes to the database file are an integer multiple of the page size
  36277. ** in length and are aligned on a page boundary.
  36278. **
  36279. ** (4) Reads from the database file are either aligned on a page boundary and
  36280. ** an integer multiple of the page size in length or are taken from the
  36281. ** first 100 bytes of the database file.
  36282. **
  36283. ** (5) All writes to the database file are synced prior to the rollback journal
  36284. ** being deleted, truncated, or zeroed.
  36285. **
  36286. ** (6) If a master journal file is used, then all writes to the database file
  36287. ** are synced prior to the master journal being deleted.
  36288. **
  36289. ** Definition: Two databases (or the same database at two points it time)
  36290. ** are said to be "logically equivalent" if they give the same answer to
  36291. ** all queries. Note in particular the content of freelist leaf
  36292. ** pages can be changed arbitarily without effecting the logical equivalence
  36293. ** of the database.
  36294. **
  36295. ** (7) At any time, if any subset, including the empty set and the total set,
  36296. ** of the unsynced changes to a rollback journal are removed and the
  36297. ** journal is rolled back, the resulting database file will be logical
  36298. ** equivalent to the database file at the beginning of the transaction.
  36299. **
  36300. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  36301. ** is called to restore the database file to the same size it was at
  36302. ** the beginning of the transaction. (In some VFSes, the xTruncate
  36303. ** method is a no-op, but that does not change the fact the SQLite will
  36304. ** invoke it.)
  36305. **
  36306. ** (9) Whenever the database file is modified, at least one bit in the range
  36307. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  36308. ** the EXCLUSIVE lock, thus signaling other connections on the same
  36309. ** database to flush their caches.
  36310. **
  36311. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  36312. ** than one billion transactions.
  36313. **
  36314. ** (11) A database file is well-formed at the beginning and at the conclusion
  36315. ** of every transaction.
  36316. **
  36317. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  36318. ** the database file.
  36319. **
  36320. ** (13) A SHARED lock is held on the database file while reading any
  36321. ** content out of the database file.
  36322. **
  36323. ******************************************************************************/
  36324. /*
  36325. ** Macros for troubleshooting. Normally turned off
  36326. */
  36327. #if 0
  36328. int sqlite3PagerTrace=1; /* True to enable tracing */
  36329. #define sqlite3DebugPrintf printf
  36330. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  36331. #else
  36332. #define PAGERTRACE(X)
  36333. #endif
  36334. /*
  36335. ** The following two macros are used within the PAGERTRACE() macros above
  36336. ** to print out file-descriptors.
  36337. **
  36338. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  36339. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  36340. ** struct as its argument.
  36341. */
  36342. #define PAGERID(p) ((int)(p->fd))
  36343. #define FILEHANDLEID(fd) ((int)fd)
  36344. /*
  36345. ** The Pager.eState variable stores the current 'state' of a pager. A
  36346. ** pager may be in any one of the seven states shown in the following
  36347. ** state diagram.
  36348. **
  36349. ** OPEN <------+------+
  36350. ** | | |
  36351. ** V | |
  36352. ** +---------> READER-------+ |
  36353. ** | | |
  36354. ** | V |
  36355. ** |<-------WRITER_LOCKED------> ERROR
  36356. ** | | ^
  36357. ** | V |
  36358. ** |<------WRITER_CACHEMOD-------->|
  36359. ** | | |
  36360. ** | V |
  36361. ** |<-------WRITER_DBMOD---------->|
  36362. ** | | |
  36363. ** | V |
  36364. ** +<------WRITER_FINISHED-------->+
  36365. **
  36366. **
  36367. ** List of state transitions and the C [function] that performs each:
  36368. **
  36369. ** OPEN -> READER [sqlite3PagerSharedLock]
  36370. ** READER -> OPEN [pager_unlock]
  36371. **
  36372. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  36373. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  36374. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  36375. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  36376. ** WRITER_*** -> READER [pager_end_transaction]
  36377. **
  36378. ** WRITER_*** -> ERROR [pager_error]
  36379. ** ERROR -> OPEN [pager_unlock]
  36380. **
  36381. **
  36382. ** OPEN:
  36383. **
  36384. ** The pager starts up in this state. Nothing is guaranteed in this
  36385. ** state - the file may or may not be locked and the database size is
  36386. ** unknown. The database may not be read or written.
  36387. **
  36388. ** * No read or write transaction is active.
  36389. ** * Any lock, or no lock at all, may be held on the database file.
  36390. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  36391. **
  36392. ** READER:
  36393. **
  36394. ** In this state all the requirements for reading the database in
  36395. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  36396. ** was) in exclusive-locking mode, a user-level read transaction is
  36397. ** open. The database size is known in this state.
  36398. **
  36399. ** A connection running with locking_mode=normal enters this state when
  36400. ** it opens a read-transaction on the database and returns to state
  36401. ** OPEN after the read-transaction is completed. However a connection
  36402. ** running in locking_mode=exclusive (including temp databases) remains in
  36403. ** this state even after the read-transaction is closed. The only way
  36404. ** a locking_mode=exclusive connection can transition from READER to OPEN
  36405. ** is via the ERROR state (see below).
  36406. **
  36407. ** * A read transaction may be active (but a write-transaction cannot).
  36408. ** * A SHARED or greater lock is held on the database file.
  36409. ** * The dbSize variable may be trusted (even if a user-level read
  36410. ** transaction is not active). The dbOrigSize and dbFileSize variables
  36411. ** may not be trusted at this point.
  36412. ** * If the database is a WAL database, then the WAL connection is open.
  36413. ** * Even if a read-transaction is not open, it is guaranteed that
  36414. ** there is no hot-journal in the file-system.
  36415. **
  36416. ** WRITER_LOCKED:
  36417. **
  36418. ** The pager moves to this state from READER when a write-transaction
  36419. ** is first opened on the database. In WRITER_LOCKED state, all locks
  36420. ** required to start a write-transaction are held, but no actual
  36421. ** modifications to the cache or database have taken place.
  36422. **
  36423. ** In rollback mode, a RESERVED or (if the transaction was opened with
  36424. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  36425. ** moving to this state, but the journal file is not written to or opened
  36426. ** to in this state. If the transaction is committed or rolled back while
  36427. ** in WRITER_LOCKED state, all that is required is to unlock the database
  36428. ** file.
  36429. **
  36430. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  36431. ** If the connection is running with locking_mode=exclusive, an attempt
  36432. ** is made to obtain an EXCLUSIVE lock on the database file.
  36433. **
  36434. ** * A write transaction is active.
  36435. ** * If the connection is open in rollback-mode, a RESERVED or greater
  36436. ** lock is held on the database file.
  36437. ** * If the connection is open in WAL-mode, a WAL write transaction
  36438. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  36439. ** called).
  36440. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  36441. ** * The contents of the pager cache have not been modified.
  36442. ** * The journal file may or may not be open.
  36443. ** * Nothing (not even the first header) has been written to the journal.
  36444. **
  36445. ** WRITER_CACHEMOD:
  36446. **
  36447. ** A pager moves from WRITER_LOCKED state to this state when a page is
  36448. ** first modified by the upper layer. In rollback mode the journal file
  36449. ** is opened (if it is not already open) and a header written to the
  36450. ** start of it. The database file on disk has not been modified.
  36451. **
  36452. ** * A write transaction is active.
  36453. ** * A RESERVED or greater lock is held on the database file.
  36454. ** * The journal file is open and the first header has been written
  36455. ** to it, but the header has not been synced to disk.
  36456. ** * The contents of the page cache have been modified.
  36457. **
  36458. ** WRITER_DBMOD:
  36459. **
  36460. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  36461. ** when it modifies the contents of the database file. WAL connections
  36462. ** never enter this state (since they do not modify the database file,
  36463. ** just the log file).
  36464. **
  36465. ** * A write transaction is active.
  36466. ** * An EXCLUSIVE or greater lock is held on the database file.
  36467. ** * The journal file is open and the first header has been written
  36468. ** and synced to disk.
  36469. ** * The contents of the page cache have been modified (and possibly
  36470. ** written to disk).
  36471. **
  36472. ** WRITER_FINISHED:
  36473. **
  36474. ** It is not possible for a WAL connection to enter this state.
  36475. **
  36476. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  36477. ** state after the entire transaction has been successfully written into the
  36478. ** database file. In this state the transaction may be committed simply
  36479. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  36480. ** not possible to modify the database further. At this point, the upper
  36481. ** layer must either commit or rollback the transaction.
  36482. **
  36483. ** * A write transaction is active.
  36484. ** * An EXCLUSIVE or greater lock is held on the database file.
  36485. ** * All writing and syncing of journal and database data has finished.
  36486. ** If no error occurred, all that remains is to finalize the journal to
  36487. ** commit the transaction. If an error did occur, the caller will need
  36488. ** to rollback the transaction.
  36489. **
  36490. ** ERROR:
  36491. **
  36492. ** The ERROR state is entered when an IO or disk-full error (including
  36493. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  36494. ** difficult to be sure that the in-memory pager state (cache contents,
  36495. ** db size etc.) are consistent with the contents of the file-system.
  36496. **
  36497. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  36498. ** cannot.
  36499. **
  36500. ** For example, if an IO error occurs while performing a rollback,
  36501. ** the contents of the page-cache may be left in an inconsistent state.
  36502. ** At this point it would be dangerous to change back to READER state
  36503. ** (as usually happens after a rollback). Any subsequent readers might
  36504. ** report database corruption (due to the inconsistent cache), and if
  36505. ** they upgrade to writers, they may inadvertently corrupt the database
  36506. ** file. To avoid this hazard, the pager switches into the ERROR state
  36507. ** instead of READER following such an error.
  36508. **
  36509. ** Once it has entered the ERROR state, any attempt to use the pager
  36510. ** to read or write data returns an error. Eventually, once all
  36511. ** outstanding transactions have been abandoned, the pager is able to
  36512. ** transition back to OPEN state, discarding the contents of the
  36513. ** page-cache and any other in-memory state at the same time. Everything
  36514. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  36515. ** when a read-transaction is next opened on the pager (transitioning
  36516. ** the pager into READER state). At that point the system has recovered
  36517. ** from the error.
  36518. **
  36519. ** Specifically, the pager jumps into the ERROR state if:
  36520. **
  36521. ** 1. An error occurs while attempting a rollback. This happens in
  36522. ** function sqlite3PagerRollback().
  36523. **
  36524. ** 2. An error occurs while attempting to finalize a journal file
  36525. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  36526. **
  36527. ** 3. An error occurs while attempting to write to the journal or
  36528. ** database file in function pagerStress() in order to free up
  36529. ** memory.
  36530. **
  36531. ** In other cases, the error is returned to the b-tree layer. The b-tree
  36532. ** layer then attempts a rollback operation. If the error condition
  36533. ** persists, the pager enters the ERROR state via condition (1) above.
  36534. **
  36535. ** Condition (3) is necessary because it can be triggered by a read-only
  36536. ** statement executed within a transaction. In this case, if the error
  36537. ** code were simply returned to the user, the b-tree layer would not
  36538. ** automatically attempt a rollback, as it assumes that an error in a
  36539. ** read-only statement cannot leave the pager in an internally inconsistent
  36540. ** state.
  36541. **
  36542. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  36543. ** * There are one or more outstanding references to pages (after the
  36544. ** last reference is dropped the pager should move back to OPEN state).
  36545. ** * The pager is not an in-memory pager.
  36546. **
  36547. **
  36548. ** Notes:
  36549. **
  36550. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  36551. ** connection is open in WAL mode. A WAL connection is always in one
  36552. ** of the first four states.
  36553. **
  36554. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  36555. ** state. There are two exceptions: immediately after exclusive-mode has
  36556. ** been turned on (and before any read or write transactions are
  36557. ** executed), and when the pager is leaving the "error state".
  36558. **
  36559. ** * See also: assert_pager_state().
  36560. */
  36561. #define PAGER_OPEN 0
  36562. #define PAGER_READER 1
  36563. #define PAGER_WRITER_LOCKED 2
  36564. #define PAGER_WRITER_CACHEMOD 3
  36565. #define PAGER_WRITER_DBMOD 4
  36566. #define PAGER_WRITER_FINISHED 5
  36567. #define PAGER_ERROR 6
  36568. /*
  36569. ** The Pager.eLock variable is almost always set to one of the
  36570. ** following locking-states, according to the lock currently held on
  36571. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  36572. ** This variable is kept up to date as locks are taken and released by
  36573. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  36574. **
  36575. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  36576. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  36577. ** the operation was successful. In these circumstances pagerLockDb() and
  36578. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  36579. ** when unlocking the file, and only updated when locking the file if the
  36580. ** VFS call is successful. This way, the Pager.eLock variable may be set
  36581. ** to a less exclusive (lower) value than the lock that is actually held
  36582. ** at the system level, but it is never set to a more exclusive value.
  36583. **
  36584. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  36585. ** be a few redundant xLock() calls or a lock may be held for longer than
  36586. ** required, but nothing really goes wrong.
  36587. **
  36588. ** The exception is when the database file is unlocked as the pager moves
  36589. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  36590. ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
  36591. ** transition, by the same pager or any other). If the call to xUnlock()
  36592. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  36593. ** can confuse the call to xCheckReservedLock() call made later as part
  36594. ** of hot-journal detection.
  36595. **
  36596. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  36597. ** lock held by this process or any others". So xCheckReservedLock may
  36598. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  36599. ** doesn't know it because of a previous error in xUnlock). If this happens
  36600. ** a hot-journal may be mistaken for a journal being created by an active
  36601. ** transaction in another process, causing SQLite to read from the database
  36602. ** without rolling it back.
  36603. **
  36604. ** To work around this, if a call to xUnlock() fails when unlocking the
  36605. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  36606. ** is only changed back to a real locking state after a successful call
  36607. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  36608. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  36609. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  36610. ** lock on the database file before attempting to roll it back. See function
  36611. ** PagerSharedLock() for more detail.
  36612. **
  36613. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  36614. ** PAGER_OPEN state.
  36615. */
  36616. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  36617. /*
  36618. ** A macro used for invoking the codec if there is one
  36619. */
  36620. #ifdef SQLITE_HAS_CODEC
  36621. # define CODEC1(P,D,N,X,E) \
  36622. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  36623. # define CODEC2(P,D,N,X,E,O) \
  36624. if( P->xCodec==0 ){ O=(char*)D; }else \
  36625. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  36626. #else
  36627. # define CODEC1(P,D,N,X,E) /* NO-OP */
  36628. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  36629. #endif
  36630. /*
  36631. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  36632. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  36633. ** This could conceivably cause corruption following a power failure on
  36634. ** such a system. This is currently an undocumented limit.
  36635. */
  36636. #define MAX_SECTOR_SIZE 0x10000
  36637. /*
  36638. ** An instance of the following structure is allocated for each active
  36639. ** savepoint and statement transaction in the system. All such structures
  36640. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  36641. ** resized using sqlite3Realloc().
  36642. **
  36643. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  36644. ** set to 0. If a journal-header is written into the main journal while
  36645. ** the savepoint is active, then iHdrOffset is set to the byte offset
  36646. ** immediately following the last journal record written into the main
  36647. ** journal before the journal-header. This is required during savepoint
  36648. ** rollback (see pagerPlaybackSavepoint()).
  36649. */
  36650. typedef struct PagerSavepoint PagerSavepoint;
  36651. struct PagerSavepoint {
  36652. i64 iOffset; /* Starting offset in main journal */
  36653. i64 iHdrOffset; /* See above */
  36654. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  36655. Pgno nOrig; /* Original number of pages in file */
  36656. Pgno iSubRec; /* Index of first record in sub-journal */
  36657. #ifndef SQLITE_OMIT_WAL
  36658. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  36659. #endif
  36660. };
  36661. /*
  36662. ** Bits of the Pager.doNotSpill flag. See further description below.
  36663. */
  36664. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  36665. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  36666. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  36667. /*
  36668. ** A open page cache is an instance of struct Pager. A description of
  36669. ** some of the more important member variables follows:
  36670. **
  36671. ** eState
  36672. **
  36673. ** The current 'state' of the pager object. See the comment and state
  36674. ** diagram above for a description of the pager state.
  36675. **
  36676. ** eLock
  36677. **
  36678. ** For a real on-disk database, the current lock held on the database file -
  36679. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  36680. **
  36681. ** For a temporary or in-memory database (neither of which require any
  36682. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  36683. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  36684. ** logic into thinking that it already has all the locks it will ever
  36685. ** need (and no reason to release them).
  36686. **
  36687. ** In some (obscure) circumstances, this variable may also be set to
  36688. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  36689. ** details.
  36690. **
  36691. ** changeCountDone
  36692. **
  36693. ** This boolean variable is used to make sure that the change-counter
  36694. ** (the 4-byte header field at byte offset 24 of the database file) is
  36695. ** not updated more often than necessary.
  36696. **
  36697. ** It is set to true when the change-counter field is updated, which
  36698. ** can only happen if an exclusive lock is held on the database file.
  36699. ** It is cleared (set to false) whenever an exclusive lock is
  36700. ** relinquished on the database file. Each time a transaction is committed,
  36701. ** The changeCountDone flag is inspected. If it is true, the work of
  36702. ** updating the change-counter is omitted for the current transaction.
  36703. **
  36704. ** This mechanism means that when running in exclusive mode, a connection
  36705. ** need only update the change-counter once, for the first transaction
  36706. ** committed.
  36707. **
  36708. ** setMaster
  36709. **
  36710. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  36711. ** (or may not) specify a master-journal name to be written into the
  36712. ** journal file before it is synced to disk.
  36713. **
  36714. ** Whether or not a journal file contains a master-journal pointer affects
  36715. ** the way in which the journal file is finalized after the transaction is
  36716. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  36717. ** If a journal file does not contain a master-journal pointer, it is
  36718. ** finalized by overwriting the first journal header with zeroes. If
  36719. ** it does contain a master-journal pointer the journal file is finalized
  36720. ** by truncating it to zero bytes, just as if the connection were
  36721. ** running in "journal_mode=truncate" mode.
  36722. **
  36723. ** Journal files that contain master journal pointers cannot be finalized
  36724. ** simply by overwriting the first journal-header with zeroes, as the
  36725. ** master journal pointer could interfere with hot-journal rollback of any
  36726. ** subsequently interrupted transaction that reuses the journal file.
  36727. **
  36728. ** The flag is cleared as soon as the journal file is finalized (either
  36729. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  36730. ** journal file from being successfully finalized, the setMaster flag
  36731. ** is cleared anyway (and the pager will move to ERROR state).
  36732. **
  36733. ** doNotSpill
  36734. **
  36735. ** This variables control the behavior of cache-spills (calls made by
  36736. ** the pcache module to the pagerStress() routine to write cached data
  36737. ** to the file-system in order to free up memory).
  36738. **
  36739. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  36740. ** writing to the database from pagerStress() is disabled altogether.
  36741. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  36742. ** comes up during savepoint rollback that requires the pcache module
  36743. ** to allocate a new page to prevent the journal file from being written
  36744. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  36745. ** case is a user preference.
  36746. **
  36747. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
  36748. ** is permitted, but syncing the journal file is not. This flag is set
  36749. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  36750. ** the database page-size in order to prevent a journal sync from happening
  36751. ** in between the journalling of two pages on the same sector.
  36752. **
  36753. ** subjInMemory
  36754. **
  36755. ** This is a boolean variable. If true, then any required sub-journal
  36756. ** is opened as an in-memory journal file. If false, then in-memory
  36757. ** sub-journals are only used for in-memory pager files.
  36758. **
  36759. ** This variable is updated by the upper layer each time a new
  36760. ** write-transaction is opened.
  36761. **
  36762. ** dbSize, dbOrigSize, dbFileSize
  36763. **
  36764. ** Variable dbSize is set to the number of pages in the database file.
  36765. ** It is valid in PAGER_READER and higher states (all states except for
  36766. ** OPEN and ERROR).
  36767. **
  36768. ** dbSize is set based on the size of the database file, which may be
  36769. ** larger than the size of the database (the value stored at offset
  36770. ** 28 of the database header by the btree). If the size of the file
  36771. ** is not an integer multiple of the page-size, the value stored in
  36772. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  36773. ** Except, any file that is greater than 0 bytes in size is considered
  36774. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  36775. ** to dbSize==1).
  36776. **
  36777. ** During a write-transaction, if pages with page-numbers greater than
  36778. ** dbSize are modified in the cache, dbSize is updated accordingly.
  36779. ** Similarly, if the database is truncated using PagerTruncateImage(),
  36780. ** dbSize is updated.
  36781. **
  36782. ** Variables dbOrigSize and dbFileSize are valid in states
  36783. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  36784. ** variable at the start of the transaction. It is used during rollback,
  36785. ** and to determine whether or not pages need to be journalled before
  36786. ** being modified.
  36787. **
  36788. ** Throughout a write-transaction, dbFileSize contains the size of
  36789. ** the file on disk in pages. It is set to a copy of dbSize when the
  36790. ** write-transaction is first opened, and updated when VFS calls are made
  36791. ** to write or truncate the database file on disk.
  36792. **
  36793. ** The only reason the dbFileSize variable is required is to suppress
  36794. ** unnecessary calls to xTruncate() after committing a transaction. If,
  36795. ** when a transaction is committed, the dbFileSize variable indicates
  36796. ** that the database file is larger than the database image (Pager.dbSize),
  36797. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  36798. ** to measure the database file on disk, and then truncates it if required.
  36799. ** dbFileSize is not used when rolling back a transaction. In this case
  36800. ** pager_truncate() is called unconditionally (which means there may be
  36801. ** a call to xFilesize() that is not strictly required). In either case,
  36802. ** pager_truncate() may cause the file to become smaller or larger.
  36803. **
  36804. ** dbHintSize
  36805. **
  36806. ** The dbHintSize variable is used to limit the number of calls made to
  36807. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  36808. **
  36809. ** dbHintSize is set to a copy of the dbSize variable when a
  36810. ** write-transaction is opened (at the same time as dbFileSize and
  36811. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  36812. ** dbHintSize is increased to the number of pages that correspond to the
  36813. ** size-hint passed to the method call. See pager_write_pagelist() for
  36814. ** details.
  36815. **
  36816. ** errCode
  36817. **
  36818. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  36819. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  36820. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  36821. ** sub-codes.
  36822. */
  36823. struct Pager {
  36824. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  36825. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  36826. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  36827. u8 useJournal; /* Use a rollback journal on this file */
  36828. u8 noSync; /* Do not sync the journal if true */
  36829. u8 fullSync; /* Do extra syncs of the journal for robustness */
  36830. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  36831. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  36832. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  36833. u8 tempFile; /* zFilename is a temporary file */
  36834. u8 readOnly; /* True for a read-only database */
  36835. u8 memDb; /* True to inhibit all file I/O */
  36836. /**************************************************************************
  36837. ** The following block contains those class members that change during
  36838. ** routine opertion. Class members not in this block are either fixed
  36839. ** when the pager is first created or else only change when there is a
  36840. ** significant mode change (such as changing the page_size, locking_mode,
  36841. ** or the journal_mode). From another view, these class members describe
  36842. ** the "state" of the pager, while other class members describe the
  36843. ** "configuration" of the pager.
  36844. */
  36845. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  36846. u8 eLock; /* Current lock held on database file */
  36847. u8 changeCountDone; /* Set after incrementing the change-counter */
  36848. u8 setMaster; /* True if a m-j name has been written to jrnl */
  36849. u8 doNotSpill; /* Do not spill the cache when non-zero */
  36850. u8 subjInMemory; /* True to use in-memory sub-journals */
  36851. Pgno dbSize; /* Number of pages in the database */
  36852. Pgno dbOrigSize; /* dbSize before the current transaction */
  36853. Pgno dbFileSize; /* Number of pages in the database file */
  36854. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  36855. int errCode; /* One of several kinds of errors */
  36856. int nRec; /* Pages journalled since last j-header written */
  36857. u32 cksumInit; /* Quasi-random value added to every checksum */
  36858. u32 nSubRec; /* Number of records written to sub-journal */
  36859. Bitvec *pInJournal; /* One bit for each page in the database file */
  36860. sqlite3_file *fd; /* File descriptor for database */
  36861. sqlite3_file *jfd; /* File descriptor for main journal */
  36862. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  36863. i64 journalOff; /* Current write offset in the journal file */
  36864. i64 journalHdr; /* Byte offset to previous journal header */
  36865. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  36866. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  36867. int nSavepoint; /* Number of elements in aSavepoint[] */
  36868. char dbFileVers[16]; /* Changes whenever database file changes */
  36869. u8 bUseFetch; /* True to use xFetch() */
  36870. int nMmapOut; /* Number of mmap pages currently outstanding */
  36871. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  36872. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  36873. /*
  36874. ** End of the routinely-changing class members
  36875. ***************************************************************************/
  36876. u16 nExtra; /* Add this many bytes to each in-memory page */
  36877. i16 nReserve; /* Number of unused bytes at end of each page */
  36878. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  36879. u32 sectorSize; /* Assumed sector size during rollback */
  36880. int pageSize; /* Number of bytes in a page */
  36881. Pgno mxPgno; /* Maximum allowed size of the database */
  36882. i64 journalSizeLimit; /* Size limit for persistent journal files */
  36883. char *zFilename; /* Name of the database file */
  36884. char *zJournal; /* Name of the journal file */
  36885. int (*xBusyHandler)(void*); /* Function to call when busy */
  36886. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  36887. int aStat[3]; /* Total cache hits, misses and writes */
  36888. #ifdef SQLITE_TEST
  36889. int nRead; /* Database pages read */
  36890. #endif
  36891. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  36892. #ifdef SQLITE_HAS_CODEC
  36893. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  36894. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  36895. void (*xCodecFree)(void*); /* Destructor for the codec */
  36896. void *pCodec; /* First argument to xCodec... methods */
  36897. #endif
  36898. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  36899. PCache *pPCache; /* Pointer to page cache object */
  36900. #ifndef SQLITE_OMIT_WAL
  36901. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  36902. char *zWal; /* File name for write-ahead log */
  36903. #endif
  36904. };
  36905. /*
  36906. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  36907. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  36908. ** or CACHE_WRITE to sqlite3_db_status().
  36909. */
  36910. #define PAGER_STAT_HIT 0
  36911. #define PAGER_STAT_MISS 1
  36912. #define PAGER_STAT_WRITE 2
  36913. /*
  36914. ** The following global variables hold counters used for
  36915. ** testing purposes only. These variables do not exist in
  36916. ** a non-testing build. These variables are not thread-safe.
  36917. */
  36918. #ifdef SQLITE_TEST
  36919. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  36920. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  36921. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  36922. # define PAGER_INCR(v) v++
  36923. #else
  36924. # define PAGER_INCR(v)
  36925. #endif
  36926. /*
  36927. ** Journal files begin with the following magic string. The data
  36928. ** was obtained from /dev/random. It is used only as a sanity check.
  36929. **
  36930. ** Since version 2.8.0, the journal format contains additional sanity
  36931. ** checking information. If the power fails while the journal is being
  36932. ** written, semi-random garbage data might appear in the journal
  36933. ** file after power is restored. If an attempt is then made
  36934. ** to roll the journal back, the database could be corrupted. The additional
  36935. ** sanity checking data is an attempt to discover the garbage in the
  36936. ** journal and ignore it.
  36937. **
  36938. ** The sanity checking information for the new journal format consists
  36939. ** of a 32-bit checksum on each page of data. The checksum covers both
  36940. ** the page number and the pPager->pageSize bytes of data for the page.
  36941. ** This cksum is initialized to a 32-bit random value that appears in the
  36942. ** journal file right after the header. The random initializer is important,
  36943. ** because garbage data that appears at the end of a journal is likely
  36944. ** data that was once in other files that have now been deleted. If the
  36945. ** garbage data came from an obsolete journal file, the checksums might
  36946. ** be correct. But by initializing the checksum to random value which
  36947. ** is different for every journal, we minimize that risk.
  36948. */
  36949. static const unsigned char aJournalMagic[] = {
  36950. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  36951. };
  36952. /*
  36953. ** The size of the of each page record in the journal is given by
  36954. ** the following macro.
  36955. */
  36956. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  36957. /*
  36958. ** The journal header size for this pager. This is usually the same
  36959. ** size as a single disk sector. See also setSectorSize().
  36960. */
  36961. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  36962. /*
  36963. ** The macro MEMDB is true if we are dealing with an in-memory database.
  36964. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  36965. ** the value of MEMDB will be a constant and the compiler will optimize
  36966. ** out code that would never execute.
  36967. */
  36968. #ifdef SQLITE_OMIT_MEMORYDB
  36969. # define MEMDB 0
  36970. #else
  36971. # define MEMDB pPager->memDb
  36972. #endif
  36973. /*
  36974. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  36975. ** interfaces to access the database using memory-mapped I/O.
  36976. */
  36977. #if SQLITE_MAX_MMAP_SIZE>0
  36978. # define USEFETCH(x) ((x)->bUseFetch)
  36979. #else
  36980. # define USEFETCH(x) 0
  36981. #endif
  36982. /*
  36983. ** The maximum legal page number is (2^31 - 1).
  36984. */
  36985. #define PAGER_MAX_PGNO 2147483647
  36986. /*
  36987. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  36988. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  36989. **
  36990. ** This is so that expressions can be written as:
  36991. **
  36992. ** if( isOpen(pPager->jfd) ){ ...
  36993. **
  36994. ** instead of
  36995. **
  36996. ** if( pPager->jfd->pMethods ){ ...
  36997. */
  36998. #define isOpen(pFd) ((pFd)->pMethods)
  36999. /*
  37000. ** Return true if this pager uses a write-ahead log instead of the usual
  37001. ** rollback journal. Otherwise false.
  37002. */
  37003. #ifndef SQLITE_OMIT_WAL
  37004. static int pagerUseWal(Pager *pPager){
  37005. return (pPager->pWal!=0);
  37006. }
  37007. #else
  37008. # define pagerUseWal(x) 0
  37009. # define pagerRollbackWal(x) 0
  37010. # define pagerWalFrames(v,w,x,y) 0
  37011. # define pagerOpenWalIfPresent(z) SQLITE_OK
  37012. # define pagerBeginReadTransaction(z) SQLITE_OK
  37013. #endif
  37014. #ifndef NDEBUG
  37015. /*
  37016. ** Usage:
  37017. **
  37018. ** assert( assert_pager_state(pPager) );
  37019. **
  37020. ** This function runs many asserts to try to find inconsistencies in
  37021. ** the internal state of the Pager object.
  37022. */
  37023. static int assert_pager_state(Pager *p){
  37024. Pager *pPager = p;
  37025. /* State must be valid. */
  37026. assert( p->eState==PAGER_OPEN
  37027. || p->eState==PAGER_READER
  37028. || p->eState==PAGER_WRITER_LOCKED
  37029. || p->eState==PAGER_WRITER_CACHEMOD
  37030. || p->eState==PAGER_WRITER_DBMOD
  37031. || p->eState==PAGER_WRITER_FINISHED
  37032. || p->eState==PAGER_ERROR
  37033. );
  37034. /* Regardless of the current state, a temp-file connection always behaves
  37035. ** as if it has an exclusive lock on the database file. It never updates
  37036. ** the change-counter field, so the changeCountDone flag is always set.
  37037. */
  37038. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  37039. assert( p->tempFile==0 || pPager->changeCountDone );
  37040. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  37041. ** And if the journal-mode is "OFF", the journal file must not be open.
  37042. */
  37043. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  37044. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  37045. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  37046. ** this means an in-memory pager performs no IO at all, it cannot encounter
  37047. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  37048. ** a journal file. (although the in-memory journal implementation may
  37049. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  37050. ** is therefore not possible for an in-memory pager to enter the ERROR
  37051. ** state.
  37052. */
  37053. if( MEMDB ){
  37054. assert( p->noSync );
  37055. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  37056. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  37057. );
  37058. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  37059. assert( pagerUseWal(p)==0 );
  37060. }
  37061. /* If changeCountDone is set, a RESERVED lock or greater must be held
  37062. ** on the file.
  37063. */
  37064. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  37065. assert( p->eLock!=PENDING_LOCK );
  37066. switch( p->eState ){
  37067. case PAGER_OPEN:
  37068. assert( !MEMDB );
  37069. assert( pPager->errCode==SQLITE_OK );
  37070. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  37071. break;
  37072. case PAGER_READER:
  37073. assert( pPager->errCode==SQLITE_OK );
  37074. assert( p->eLock!=UNKNOWN_LOCK );
  37075. assert( p->eLock>=SHARED_LOCK );
  37076. break;
  37077. case PAGER_WRITER_LOCKED:
  37078. assert( p->eLock!=UNKNOWN_LOCK );
  37079. assert( pPager->errCode==SQLITE_OK );
  37080. if( !pagerUseWal(pPager) ){
  37081. assert( p->eLock>=RESERVED_LOCK );
  37082. }
  37083. assert( pPager->dbSize==pPager->dbOrigSize );
  37084. assert( pPager->dbOrigSize==pPager->dbFileSize );
  37085. assert( pPager->dbOrigSize==pPager->dbHintSize );
  37086. assert( pPager->setMaster==0 );
  37087. break;
  37088. case PAGER_WRITER_CACHEMOD:
  37089. assert( p->eLock!=UNKNOWN_LOCK );
  37090. assert( pPager->errCode==SQLITE_OK );
  37091. if( !pagerUseWal(pPager) ){
  37092. /* It is possible that if journal_mode=wal here that neither the
  37093. ** journal file nor the WAL file are open. This happens during
  37094. ** a rollback transaction that switches from journal_mode=off
  37095. ** to journal_mode=wal.
  37096. */
  37097. assert( p->eLock>=RESERVED_LOCK );
  37098. assert( isOpen(p->jfd)
  37099. || p->journalMode==PAGER_JOURNALMODE_OFF
  37100. || p->journalMode==PAGER_JOURNALMODE_WAL
  37101. );
  37102. }
  37103. assert( pPager->dbOrigSize==pPager->dbFileSize );
  37104. assert( pPager->dbOrigSize==pPager->dbHintSize );
  37105. break;
  37106. case PAGER_WRITER_DBMOD:
  37107. assert( p->eLock==EXCLUSIVE_LOCK );
  37108. assert( pPager->errCode==SQLITE_OK );
  37109. assert( !pagerUseWal(pPager) );
  37110. assert( p->eLock>=EXCLUSIVE_LOCK );
  37111. assert( isOpen(p->jfd)
  37112. || p->journalMode==PAGER_JOURNALMODE_OFF
  37113. || p->journalMode==PAGER_JOURNALMODE_WAL
  37114. );
  37115. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  37116. break;
  37117. case PAGER_WRITER_FINISHED:
  37118. assert( p->eLock==EXCLUSIVE_LOCK );
  37119. assert( pPager->errCode==SQLITE_OK );
  37120. assert( !pagerUseWal(pPager) );
  37121. assert( isOpen(p->jfd)
  37122. || p->journalMode==PAGER_JOURNALMODE_OFF
  37123. || p->journalMode==PAGER_JOURNALMODE_WAL
  37124. );
  37125. break;
  37126. case PAGER_ERROR:
  37127. /* There must be at least one outstanding reference to the pager if
  37128. ** in ERROR state. Otherwise the pager should have already dropped
  37129. ** back to OPEN state.
  37130. */
  37131. assert( pPager->errCode!=SQLITE_OK );
  37132. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  37133. break;
  37134. }
  37135. return 1;
  37136. }
  37137. #endif /* ifndef NDEBUG */
  37138. #ifdef SQLITE_DEBUG
  37139. /*
  37140. ** Return a pointer to a human readable string in a static buffer
  37141. ** containing the state of the Pager object passed as an argument. This
  37142. ** is intended to be used within debuggers. For example, as an alternative
  37143. ** to "print *pPager" in gdb:
  37144. **
  37145. ** (gdb) printf "%s", print_pager_state(pPager)
  37146. */
  37147. static char *print_pager_state(Pager *p){
  37148. static char zRet[1024];
  37149. sqlite3_snprintf(1024, zRet,
  37150. "Filename: %s\n"
  37151. "State: %s errCode=%d\n"
  37152. "Lock: %s\n"
  37153. "Locking mode: locking_mode=%s\n"
  37154. "Journal mode: journal_mode=%s\n"
  37155. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  37156. "Journal: journalOff=%lld journalHdr=%lld\n"
  37157. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  37158. , p->zFilename
  37159. , p->eState==PAGER_OPEN ? "OPEN" :
  37160. p->eState==PAGER_READER ? "READER" :
  37161. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  37162. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  37163. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  37164. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  37165. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  37166. , (int)p->errCode
  37167. , p->eLock==NO_LOCK ? "NO_LOCK" :
  37168. p->eLock==RESERVED_LOCK ? "RESERVED" :
  37169. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  37170. p->eLock==SHARED_LOCK ? "SHARED" :
  37171. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  37172. , p->exclusiveMode ? "exclusive" : "normal"
  37173. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  37174. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  37175. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  37176. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  37177. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  37178. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  37179. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  37180. , p->journalOff, p->journalHdr
  37181. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  37182. );
  37183. return zRet;
  37184. }
  37185. #endif
  37186. /*
  37187. ** Return true if it is necessary to write page *pPg into the sub-journal.
  37188. ** A page needs to be written into the sub-journal if there exists one
  37189. ** or more open savepoints for which:
  37190. **
  37191. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  37192. ** * The bit corresponding to the page-number is not set in
  37193. ** PagerSavepoint.pInSavepoint.
  37194. */
  37195. static int subjRequiresPage(PgHdr *pPg){
  37196. Pager *pPager = pPg->pPager;
  37197. PagerSavepoint *p;
  37198. Pgno pgno;
  37199. int i;
  37200. if( pPager->nSavepoint ){
  37201. pgno = pPg->pgno;
  37202. for(i=0; i<pPager->nSavepoint; i++){
  37203. p = &pPager->aSavepoint[i];
  37204. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  37205. return 1;
  37206. }
  37207. }
  37208. }
  37209. return 0;
  37210. }
  37211. /*
  37212. ** Return true if the page is already in the journal file.
  37213. */
  37214. static int pageInJournal(PgHdr *pPg){
  37215. return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
  37216. }
  37217. /*
  37218. ** Read a 32-bit integer from the given file descriptor. Store the integer
  37219. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  37220. ** error code is something goes wrong.
  37221. **
  37222. ** All values are stored on disk as big-endian.
  37223. */
  37224. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  37225. unsigned char ac[4];
  37226. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  37227. if( rc==SQLITE_OK ){
  37228. *pRes = sqlite3Get4byte(ac);
  37229. }
  37230. return rc;
  37231. }
  37232. /*
  37233. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  37234. */
  37235. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  37236. /*
  37237. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  37238. ** on success or an error code is something goes wrong.
  37239. */
  37240. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  37241. char ac[4];
  37242. put32bits(ac, val);
  37243. return sqlite3OsWrite(fd, ac, 4, offset);
  37244. }
  37245. /*
  37246. ** Unlock the database file to level eLock, which must be either NO_LOCK
  37247. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  37248. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  37249. **
  37250. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  37251. ** called, do not modify it. See the comment above the #define of
  37252. ** UNKNOWN_LOCK for an explanation of this.
  37253. */
  37254. static int pagerUnlockDb(Pager *pPager, int eLock){
  37255. int rc = SQLITE_OK;
  37256. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  37257. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  37258. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  37259. if( isOpen(pPager->fd) ){
  37260. assert( pPager->eLock>=eLock );
  37261. rc = sqlite3OsUnlock(pPager->fd, eLock);
  37262. if( pPager->eLock!=UNKNOWN_LOCK ){
  37263. pPager->eLock = (u8)eLock;
  37264. }
  37265. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  37266. }
  37267. return rc;
  37268. }
  37269. /*
  37270. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  37271. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  37272. ** Pager.eLock variable to the new locking state.
  37273. **
  37274. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  37275. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  37276. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  37277. ** of this.
  37278. */
  37279. static int pagerLockDb(Pager *pPager, int eLock){
  37280. int rc = SQLITE_OK;
  37281. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  37282. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  37283. rc = sqlite3OsLock(pPager->fd, eLock);
  37284. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  37285. pPager->eLock = (u8)eLock;
  37286. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  37287. }
  37288. }
  37289. return rc;
  37290. }
  37291. /*
  37292. ** This function determines whether or not the atomic-write optimization
  37293. ** can be used with this pager. The optimization can be used if:
  37294. **
  37295. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  37296. ** a database page may be written atomically, and
  37297. ** (b) the value returned by OsSectorSize() is less than or equal
  37298. ** to the page size.
  37299. **
  37300. ** The optimization is also always enabled for temporary files. It is
  37301. ** an error to call this function if pPager is opened on an in-memory
  37302. ** database.
  37303. **
  37304. ** If the optimization cannot be used, 0 is returned. If it can be used,
  37305. ** then the value returned is the size of the journal file when it
  37306. ** contains rollback data for exactly one page.
  37307. */
  37308. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  37309. static int jrnlBufferSize(Pager *pPager){
  37310. assert( !MEMDB );
  37311. if( !pPager->tempFile ){
  37312. int dc; /* Device characteristics */
  37313. int nSector; /* Sector size */
  37314. int szPage; /* Page size */
  37315. assert( isOpen(pPager->fd) );
  37316. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  37317. nSector = pPager->sectorSize;
  37318. szPage = pPager->pageSize;
  37319. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  37320. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  37321. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  37322. return 0;
  37323. }
  37324. }
  37325. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  37326. }
  37327. #endif
  37328. /*
  37329. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  37330. ** on the cache using a hash function. This is used for testing
  37331. ** and debugging only.
  37332. */
  37333. #ifdef SQLITE_CHECK_PAGES
  37334. /*
  37335. ** Return a 32-bit hash of the page data for pPage.
  37336. */
  37337. static u32 pager_datahash(int nByte, unsigned char *pData){
  37338. u32 hash = 0;
  37339. int i;
  37340. for(i=0; i<nByte; i++){
  37341. hash = (hash*1039) + pData[i];
  37342. }
  37343. return hash;
  37344. }
  37345. static u32 pager_pagehash(PgHdr *pPage){
  37346. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  37347. }
  37348. static void pager_set_pagehash(PgHdr *pPage){
  37349. pPage->pageHash = pager_pagehash(pPage);
  37350. }
  37351. /*
  37352. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  37353. ** is defined, and NDEBUG is not defined, an assert() statement checks
  37354. ** that the page is either dirty or still matches the calculated page-hash.
  37355. */
  37356. #define CHECK_PAGE(x) checkPage(x)
  37357. static void checkPage(PgHdr *pPg){
  37358. Pager *pPager = pPg->pPager;
  37359. assert( pPager->eState!=PAGER_ERROR );
  37360. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  37361. }
  37362. #else
  37363. #define pager_datahash(X,Y) 0
  37364. #define pager_pagehash(X) 0
  37365. #define pager_set_pagehash(X)
  37366. #define CHECK_PAGE(x)
  37367. #endif /* SQLITE_CHECK_PAGES */
  37368. /*
  37369. ** When this is called the journal file for pager pPager must be open.
  37370. ** This function attempts to read a master journal file name from the
  37371. ** end of the file and, if successful, copies it into memory supplied
  37372. ** by the caller. See comments above writeMasterJournal() for the format
  37373. ** used to store a master journal file name at the end of a journal file.
  37374. **
  37375. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  37376. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  37377. ** enough space to write the master journal name). If the master journal
  37378. ** name in the journal is longer than nMaster bytes (including a
  37379. ** nul-terminator), then this is handled as if no master journal name
  37380. ** were present in the journal.
  37381. **
  37382. ** If a master journal file name is present at the end of the journal
  37383. ** file, then it is copied into the buffer pointed to by zMaster. A
  37384. ** nul-terminator byte is appended to the buffer following the master
  37385. ** journal file name.
  37386. **
  37387. ** If it is determined that no master journal file name is present
  37388. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  37389. **
  37390. ** If an error occurs while reading from the journal file, an SQLite
  37391. ** error code is returned.
  37392. */
  37393. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  37394. int rc; /* Return code */
  37395. u32 len; /* Length in bytes of master journal name */
  37396. i64 szJ; /* Total size in bytes of journal file pJrnl */
  37397. u32 cksum; /* MJ checksum value read from journal */
  37398. u32 u; /* Unsigned loop counter */
  37399. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  37400. zMaster[0] = '\0';
  37401. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  37402. || szJ<16
  37403. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  37404. || len>=nMaster
  37405. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  37406. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  37407. || memcmp(aMagic, aJournalMagic, 8)
  37408. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  37409. ){
  37410. return rc;
  37411. }
  37412. /* See if the checksum matches the master journal name */
  37413. for(u=0; u<len; u++){
  37414. cksum -= zMaster[u];
  37415. }
  37416. if( cksum ){
  37417. /* If the checksum doesn't add up, then one or more of the disk sectors
  37418. ** containing the master journal filename is corrupted. This means
  37419. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  37420. ** master-journal filename.
  37421. */
  37422. len = 0;
  37423. }
  37424. zMaster[len] = '\0';
  37425. return SQLITE_OK;
  37426. }
  37427. /*
  37428. ** Return the offset of the sector boundary at or immediately
  37429. ** following the value in pPager->journalOff, assuming a sector
  37430. ** size of pPager->sectorSize bytes.
  37431. **
  37432. ** i.e for a sector size of 512:
  37433. **
  37434. ** Pager.journalOff Return value
  37435. ** ---------------------------------------
  37436. ** 0 0
  37437. ** 512 512
  37438. ** 100 512
  37439. ** 2000 2048
  37440. **
  37441. */
  37442. static i64 journalHdrOffset(Pager *pPager){
  37443. i64 offset = 0;
  37444. i64 c = pPager->journalOff;
  37445. if( c ){
  37446. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  37447. }
  37448. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  37449. assert( offset>=c );
  37450. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  37451. return offset;
  37452. }
  37453. /*
  37454. ** The journal file must be open when this function is called.
  37455. **
  37456. ** This function is a no-op if the journal file has not been written to
  37457. ** within the current transaction (i.e. if Pager.journalOff==0).
  37458. **
  37459. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  37460. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  37461. ** zero the 28-byte header at the start of the journal file. In either case,
  37462. ** if the pager is not in no-sync mode, sync the journal file immediately
  37463. ** after writing or truncating it.
  37464. **
  37465. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  37466. ** following the truncation or zeroing described above the size of the
  37467. ** journal file in bytes is larger than this value, then truncate the
  37468. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  37469. ** not need to be synced following this operation.
  37470. **
  37471. ** If an IO error occurs, abandon processing and return the IO error code.
  37472. ** Otherwise, return SQLITE_OK.
  37473. */
  37474. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  37475. int rc = SQLITE_OK; /* Return code */
  37476. assert( isOpen(pPager->jfd) );
  37477. if( pPager->journalOff ){
  37478. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  37479. IOTRACE(("JZEROHDR %p\n", pPager))
  37480. if( doTruncate || iLimit==0 ){
  37481. rc = sqlite3OsTruncate(pPager->jfd, 0);
  37482. }else{
  37483. static const char zeroHdr[28] = {0};
  37484. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  37485. }
  37486. if( rc==SQLITE_OK && !pPager->noSync ){
  37487. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  37488. }
  37489. /* At this point the transaction is committed but the write lock
  37490. ** is still held on the file. If there is a size limit configured for
  37491. ** the persistent journal and the journal file currently consumes more
  37492. ** space than that limit allows for, truncate it now. There is no need
  37493. ** to sync the file following this operation.
  37494. */
  37495. if( rc==SQLITE_OK && iLimit>0 ){
  37496. i64 sz;
  37497. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  37498. if( rc==SQLITE_OK && sz>iLimit ){
  37499. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  37500. }
  37501. }
  37502. }
  37503. return rc;
  37504. }
  37505. /*
  37506. ** The journal file must be open when this routine is called. A journal
  37507. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  37508. ** current location.
  37509. **
  37510. ** The format for the journal header is as follows:
  37511. ** - 8 bytes: Magic identifying journal format.
  37512. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  37513. ** - 4 bytes: Random number used for page hash.
  37514. ** - 4 bytes: Initial database page count.
  37515. ** - 4 bytes: Sector size used by the process that wrote this journal.
  37516. ** - 4 bytes: Database page size.
  37517. **
  37518. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  37519. */
  37520. static int writeJournalHdr(Pager *pPager){
  37521. int rc = SQLITE_OK; /* Return code */
  37522. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  37523. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  37524. u32 nWrite; /* Bytes of header sector written */
  37525. int ii; /* Loop counter */
  37526. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  37527. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  37528. nHeader = JOURNAL_HDR_SZ(pPager);
  37529. }
  37530. /* If there are active savepoints and any of them were created
  37531. ** since the most recent journal header was written, update the
  37532. ** PagerSavepoint.iHdrOffset fields now.
  37533. */
  37534. for(ii=0; ii<pPager->nSavepoint; ii++){
  37535. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  37536. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  37537. }
  37538. }
  37539. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  37540. /*
  37541. ** Write the nRec Field - the number of page records that follow this
  37542. ** journal header. Normally, zero is written to this value at this time.
  37543. ** After the records are added to the journal (and the journal synced,
  37544. ** if in full-sync mode), the zero is overwritten with the true number
  37545. ** of records (see syncJournal()).
  37546. **
  37547. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  37548. ** reading the journal this value tells SQLite to assume that the
  37549. ** rest of the journal file contains valid page records. This assumption
  37550. ** is dangerous, as if a failure occurred whilst writing to the journal
  37551. ** file it may contain some garbage data. There are two scenarios
  37552. ** where this risk can be ignored:
  37553. **
  37554. ** * When the pager is in no-sync mode. Corruption can follow a
  37555. ** power failure in this case anyway.
  37556. **
  37557. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  37558. ** that garbage data is never appended to the journal file.
  37559. */
  37560. assert( isOpen(pPager->fd) || pPager->noSync );
  37561. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  37562. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  37563. ){
  37564. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  37565. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  37566. }else{
  37567. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  37568. }
  37569. /* The random check-hash initializer */
  37570. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  37571. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  37572. /* The initial database size */
  37573. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  37574. /* The assumed sector size for this process */
  37575. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  37576. /* The page size */
  37577. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  37578. /* Initializing the tail of the buffer is not necessary. Everything
  37579. ** works find if the following memset() is omitted. But initializing
  37580. ** the memory prevents valgrind from complaining, so we are willing to
  37581. ** take the performance hit.
  37582. */
  37583. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  37584. nHeader-(sizeof(aJournalMagic)+20));
  37585. /* In theory, it is only necessary to write the 28 bytes that the
  37586. ** journal header consumes to the journal file here. Then increment the
  37587. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  37588. ** record is written to the following sector (leaving a gap in the file
  37589. ** that will be implicitly filled in by the OS).
  37590. **
  37591. ** However it has been discovered that on some systems this pattern can
  37592. ** be significantly slower than contiguously writing data to the file,
  37593. ** even if that means explicitly writing data to the block of
  37594. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  37595. ** is done.
  37596. **
  37597. ** The loop is required here in case the sector-size is larger than the
  37598. ** database page size. Since the zHeader buffer is only Pager.pageSize
  37599. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  37600. ** to populate the entire journal header sector.
  37601. */
  37602. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  37603. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  37604. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  37605. assert( pPager->journalHdr <= pPager->journalOff );
  37606. pPager->journalOff += nHeader;
  37607. }
  37608. return rc;
  37609. }
  37610. /*
  37611. ** The journal file must be open when this is called. A journal header file
  37612. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  37613. ** file. The current location in the journal file is given by
  37614. ** pPager->journalOff. See comments above function writeJournalHdr() for
  37615. ** a description of the journal header format.
  37616. **
  37617. ** If the header is read successfully, *pNRec is set to the number of
  37618. ** page records following this header and *pDbSize is set to the size of the
  37619. ** database before the transaction began, in pages. Also, pPager->cksumInit
  37620. ** is set to the value read from the journal header. SQLITE_OK is returned
  37621. ** in this case.
  37622. **
  37623. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  37624. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  37625. ** cannot be read from the journal file an error code is returned.
  37626. */
  37627. static int readJournalHdr(
  37628. Pager *pPager, /* Pager object */
  37629. int isHot,
  37630. i64 journalSize, /* Size of the open journal file in bytes */
  37631. u32 *pNRec, /* OUT: Value read from the nRec field */
  37632. u32 *pDbSize /* OUT: Value of original database size field */
  37633. ){
  37634. int rc; /* Return code */
  37635. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  37636. i64 iHdrOff; /* Offset of journal header being read */
  37637. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  37638. /* Advance Pager.journalOff to the start of the next sector. If the
  37639. ** journal file is too small for there to be a header stored at this
  37640. ** point, return SQLITE_DONE.
  37641. */
  37642. pPager->journalOff = journalHdrOffset(pPager);
  37643. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  37644. return SQLITE_DONE;
  37645. }
  37646. iHdrOff = pPager->journalOff;
  37647. /* Read in the first 8 bytes of the journal header. If they do not match
  37648. ** the magic string found at the start of each journal header, return
  37649. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  37650. ** proceed.
  37651. */
  37652. if( isHot || iHdrOff!=pPager->journalHdr ){
  37653. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  37654. if( rc ){
  37655. return rc;
  37656. }
  37657. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  37658. return SQLITE_DONE;
  37659. }
  37660. }
  37661. /* Read the first three 32-bit fields of the journal header: The nRec
  37662. ** field, the checksum-initializer and the database size at the start
  37663. ** of the transaction. Return an error code if anything goes wrong.
  37664. */
  37665. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  37666. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  37667. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  37668. ){
  37669. return rc;
  37670. }
  37671. if( pPager->journalOff==0 ){
  37672. u32 iPageSize; /* Page-size field of journal header */
  37673. u32 iSectorSize; /* Sector-size field of journal header */
  37674. /* Read the page-size and sector-size journal header fields. */
  37675. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  37676. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  37677. ){
  37678. return rc;
  37679. }
  37680. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  37681. ** journal header to zero. In this case, assume that the Pager.pageSize
  37682. ** variable is already set to the correct page size.
  37683. */
  37684. if( iPageSize==0 ){
  37685. iPageSize = pPager->pageSize;
  37686. }
  37687. /* Check that the values read from the page-size and sector-size fields
  37688. ** are within range. To be 'in range', both values need to be a power
  37689. ** of two greater than or equal to 512 or 32, and not greater than their
  37690. ** respective compile time maximum limits.
  37691. */
  37692. if( iPageSize<512 || iSectorSize<32
  37693. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  37694. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  37695. ){
  37696. /* If the either the page-size or sector-size in the journal-header is
  37697. ** invalid, then the process that wrote the journal-header must have
  37698. ** crashed before the header was synced. In this case stop reading
  37699. ** the journal file here.
  37700. */
  37701. return SQLITE_DONE;
  37702. }
  37703. /* Update the page-size to match the value read from the journal.
  37704. ** Use a testcase() macro to make sure that malloc failure within
  37705. ** PagerSetPagesize() is tested.
  37706. */
  37707. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  37708. testcase( rc!=SQLITE_OK );
  37709. /* Update the assumed sector-size to match the value used by
  37710. ** the process that created this journal. If this journal was
  37711. ** created by a process other than this one, then this routine
  37712. ** is being called from within pager_playback(). The local value
  37713. ** of Pager.sectorSize is restored at the end of that routine.
  37714. */
  37715. pPager->sectorSize = iSectorSize;
  37716. }
  37717. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  37718. return rc;
  37719. }
  37720. /*
  37721. ** Write the supplied master journal name into the journal file for pager
  37722. ** pPager at the current location. The master journal name must be the last
  37723. ** thing written to a journal file. If the pager is in full-sync mode, the
  37724. ** journal file descriptor is advanced to the next sector boundary before
  37725. ** anything is written. The format is:
  37726. **
  37727. ** + 4 bytes: PAGER_MJ_PGNO.
  37728. ** + N bytes: Master journal filename in utf-8.
  37729. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  37730. ** + 4 bytes: Master journal name checksum.
  37731. ** + 8 bytes: aJournalMagic[].
  37732. **
  37733. ** The master journal page checksum is the sum of the bytes in the master
  37734. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  37735. **
  37736. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  37737. ** this call is a no-op.
  37738. */
  37739. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  37740. int rc; /* Return code */
  37741. int nMaster; /* Length of string zMaster */
  37742. i64 iHdrOff; /* Offset of header in journal file */
  37743. i64 jrnlSize; /* Size of journal file on disk */
  37744. u32 cksum = 0; /* Checksum of string zMaster */
  37745. assert( pPager->setMaster==0 );
  37746. assert( !pagerUseWal(pPager) );
  37747. if( !zMaster
  37748. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  37749. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  37750. ){
  37751. return SQLITE_OK;
  37752. }
  37753. pPager->setMaster = 1;
  37754. assert( isOpen(pPager->jfd) );
  37755. assert( pPager->journalHdr <= pPager->journalOff );
  37756. /* Calculate the length in bytes and the checksum of zMaster */
  37757. for(nMaster=0; zMaster[nMaster]; nMaster++){
  37758. cksum += zMaster[nMaster];
  37759. }
  37760. /* If in full-sync mode, advance to the next disk sector before writing
  37761. ** the master journal name. This is in case the previous page written to
  37762. ** the journal has already been synced.
  37763. */
  37764. if( pPager->fullSync ){
  37765. pPager->journalOff = journalHdrOffset(pPager);
  37766. }
  37767. iHdrOff = pPager->journalOff;
  37768. /* Write the master journal data to the end of the journal file. If
  37769. ** an error occurs, return the error code to the caller.
  37770. */
  37771. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  37772. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  37773. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  37774. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  37775. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  37776. ){
  37777. return rc;
  37778. }
  37779. pPager->journalOff += (nMaster+20);
  37780. /* If the pager is in peristent-journal mode, then the physical
  37781. ** journal-file may extend past the end of the master-journal name
  37782. ** and 8 bytes of magic data just written to the file. This is
  37783. ** dangerous because the code to rollback a hot-journal file
  37784. ** will not be able to find the master-journal name to determine
  37785. ** whether or not the journal is hot.
  37786. **
  37787. ** Easiest thing to do in this scenario is to truncate the journal
  37788. ** file to the required size.
  37789. */
  37790. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  37791. && jrnlSize>pPager->journalOff
  37792. ){
  37793. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  37794. }
  37795. return rc;
  37796. }
  37797. /*
  37798. ** Find a page in the hash table given its page number. Return
  37799. ** a pointer to the page or NULL if the requested page is not
  37800. ** already in memory.
  37801. */
  37802. static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  37803. PgHdr *p; /* Return value */
  37804. /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  37805. ** fail, since no attempt to allocate dynamic memory will be made.
  37806. */
  37807. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  37808. return p;
  37809. }
  37810. /*
  37811. ** Discard the entire contents of the in-memory page-cache.
  37812. */
  37813. static void pager_reset(Pager *pPager){
  37814. sqlite3BackupRestart(pPager->pBackup);
  37815. sqlite3PcacheClear(pPager->pPCache);
  37816. }
  37817. /*
  37818. ** Free all structures in the Pager.aSavepoint[] array and set both
  37819. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  37820. ** if it is open and the pager is not in exclusive mode.
  37821. */
  37822. static void releaseAllSavepoints(Pager *pPager){
  37823. int ii; /* Iterator for looping through Pager.aSavepoint */
  37824. for(ii=0; ii<pPager->nSavepoint; ii++){
  37825. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  37826. }
  37827. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  37828. sqlite3OsClose(pPager->sjfd);
  37829. }
  37830. sqlite3_free(pPager->aSavepoint);
  37831. pPager->aSavepoint = 0;
  37832. pPager->nSavepoint = 0;
  37833. pPager->nSubRec = 0;
  37834. }
  37835. /*
  37836. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  37837. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  37838. ** or SQLITE_NOMEM if a malloc failure occurs.
  37839. */
  37840. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  37841. int ii; /* Loop counter */
  37842. int rc = SQLITE_OK; /* Result code */
  37843. for(ii=0; ii<pPager->nSavepoint; ii++){
  37844. PagerSavepoint *p = &pPager->aSavepoint[ii];
  37845. if( pgno<=p->nOrig ){
  37846. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  37847. testcase( rc==SQLITE_NOMEM );
  37848. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  37849. }
  37850. }
  37851. return rc;
  37852. }
  37853. /*
  37854. ** This function is a no-op if the pager is in exclusive mode and not
  37855. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  37856. ** state.
  37857. **
  37858. ** If the pager is not in exclusive-access mode, the database file is
  37859. ** completely unlocked. If the file is unlocked and the file-system does
  37860. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  37861. ** closed (if it is open).
  37862. **
  37863. ** If the pager is in ERROR state when this function is called, the
  37864. ** contents of the pager cache are discarded before switching back to
  37865. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  37866. ** or not, any journal file left in the file-system will be treated
  37867. ** as a hot-journal and rolled back the next time a read-transaction
  37868. ** is opened (by this or by any other connection).
  37869. */
  37870. static void pager_unlock(Pager *pPager){
  37871. assert( pPager->eState==PAGER_READER
  37872. || pPager->eState==PAGER_OPEN
  37873. || pPager->eState==PAGER_ERROR
  37874. );
  37875. sqlite3BitvecDestroy(pPager->pInJournal);
  37876. pPager->pInJournal = 0;
  37877. releaseAllSavepoints(pPager);
  37878. if( pagerUseWal(pPager) ){
  37879. assert( !isOpen(pPager->jfd) );
  37880. sqlite3WalEndReadTransaction(pPager->pWal);
  37881. pPager->eState = PAGER_OPEN;
  37882. }else if( !pPager->exclusiveMode ){
  37883. int rc; /* Error code returned by pagerUnlockDb() */
  37884. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  37885. /* If the operating system support deletion of open files, then
  37886. ** close the journal file when dropping the database lock. Otherwise
  37887. ** another connection with journal_mode=delete might delete the file
  37888. ** out from under us.
  37889. */
  37890. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  37891. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  37892. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  37893. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  37894. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  37895. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  37896. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  37897. || 1!=(pPager->journalMode & 5)
  37898. ){
  37899. sqlite3OsClose(pPager->jfd);
  37900. }
  37901. /* If the pager is in the ERROR state and the call to unlock the database
  37902. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  37903. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  37904. ** is necessary.
  37905. */
  37906. rc = pagerUnlockDb(pPager, NO_LOCK);
  37907. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  37908. pPager->eLock = UNKNOWN_LOCK;
  37909. }
  37910. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  37911. ** without clearing the error code. This is intentional - the error
  37912. ** code is cleared and the cache reset in the block below.
  37913. */
  37914. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  37915. pPager->changeCountDone = 0;
  37916. pPager->eState = PAGER_OPEN;
  37917. }
  37918. /* If Pager.errCode is set, the contents of the pager cache cannot be
  37919. ** trusted. Now that there are no outstanding references to the pager,
  37920. ** it can safely move back to PAGER_OPEN state. This happens in both
  37921. ** normal and exclusive-locking mode.
  37922. */
  37923. if( pPager->errCode ){
  37924. assert( !MEMDB );
  37925. pager_reset(pPager);
  37926. pPager->changeCountDone = pPager->tempFile;
  37927. pPager->eState = PAGER_OPEN;
  37928. pPager->errCode = SQLITE_OK;
  37929. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  37930. }
  37931. pPager->journalOff = 0;
  37932. pPager->journalHdr = 0;
  37933. pPager->setMaster = 0;
  37934. }
  37935. /*
  37936. ** This function is called whenever an IOERR or FULL error that requires
  37937. ** the pager to transition into the ERROR state may ahve occurred.
  37938. ** The first argument is a pointer to the pager structure, the second
  37939. ** the error-code about to be returned by a pager API function. The
  37940. ** value returned is a copy of the second argument to this function.
  37941. **
  37942. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  37943. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  37944. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  37945. ** all major API calls on the Pager will immediately return Pager.errCode.
  37946. **
  37947. ** The ERROR state indicates that the contents of the pager-cache
  37948. ** cannot be trusted. This state can be cleared by completely discarding
  37949. ** the contents of the pager-cache. If a transaction was active when
  37950. ** the persistent error occurred, then the rollback journal may need
  37951. ** to be replayed to restore the contents of the database file (as if
  37952. ** it were a hot-journal).
  37953. */
  37954. static int pager_error(Pager *pPager, int rc){
  37955. int rc2 = rc & 0xff;
  37956. assert( rc==SQLITE_OK || !MEMDB );
  37957. assert(
  37958. pPager->errCode==SQLITE_FULL ||
  37959. pPager->errCode==SQLITE_OK ||
  37960. (pPager->errCode & 0xff)==SQLITE_IOERR
  37961. );
  37962. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  37963. pPager->errCode = rc;
  37964. pPager->eState = PAGER_ERROR;
  37965. }
  37966. return rc;
  37967. }
  37968. static int pager_truncate(Pager *pPager, Pgno nPage);
  37969. /*
  37970. ** This routine ends a transaction. A transaction is usually ended by
  37971. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  37972. ** after rollback of a hot-journal, or if an error occurs while opening
  37973. ** the journal file or writing the very first journal-header of a
  37974. ** database transaction.
  37975. **
  37976. ** This routine is never called in PAGER_ERROR state. If it is called
  37977. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  37978. ** exclusive than a RESERVED lock, it is a no-op.
  37979. **
  37980. ** Otherwise, any active savepoints are released.
  37981. **
  37982. ** If the journal file is open, then it is "finalized". Once a journal
  37983. ** file has been finalized it is not possible to use it to roll back a
  37984. ** transaction. Nor will it be considered to be a hot-journal by this
  37985. ** or any other database connection. Exactly how a journal is finalized
  37986. ** depends on whether or not the pager is running in exclusive mode and
  37987. ** the current journal-mode (Pager.journalMode value), as follows:
  37988. **
  37989. ** journalMode==MEMORY
  37990. ** Journal file descriptor is simply closed. This destroys an
  37991. ** in-memory journal.
  37992. **
  37993. ** journalMode==TRUNCATE
  37994. ** Journal file is truncated to zero bytes in size.
  37995. **
  37996. ** journalMode==PERSIST
  37997. ** The first 28 bytes of the journal file are zeroed. This invalidates
  37998. ** the first journal header in the file, and hence the entire journal
  37999. ** file. An invalid journal file cannot be rolled back.
  38000. **
  38001. ** journalMode==DELETE
  38002. ** The journal file is closed and deleted using sqlite3OsDelete().
  38003. **
  38004. ** If the pager is running in exclusive mode, this method of finalizing
  38005. ** the journal file is never used. Instead, if the journalMode is
  38006. ** DELETE and the pager is in exclusive mode, the method described under
  38007. ** journalMode==PERSIST is used instead.
  38008. **
  38009. ** After the journal is finalized, the pager moves to PAGER_READER state.
  38010. ** If running in non-exclusive rollback mode, the lock on the file is
  38011. ** downgraded to a SHARED_LOCK.
  38012. **
  38013. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  38014. ** any of the IO operations to finalize the journal file or unlock the
  38015. ** database then the IO error code is returned to the user. If the
  38016. ** operation to finalize the journal file fails, then the code still
  38017. ** tries to unlock the database file if not in exclusive mode. If the
  38018. ** unlock operation fails as well, then the first error code related
  38019. ** to the first error encountered (the journal finalization one) is
  38020. ** returned.
  38021. */
  38022. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  38023. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  38024. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  38025. /* Do nothing if the pager does not have an open write transaction
  38026. ** or at least a RESERVED lock. This function may be called when there
  38027. ** is no write-transaction active but a RESERVED or greater lock is
  38028. ** held under two circumstances:
  38029. **
  38030. ** 1. After a successful hot-journal rollback, it is called with
  38031. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  38032. **
  38033. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  38034. ** lock switches back to locking_mode=normal and then executes a
  38035. ** read-transaction, this function is called with eState==PAGER_READER
  38036. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  38037. */
  38038. assert( assert_pager_state(pPager) );
  38039. assert( pPager->eState!=PAGER_ERROR );
  38040. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  38041. return SQLITE_OK;
  38042. }
  38043. releaseAllSavepoints(pPager);
  38044. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  38045. if( isOpen(pPager->jfd) ){
  38046. assert( !pagerUseWal(pPager) );
  38047. /* Finalize the journal file. */
  38048. if( sqlite3IsMemJournal(pPager->jfd) ){
  38049. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  38050. sqlite3OsClose(pPager->jfd);
  38051. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  38052. if( pPager->journalOff==0 ){
  38053. rc = SQLITE_OK;
  38054. }else{
  38055. rc = sqlite3OsTruncate(pPager->jfd, 0);
  38056. }
  38057. pPager->journalOff = 0;
  38058. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  38059. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  38060. ){
  38061. rc = zeroJournalHdr(pPager, hasMaster);
  38062. pPager->journalOff = 0;
  38063. }else{
  38064. /* This branch may be executed with Pager.journalMode==MEMORY if
  38065. ** a hot-journal was just rolled back. In this case the journal
  38066. ** file should be closed and deleted. If this connection writes to
  38067. ** the database file, it will do so using an in-memory journal.
  38068. */
  38069. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  38070. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  38071. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  38072. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  38073. );
  38074. sqlite3OsClose(pPager->jfd);
  38075. if( bDelete ){
  38076. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  38077. }
  38078. }
  38079. }
  38080. #ifdef SQLITE_CHECK_PAGES
  38081. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  38082. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  38083. PgHdr *p = pager_lookup(pPager, 1);
  38084. if( p ){
  38085. p->pageHash = 0;
  38086. sqlite3PagerUnref(p);
  38087. }
  38088. }
  38089. #endif
  38090. sqlite3BitvecDestroy(pPager->pInJournal);
  38091. pPager->pInJournal = 0;
  38092. pPager->nRec = 0;
  38093. sqlite3PcacheCleanAll(pPager->pPCache);
  38094. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  38095. if( pagerUseWal(pPager) ){
  38096. /* Drop the WAL write-lock, if any. Also, if the connection was in
  38097. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  38098. ** lock held on the database file.
  38099. */
  38100. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  38101. assert( rc2==SQLITE_OK );
  38102. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  38103. /* This branch is taken when committing a transaction in rollback-journal
  38104. ** mode if the database file on disk is larger than the database image.
  38105. ** At this point the journal has been finalized and the transaction
  38106. ** successfully committed, but the EXCLUSIVE lock is still held on the
  38107. ** file. So it is safe to truncate the database file to its minimum
  38108. ** required size. */
  38109. assert( pPager->eLock==EXCLUSIVE_LOCK );
  38110. rc = pager_truncate(pPager, pPager->dbSize);
  38111. }
  38112. if( !pPager->exclusiveMode
  38113. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  38114. ){
  38115. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  38116. pPager->changeCountDone = 0;
  38117. }
  38118. pPager->eState = PAGER_READER;
  38119. pPager->setMaster = 0;
  38120. return (rc==SQLITE_OK?rc2:rc);
  38121. }
  38122. /*
  38123. ** Execute a rollback if a transaction is active and unlock the
  38124. ** database file.
  38125. **
  38126. ** If the pager has already entered the ERROR state, do not attempt
  38127. ** the rollback at this time. Instead, pager_unlock() is called. The
  38128. ** call to pager_unlock() will discard all in-memory pages, unlock
  38129. ** the database file and move the pager back to OPEN state. If this
  38130. ** means that there is a hot-journal left in the file-system, the next
  38131. ** connection to obtain a shared lock on the pager (which may be this one)
  38132. ** will roll it back.
  38133. **
  38134. ** If the pager has not already entered the ERROR state, but an IO or
  38135. ** malloc error occurs during a rollback, then this will itself cause
  38136. ** the pager to enter the ERROR state. Which will be cleared by the
  38137. ** call to pager_unlock(), as described above.
  38138. */
  38139. static void pagerUnlockAndRollback(Pager *pPager){
  38140. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  38141. assert( assert_pager_state(pPager) );
  38142. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  38143. sqlite3BeginBenignMalloc();
  38144. sqlite3PagerRollback(pPager);
  38145. sqlite3EndBenignMalloc();
  38146. }else if( !pPager->exclusiveMode ){
  38147. assert( pPager->eState==PAGER_READER );
  38148. pager_end_transaction(pPager, 0, 0);
  38149. }
  38150. }
  38151. pager_unlock(pPager);
  38152. }
  38153. /*
  38154. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  38155. ** of data. Compute and return a checksum based ont the contents of the
  38156. ** page of data and the current value of pPager->cksumInit.
  38157. **
  38158. ** This is not a real checksum. It is really just the sum of the
  38159. ** random initial value (pPager->cksumInit) and every 200th byte
  38160. ** of the page data, starting with byte offset (pPager->pageSize%200).
  38161. ** Each byte is interpreted as an 8-bit unsigned integer.
  38162. **
  38163. ** Changing the formula used to compute this checksum results in an
  38164. ** incompatible journal file format.
  38165. **
  38166. ** If journal corruption occurs due to a power failure, the most likely
  38167. ** scenario is that one end or the other of the record will be changed.
  38168. ** It is much less likely that the two ends of the journal record will be
  38169. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  38170. ** though fast and simple, catches the mostly likely kind of corruption.
  38171. */
  38172. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  38173. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  38174. int i = pPager->pageSize-200; /* Loop counter */
  38175. while( i>0 ){
  38176. cksum += aData[i];
  38177. i -= 200;
  38178. }
  38179. return cksum;
  38180. }
  38181. /*
  38182. ** Report the current page size and number of reserved bytes back
  38183. ** to the codec.
  38184. */
  38185. #ifdef SQLITE_HAS_CODEC
  38186. static void pagerReportSize(Pager *pPager){
  38187. if( pPager->xCodecSizeChng ){
  38188. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  38189. (int)pPager->nReserve);
  38190. }
  38191. }
  38192. #else
  38193. # define pagerReportSize(X) /* No-op if we do not support a codec */
  38194. #endif
  38195. /*
  38196. ** Read a single page from either the journal file (if isMainJrnl==1) or
  38197. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  38198. ** The page begins at offset *pOffset into the file. The *pOffset
  38199. ** value is increased to the start of the next page in the journal.
  38200. **
  38201. ** The main rollback journal uses checksums - the statement journal does
  38202. ** not.
  38203. **
  38204. ** If the page number of the page record read from the (sub-)journal file
  38205. ** is greater than the current value of Pager.dbSize, then playback is
  38206. ** skipped and SQLITE_OK is returned.
  38207. **
  38208. ** If pDone is not NULL, then it is a record of pages that have already
  38209. ** been played back. If the page at *pOffset has already been played back
  38210. ** (if the corresponding pDone bit is set) then skip the playback.
  38211. ** Make sure the pDone bit corresponding to the *pOffset page is set
  38212. ** prior to returning.
  38213. **
  38214. ** If the page record is successfully read from the (sub-)journal file
  38215. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  38216. ** while reading the record from the (sub-)journal file or while writing
  38217. ** to the database file, then the IO error code is returned. If data
  38218. ** is successfully read from the (sub-)journal file but appears to be
  38219. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  38220. ** two circumstances:
  38221. **
  38222. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  38223. ** * If the record is being rolled back from the main journal file
  38224. ** and the checksum field does not match the record content.
  38225. **
  38226. ** Neither of these two scenarios are possible during a savepoint rollback.
  38227. **
  38228. ** If this is a savepoint rollback, then memory may have to be dynamically
  38229. ** allocated by this function. If this is the case and an allocation fails,
  38230. ** SQLITE_NOMEM is returned.
  38231. */
  38232. static int pager_playback_one_page(
  38233. Pager *pPager, /* The pager being played back */
  38234. i64 *pOffset, /* Offset of record to playback */
  38235. Bitvec *pDone, /* Bitvec of pages already played back */
  38236. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  38237. int isSavepnt /* True for a savepoint rollback */
  38238. ){
  38239. int rc;
  38240. PgHdr *pPg; /* An existing page in the cache */
  38241. Pgno pgno; /* The page number of a page in journal */
  38242. u32 cksum; /* Checksum used for sanity checking */
  38243. char *aData; /* Temporary storage for the page */
  38244. sqlite3_file *jfd; /* The file descriptor for the journal file */
  38245. int isSynced; /* True if journal page is synced */
  38246. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  38247. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  38248. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  38249. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  38250. aData = pPager->pTmpSpace;
  38251. assert( aData ); /* Temp storage must have already been allocated */
  38252. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  38253. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  38254. ** or savepoint rollback done at the request of the caller) or this is
  38255. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  38256. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  38257. ** only reads from the main journal, not the sub-journal.
  38258. */
  38259. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  38260. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  38261. );
  38262. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  38263. /* Read the page number and page data from the journal or sub-journal
  38264. ** file. Return an error code to the caller if an IO error occurs.
  38265. */
  38266. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  38267. rc = read32bits(jfd, *pOffset, &pgno);
  38268. if( rc!=SQLITE_OK ) return rc;
  38269. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  38270. if( rc!=SQLITE_OK ) return rc;
  38271. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  38272. /* Sanity checking on the page. This is more important that I originally
  38273. ** thought. If a power failure occurs while the journal is being written,
  38274. ** it could cause invalid data to be written into the journal. We need to
  38275. ** detect this invalid data (with high probability) and ignore it.
  38276. */
  38277. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  38278. assert( !isSavepnt );
  38279. return SQLITE_DONE;
  38280. }
  38281. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  38282. return SQLITE_OK;
  38283. }
  38284. if( isMainJrnl ){
  38285. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  38286. if( rc ) return rc;
  38287. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  38288. return SQLITE_DONE;
  38289. }
  38290. }
  38291. /* If this page has already been played by before during the current
  38292. ** rollback, then don't bother to play it back again.
  38293. */
  38294. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  38295. return rc;
  38296. }
  38297. /* When playing back page 1, restore the nReserve setting
  38298. */
  38299. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  38300. pPager->nReserve = ((u8*)aData)[20];
  38301. pagerReportSize(pPager);
  38302. }
  38303. /* If the pager is in CACHEMOD state, then there must be a copy of this
  38304. ** page in the pager cache. In this case just update the pager cache,
  38305. ** not the database file. The page is left marked dirty in this case.
  38306. **
  38307. ** An exception to the above rule: If the database is in no-sync mode
  38308. ** and a page is moved during an incremental vacuum then the page may
  38309. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  38310. ** during a Movepage() call, then the page may not be in the cache
  38311. ** either. So the condition described in the above paragraph is not
  38312. ** assert()able.
  38313. **
  38314. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  38315. ** pager cache if it exists and the main file. The page is then marked
  38316. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  38317. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  38318. ** if the pager is in OPEN state.
  38319. **
  38320. ** Ticket #1171: The statement journal might contain page content that is
  38321. ** different from the page content at the start of the transaction.
  38322. ** This occurs when a page is changed prior to the start of a statement
  38323. ** then changed again within the statement. When rolling back such a
  38324. ** statement we must not write to the original database unless we know
  38325. ** for certain that original page contents are synced into the main rollback
  38326. ** journal. Otherwise, a power loss might leave modified data in the
  38327. ** database file without an entry in the rollback journal that can
  38328. ** restore the database to its original form. Two conditions must be
  38329. ** met before writing to the database files. (1) the database must be
  38330. ** locked. (2) we know that the original page content is fully synced
  38331. ** in the main journal either because the page is not in cache or else
  38332. ** the page is marked as needSync==0.
  38333. **
  38334. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  38335. ** is possible to fail a statement on a database that does not yet exist.
  38336. ** Do not attempt to write if database file has never been opened.
  38337. */
  38338. if( pagerUseWal(pPager) ){
  38339. pPg = 0;
  38340. }else{
  38341. pPg = pager_lookup(pPager, pgno);
  38342. }
  38343. assert( pPg || !MEMDB );
  38344. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  38345. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  38346. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  38347. (isMainJrnl?"main-journal":"sub-journal")
  38348. ));
  38349. if( isMainJrnl ){
  38350. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  38351. }else{
  38352. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  38353. }
  38354. if( isOpen(pPager->fd)
  38355. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  38356. && isSynced
  38357. ){
  38358. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  38359. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  38360. assert( !pagerUseWal(pPager) );
  38361. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  38362. if( pgno>pPager->dbFileSize ){
  38363. pPager->dbFileSize = pgno;
  38364. }
  38365. if( pPager->pBackup ){
  38366. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  38367. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  38368. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  38369. }
  38370. }else if( !isMainJrnl && pPg==0 ){
  38371. /* If this is a rollback of a savepoint and data was not written to
  38372. ** the database and the page is not in-memory, there is a potential
  38373. ** problem. When the page is next fetched by the b-tree layer, it
  38374. ** will be read from the database file, which may or may not be
  38375. ** current.
  38376. **
  38377. ** There are a couple of different ways this can happen. All are quite
  38378. ** obscure. When running in synchronous mode, this can only happen
  38379. ** if the page is on the free-list at the start of the transaction, then
  38380. ** populated, then moved using sqlite3PagerMovepage().
  38381. **
  38382. ** The solution is to add an in-memory page to the cache containing
  38383. ** the data just read from the sub-journal. Mark the page as dirty
  38384. ** and if the pager requires a journal-sync, then mark the page as
  38385. ** requiring a journal-sync before it is written.
  38386. */
  38387. assert( isSavepnt );
  38388. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  38389. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  38390. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  38391. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  38392. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  38393. if( rc!=SQLITE_OK ) return rc;
  38394. pPg->flags &= ~PGHDR_NEED_READ;
  38395. sqlite3PcacheMakeDirty(pPg);
  38396. }
  38397. if( pPg ){
  38398. /* No page should ever be explicitly rolled back that is in use, except
  38399. ** for page 1 which is held in use in order to keep the lock on the
  38400. ** database active. However such a page may be rolled back as a result
  38401. ** of an internal error resulting in an automatic call to
  38402. ** sqlite3PagerRollback().
  38403. */
  38404. void *pData;
  38405. pData = pPg->pData;
  38406. memcpy(pData, (u8*)aData, pPager->pageSize);
  38407. pPager->xReiniter(pPg);
  38408. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  38409. /* If the contents of this page were just restored from the main
  38410. ** journal file, then its content must be as they were when the
  38411. ** transaction was first opened. In this case we can mark the page
  38412. ** as clean, since there will be no need to write it out to the
  38413. ** database.
  38414. **
  38415. ** There is one exception to this rule. If the page is being rolled
  38416. ** back as part of a savepoint (or statement) rollback from an
  38417. ** unsynced portion of the main journal file, then it is not safe
  38418. ** to mark the page as clean. This is because marking the page as
  38419. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  38420. ** already in the journal file (recorded in Pager.pInJournal) and
  38421. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  38422. ** again within this transaction, it will be marked as dirty but
  38423. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  38424. ** be written out into the database file before its journal file
  38425. ** segment is synced. If a crash occurs during or following this,
  38426. ** database corruption may ensue.
  38427. */
  38428. assert( !pagerUseWal(pPager) );
  38429. sqlite3PcacheMakeClean(pPg);
  38430. }
  38431. pager_set_pagehash(pPg);
  38432. /* If this was page 1, then restore the value of Pager.dbFileVers.
  38433. ** Do this before any decoding. */
  38434. if( pgno==1 ){
  38435. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  38436. }
  38437. /* Decode the page just read from disk */
  38438. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  38439. sqlite3PcacheRelease(pPg);
  38440. }
  38441. return rc;
  38442. }
  38443. /*
  38444. ** Parameter zMaster is the name of a master journal file. A single journal
  38445. ** file that referred to the master journal file has just been rolled back.
  38446. ** This routine checks if it is possible to delete the master journal file,
  38447. ** and does so if it is.
  38448. **
  38449. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  38450. ** available for use within this function.
  38451. **
  38452. ** When a master journal file is created, it is populated with the names
  38453. ** of all of its child journals, one after another, formatted as utf-8
  38454. ** encoded text. The end of each child journal file is marked with a
  38455. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  38456. ** file for a transaction involving two databases might be:
  38457. **
  38458. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  38459. **
  38460. ** A master journal file may only be deleted once all of its child
  38461. ** journals have been rolled back.
  38462. **
  38463. ** This function reads the contents of the master-journal file into
  38464. ** memory and loops through each of the child journal names. For
  38465. ** each child journal, it checks if:
  38466. **
  38467. ** * if the child journal exists, and if so
  38468. ** * if the child journal contains a reference to master journal
  38469. ** file zMaster
  38470. **
  38471. ** If a child journal can be found that matches both of the criteria
  38472. ** above, this function returns without doing anything. Otherwise, if
  38473. ** no such child journal can be found, file zMaster is deleted from
  38474. ** the file-system using sqlite3OsDelete().
  38475. **
  38476. ** If an IO error within this function, an error code is returned. This
  38477. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  38478. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  38479. ** occur, SQLITE_OK is returned.
  38480. **
  38481. ** TODO: This function allocates a single block of memory to load
  38482. ** the entire contents of the master journal file. This could be
  38483. ** a couple of kilobytes or so - potentially larger than the page
  38484. ** size.
  38485. */
  38486. static int pager_delmaster(Pager *pPager, const char *zMaster){
  38487. sqlite3_vfs *pVfs = pPager->pVfs;
  38488. int rc; /* Return code */
  38489. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  38490. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  38491. char *zMasterJournal = 0; /* Contents of master journal file */
  38492. i64 nMasterJournal; /* Size of master journal file */
  38493. char *zJournal; /* Pointer to one journal within MJ file */
  38494. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  38495. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  38496. /* Allocate space for both the pJournal and pMaster file descriptors.
  38497. ** If successful, open the master journal file for reading.
  38498. */
  38499. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  38500. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  38501. if( !pMaster ){
  38502. rc = SQLITE_NOMEM;
  38503. }else{
  38504. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  38505. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  38506. }
  38507. if( rc!=SQLITE_OK ) goto delmaster_out;
  38508. /* Load the entire master journal file into space obtained from
  38509. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  38510. ** sufficient space (in zMasterPtr) to hold the names of master
  38511. ** journal files extracted from regular rollback-journals.
  38512. */
  38513. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  38514. if( rc!=SQLITE_OK ) goto delmaster_out;
  38515. nMasterPtr = pVfs->mxPathname+1;
  38516. zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
  38517. if( !zMasterJournal ){
  38518. rc = SQLITE_NOMEM;
  38519. goto delmaster_out;
  38520. }
  38521. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  38522. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  38523. if( rc!=SQLITE_OK ) goto delmaster_out;
  38524. zMasterJournal[nMasterJournal] = 0;
  38525. zJournal = zMasterJournal;
  38526. while( (zJournal-zMasterJournal)<nMasterJournal ){
  38527. int exists;
  38528. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  38529. if( rc!=SQLITE_OK ){
  38530. goto delmaster_out;
  38531. }
  38532. if( exists ){
  38533. /* One of the journals pointed to by the master journal exists.
  38534. ** Open it and check if it points at the master journal. If
  38535. ** so, return without deleting the master journal file.
  38536. */
  38537. int c;
  38538. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  38539. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  38540. if( rc!=SQLITE_OK ){
  38541. goto delmaster_out;
  38542. }
  38543. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  38544. sqlite3OsClose(pJournal);
  38545. if( rc!=SQLITE_OK ){
  38546. goto delmaster_out;
  38547. }
  38548. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  38549. if( c ){
  38550. /* We have a match. Do not delete the master journal file. */
  38551. goto delmaster_out;
  38552. }
  38553. }
  38554. zJournal += (sqlite3Strlen30(zJournal)+1);
  38555. }
  38556. sqlite3OsClose(pMaster);
  38557. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  38558. delmaster_out:
  38559. sqlite3_free(zMasterJournal);
  38560. if( pMaster ){
  38561. sqlite3OsClose(pMaster);
  38562. assert( !isOpen(pJournal) );
  38563. sqlite3_free(pMaster);
  38564. }
  38565. return rc;
  38566. }
  38567. /*
  38568. ** This function is used to change the actual size of the database
  38569. ** file in the file-system. This only happens when committing a transaction,
  38570. ** or rolling back a transaction (including rolling back a hot-journal).
  38571. **
  38572. ** If the main database file is not open, or the pager is not in either
  38573. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  38574. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  38575. ** If the file on disk is currently larger than nPage pages, then use the VFS
  38576. ** xTruncate() method to truncate it.
  38577. **
  38578. ** Or, it might might be the case that the file on disk is smaller than
  38579. ** nPage pages. Some operating system implementations can get confused if
  38580. ** you try to truncate a file to some size that is larger than it
  38581. ** currently is, so detect this case and write a single zero byte to
  38582. ** the end of the new file instead.
  38583. **
  38584. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  38585. ** the database file, return the error code to the caller.
  38586. */
  38587. static int pager_truncate(Pager *pPager, Pgno nPage){
  38588. int rc = SQLITE_OK;
  38589. assert( pPager->eState!=PAGER_ERROR );
  38590. assert( pPager->eState!=PAGER_READER );
  38591. if( isOpen(pPager->fd)
  38592. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  38593. ){
  38594. i64 currentSize, newSize;
  38595. int szPage = pPager->pageSize;
  38596. assert( pPager->eLock==EXCLUSIVE_LOCK );
  38597. /* TODO: Is it safe to use Pager.dbFileSize here? */
  38598. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  38599. newSize = szPage*(i64)nPage;
  38600. if( rc==SQLITE_OK && currentSize!=newSize ){
  38601. if( currentSize>newSize ){
  38602. rc = sqlite3OsTruncate(pPager->fd, newSize);
  38603. }else if( (currentSize+szPage)<=newSize ){
  38604. char *pTmp = pPager->pTmpSpace;
  38605. memset(pTmp, 0, szPage);
  38606. testcase( (newSize-szPage) == currentSize );
  38607. testcase( (newSize-szPage) > currentSize );
  38608. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  38609. }
  38610. if( rc==SQLITE_OK ){
  38611. pPager->dbFileSize = nPage;
  38612. }
  38613. }
  38614. }
  38615. return rc;
  38616. }
  38617. /*
  38618. ** Return a sanitized version of the sector-size of OS file pFile. The
  38619. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  38620. */
  38621. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  38622. int iRet = sqlite3OsSectorSize(pFile);
  38623. if( iRet<32 ){
  38624. iRet = 512;
  38625. }else if( iRet>MAX_SECTOR_SIZE ){
  38626. assert( MAX_SECTOR_SIZE>=512 );
  38627. iRet = MAX_SECTOR_SIZE;
  38628. }
  38629. return iRet;
  38630. }
  38631. /*
  38632. ** Set the value of the Pager.sectorSize variable for the given
  38633. ** pager based on the value returned by the xSectorSize method
  38634. ** of the open database file. The sector size will be used used
  38635. ** to determine the size and alignment of journal header and
  38636. ** master journal pointers within created journal files.
  38637. **
  38638. ** For temporary files the effective sector size is always 512 bytes.
  38639. **
  38640. ** Otherwise, for non-temporary files, the effective sector size is
  38641. ** the value returned by the xSectorSize() method rounded up to 32 if
  38642. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  38643. ** is greater than MAX_SECTOR_SIZE.
  38644. **
  38645. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  38646. ** the effective sector size to its minimum value (512). The purpose of
  38647. ** pPager->sectorSize is to define the "blast radius" of bytes that
  38648. ** might change if a crash occurs while writing to a single byte in
  38649. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  38650. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  38651. ** size. For backwards compatibility of the rollback journal file format,
  38652. ** we cannot reduce the effective sector size below 512.
  38653. */
  38654. static void setSectorSize(Pager *pPager){
  38655. assert( isOpen(pPager->fd) || pPager->tempFile );
  38656. if( pPager->tempFile
  38657. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  38658. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  38659. ){
  38660. /* Sector size doesn't matter for temporary files. Also, the file
  38661. ** may not have been opened yet, in which case the OsSectorSize()
  38662. ** call will segfault. */
  38663. pPager->sectorSize = 512;
  38664. }else{
  38665. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  38666. }
  38667. }
  38668. /*
  38669. ** Playback the journal and thus restore the database file to
  38670. ** the state it was in before we started making changes.
  38671. **
  38672. ** The journal file format is as follows:
  38673. **
  38674. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  38675. ** (2) 4 byte big-endian integer which is the number of valid page records
  38676. ** in the journal. If this value is 0xffffffff, then compute the
  38677. ** number of page records from the journal size.
  38678. ** (3) 4 byte big-endian integer which is the initial value for the
  38679. ** sanity checksum.
  38680. ** (4) 4 byte integer which is the number of pages to truncate the
  38681. ** database to during a rollback.
  38682. ** (5) 4 byte big-endian integer which is the sector size. The header
  38683. ** is this many bytes in size.
  38684. ** (6) 4 byte big-endian integer which is the page size.
  38685. ** (7) zero padding out to the next sector size.
  38686. ** (8) Zero or more pages instances, each as follows:
  38687. ** + 4 byte page number.
  38688. ** + pPager->pageSize bytes of data.
  38689. ** + 4 byte checksum
  38690. **
  38691. ** When we speak of the journal header, we mean the first 7 items above.
  38692. ** Each entry in the journal is an instance of the 8th item.
  38693. **
  38694. ** Call the value from the second bullet "nRec". nRec is the number of
  38695. ** valid page entries in the journal. In most cases, you can compute the
  38696. ** value of nRec from the size of the journal file. But if a power
  38697. ** failure occurred while the journal was being written, it could be the
  38698. ** case that the size of the journal file had already been increased but
  38699. ** the extra entries had not yet made it safely to disk. In such a case,
  38700. ** the value of nRec computed from the file size would be too large. For
  38701. ** that reason, we always use the nRec value in the header.
  38702. **
  38703. ** If the nRec value is 0xffffffff it means that nRec should be computed
  38704. ** from the file size. This value is used when the user selects the
  38705. ** no-sync option for the journal. A power failure could lead to corruption
  38706. ** in this case. But for things like temporary table (which will be
  38707. ** deleted when the power is restored) we don't care.
  38708. **
  38709. ** If the file opened as the journal file is not a well-formed
  38710. ** journal file then all pages up to the first corrupted page are rolled
  38711. ** back (or no pages if the journal header is corrupted). The journal file
  38712. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  38713. ** been encountered.
  38714. **
  38715. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  38716. ** and an error code is returned.
  38717. **
  38718. ** The isHot parameter indicates that we are trying to rollback a journal
  38719. ** that might be a hot journal. Or, it could be that the journal is
  38720. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  38721. ** If the journal really is hot, reset the pager cache prior rolling
  38722. ** back any content. If the journal is merely persistent, no reset is
  38723. ** needed.
  38724. */
  38725. static int pager_playback(Pager *pPager, int isHot){
  38726. sqlite3_vfs *pVfs = pPager->pVfs;
  38727. i64 szJ; /* Size of the journal file in bytes */
  38728. u32 nRec; /* Number of Records in the journal */
  38729. u32 u; /* Unsigned loop counter */
  38730. Pgno mxPg = 0; /* Size of the original file in pages */
  38731. int rc; /* Result code of a subroutine */
  38732. int res = 1; /* Value returned by sqlite3OsAccess() */
  38733. char *zMaster = 0; /* Name of master journal file if any */
  38734. int needPagerReset; /* True to reset page prior to first page rollback */
  38735. int nPlayback = 0; /* Total number of pages restored from journal */
  38736. /* Figure out how many records are in the journal. Abort early if
  38737. ** the journal is empty.
  38738. */
  38739. assert( isOpen(pPager->jfd) );
  38740. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  38741. if( rc!=SQLITE_OK ){
  38742. goto end_playback;
  38743. }
  38744. /* Read the master journal name from the journal, if it is present.
  38745. ** If a master journal file name is specified, but the file is not
  38746. ** present on disk, then the journal is not hot and does not need to be
  38747. ** played back.
  38748. **
  38749. ** TODO: Technically the following is an error because it assumes that
  38750. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  38751. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  38752. ** mxPathname is 512, which is the same as the minimum allowable value
  38753. ** for pageSize.
  38754. */
  38755. zMaster = pPager->pTmpSpace;
  38756. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  38757. if( rc==SQLITE_OK && zMaster[0] ){
  38758. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  38759. }
  38760. zMaster = 0;
  38761. if( rc!=SQLITE_OK || !res ){
  38762. goto end_playback;
  38763. }
  38764. pPager->journalOff = 0;
  38765. needPagerReset = isHot;
  38766. /* This loop terminates either when a readJournalHdr() or
  38767. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  38768. ** occurs.
  38769. */
  38770. while( 1 ){
  38771. /* Read the next journal header from the journal file. If there are
  38772. ** not enough bytes left in the journal file for a complete header, or
  38773. ** it is corrupted, then a process must have failed while writing it.
  38774. ** This indicates nothing more needs to be rolled back.
  38775. */
  38776. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  38777. if( rc!=SQLITE_OK ){
  38778. if( rc==SQLITE_DONE ){
  38779. rc = SQLITE_OK;
  38780. }
  38781. goto end_playback;
  38782. }
  38783. /* If nRec is 0xffffffff, then this journal was created by a process
  38784. ** working in no-sync mode. This means that the rest of the journal
  38785. ** file consists of pages, there are no more journal headers. Compute
  38786. ** the value of nRec based on this assumption.
  38787. */
  38788. if( nRec==0xffffffff ){
  38789. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  38790. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  38791. }
  38792. /* If nRec is 0 and this rollback is of a transaction created by this
  38793. ** process and if this is the final header in the journal, then it means
  38794. ** that this part of the journal was being filled but has not yet been
  38795. ** synced to disk. Compute the number of pages based on the remaining
  38796. ** size of the file.
  38797. **
  38798. ** The third term of the test was added to fix ticket #2565.
  38799. ** When rolling back a hot journal, nRec==0 always means that the next
  38800. ** chunk of the journal contains zero pages to be rolled back. But
  38801. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  38802. ** the journal, it means that the journal might contain additional
  38803. ** pages that need to be rolled back and that the number of pages
  38804. ** should be computed based on the journal file size.
  38805. */
  38806. if( nRec==0 && !isHot &&
  38807. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  38808. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  38809. }
  38810. /* If this is the first header read from the journal, truncate the
  38811. ** database file back to its original size.
  38812. */
  38813. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  38814. rc = pager_truncate(pPager, mxPg);
  38815. if( rc!=SQLITE_OK ){
  38816. goto end_playback;
  38817. }
  38818. pPager->dbSize = mxPg;
  38819. }
  38820. /* Copy original pages out of the journal and back into the
  38821. ** database file and/or page cache.
  38822. */
  38823. for(u=0; u<nRec; u++){
  38824. if( needPagerReset ){
  38825. pager_reset(pPager);
  38826. needPagerReset = 0;
  38827. }
  38828. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  38829. if( rc==SQLITE_OK ){
  38830. nPlayback++;
  38831. }else{
  38832. if( rc==SQLITE_DONE ){
  38833. pPager->journalOff = szJ;
  38834. break;
  38835. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  38836. /* If the journal has been truncated, simply stop reading and
  38837. ** processing the journal. This might happen if the journal was
  38838. ** not completely written and synced prior to a crash. In that
  38839. ** case, the database should have never been written in the
  38840. ** first place so it is OK to simply abandon the rollback. */
  38841. rc = SQLITE_OK;
  38842. goto end_playback;
  38843. }else{
  38844. /* If we are unable to rollback, quit and return the error
  38845. ** code. This will cause the pager to enter the error state
  38846. ** so that no further harm will be done. Perhaps the next
  38847. ** process to come along will be able to rollback the database.
  38848. */
  38849. goto end_playback;
  38850. }
  38851. }
  38852. }
  38853. }
  38854. /*NOTREACHED*/
  38855. assert( 0 );
  38856. end_playback:
  38857. /* Following a rollback, the database file should be back in its original
  38858. ** state prior to the start of the transaction, so invoke the
  38859. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  38860. ** assertion that the transaction counter was modified.
  38861. */
  38862. #ifdef SQLITE_DEBUG
  38863. if( pPager->fd->pMethods ){
  38864. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  38865. }
  38866. #endif
  38867. /* If this playback is happening automatically as a result of an IO or
  38868. ** malloc error that occurred after the change-counter was updated but
  38869. ** before the transaction was committed, then the change-counter
  38870. ** modification may just have been reverted. If this happens in exclusive
  38871. ** mode, then subsequent transactions performed by the connection will not
  38872. ** update the change-counter at all. This may lead to cache inconsistency
  38873. ** problems for other processes at some point in the future. So, just
  38874. ** in case this has happened, clear the changeCountDone flag now.
  38875. */
  38876. pPager->changeCountDone = pPager->tempFile;
  38877. if( rc==SQLITE_OK ){
  38878. zMaster = pPager->pTmpSpace;
  38879. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  38880. testcase( rc!=SQLITE_OK );
  38881. }
  38882. if( rc==SQLITE_OK
  38883. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  38884. ){
  38885. rc = sqlite3PagerSync(pPager);
  38886. }
  38887. if( rc==SQLITE_OK ){
  38888. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  38889. testcase( rc!=SQLITE_OK );
  38890. }
  38891. if( rc==SQLITE_OK && zMaster[0] && res ){
  38892. /* If there was a master journal and this routine will return success,
  38893. ** see if it is possible to delete the master journal.
  38894. */
  38895. rc = pager_delmaster(pPager, zMaster);
  38896. testcase( rc!=SQLITE_OK );
  38897. }
  38898. if( isHot && nPlayback ){
  38899. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  38900. nPlayback, pPager->zJournal);
  38901. }
  38902. /* The Pager.sectorSize variable may have been updated while rolling
  38903. ** back a journal created by a process with a different sector size
  38904. ** value. Reset it to the correct value for this process.
  38905. */
  38906. setSectorSize(pPager);
  38907. return rc;
  38908. }
  38909. /*
  38910. ** Read the content for page pPg out of the database file and into
  38911. ** pPg->pData. A shared lock or greater must be held on the database
  38912. ** file before this function is called.
  38913. **
  38914. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  38915. ** the value read from the database file.
  38916. **
  38917. ** If an IO error occurs, then the IO error is returned to the caller.
  38918. ** Otherwise, SQLITE_OK is returned.
  38919. */
  38920. static int readDbPage(PgHdr *pPg, u32 iFrame){
  38921. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  38922. Pgno pgno = pPg->pgno; /* Page number to read */
  38923. int rc = SQLITE_OK; /* Return code */
  38924. int pgsz = pPager->pageSize; /* Number of bytes to read */
  38925. assert( pPager->eState>=PAGER_READER && !MEMDB );
  38926. assert( isOpen(pPager->fd) );
  38927. #ifndef SQLITE_OMIT_WAL
  38928. if( iFrame ){
  38929. /* Try to pull the page from the write-ahead log. */
  38930. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  38931. }else
  38932. #endif
  38933. {
  38934. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  38935. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  38936. if( rc==SQLITE_IOERR_SHORT_READ ){
  38937. rc = SQLITE_OK;
  38938. }
  38939. }
  38940. if( pgno==1 ){
  38941. if( rc ){
  38942. /* If the read is unsuccessful, set the dbFileVers[] to something
  38943. ** that will never be a valid file version. dbFileVers[] is a copy
  38944. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  38945. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  38946. ** should be page numbers which are never 0xffffffff. So filling
  38947. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  38948. **
  38949. ** For an encrypted database, the situation is more complex: bytes
  38950. ** 24..39 of the database are white noise. But the probability of
  38951. ** white noising equaling 16 bytes of 0xff is vanishingly small so
  38952. ** we should still be ok.
  38953. */
  38954. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  38955. }else{
  38956. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  38957. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  38958. }
  38959. }
  38960. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  38961. PAGER_INCR(sqlite3_pager_readdb_count);
  38962. PAGER_INCR(pPager->nRead);
  38963. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  38964. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  38965. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  38966. return rc;
  38967. }
  38968. /*
  38969. ** Update the value of the change-counter at offsets 24 and 92 in
  38970. ** the header and the sqlite version number at offset 96.
  38971. **
  38972. ** This is an unconditional update. See also the pager_incr_changecounter()
  38973. ** routine which only updates the change-counter if the update is actually
  38974. ** needed, as determined by the pPager->changeCountDone state variable.
  38975. */
  38976. static void pager_write_changecounter(PgHdr *pPg){
  38977. u32 change_counter;
  38978. /* Increment the value just read and write it back to byte 24. */
  38979. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  38980. put32bits(((char*)pPg->pData)+24, change_counter);
  38981. /* Also store the SQLite version number in bytes 96..99 and in
  38982. ** bytes 92..95 store the change counter for which the version number
  38983. ** is valid. */
  38984. put32bits(((char*)pPg->pData)+92, change_counter);
  38985. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  38986. }
  38987. #ifndef SQLITE_OMIT_WAL
  38988. /*
  38989. ** This function is invoked once for each page that has already been
  38990. ** written into the log file when a WAL transaction is rolled back.
  38991. ** Parameter iPg is the page number of said page. The pCtx argument
  38992. ** is actually a pointer to the Pager structure.
  38993. **
  38994. ** If page iPg is present in the cache, and has no outstanding references,
  38995. ** it is discarded. Otherwise, if there are one or more outstanding
  38996. ** references, the page content is reloaded from the database. If the
  38997. ** attempt to reload content from the database is required and fails,
  38998. ** return an SQLite error code. Otherwise, SQLITE_OK.
  38999. */
  39000. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  39001. int rc = SQLITE_OK;
  39002. Pager *pPager = (Pager *)pCtx;
  39003. PgHdr *pPg;
  39004. assert( pagerUseWal(pPager) );
  39005. pPg = sqlite3PagerLookup(pPager, iPg);
  39006. if( pPg ){
  39007. if( sqlite3PcachePageRefcount(pPg)==1 ){
  39008. sqlite3PcacheDrop(pPg);
  39009. }else{
  39010. u32 iFrame = 0;
  39011. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  39012. if( rc==SQLITE_OK ){
  39013. rc = readDbPage(pPg, iFrame);
  39014. }
  39015. if( rc==SQLITE_OK ){
  39016. pPager->xReiniter(pPg);
  39017. }
  39018. sqlite3PagerUnref(pPg);
  39019. }
  39020. }
  39021. /* Normally, if a transaction is rolled back, any backup processes are
  39022. ** updated as data is copied out of the rollback journal and into the
  39023. ** database. This is not generally possible with a WAL database, as
  39024. ** rollback involves simply truncating the log file. Therefore, if one
  39025. ** or more frames have already been written to the log (and therefore
  39026. ** also copied into the backup databases) as part of this transaction,
  39027. ** the backups must be restarted.
  39028. */
  39029. sqlite3BackupRestart(pPager->pBackup);
  39030. return rc;
  39031. }
  39032. /*
  39033. ** This function is called to rollback a transaction on a WAL database.
  39034. */
  39035. static int pagerRollbackWal(Pager *pPager){
  39036. int rc; /* Return Code */
  39037. PgHdr *pList; /* List of dirty pages to revert */
  39038. /* For all pages in the cache that are currently dirty or have already
  39039. ** been written (but not committed) to the log file, do one of the
  39040. ** following:
  39041. **
  39042. ** + Discard the cached page (if refcount==0), or
  39043. ** + Reload page content from the database (if refcount>0).
  39044. */
  39045. pPager->dbSize = pPager->dbOrigSize;
  39046. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  39047. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  39048. while( pList && rc==SQLITE_OK ){
  39049. PgHdr *pNext = pList->pDirty;
  39050. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  39051. pList = pNext;
  39052. }
  39053. return rc;
  39054. }
  39055. /*
  39056. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  39057. ** the contents of the list of pages headed by pList (connected by pDirty),
  39058. ** this function notifies any active backup processes that the pages have
  39059. ** changed.
  39060. **
  39061. ** The list of pages passed into this routine is always sorted by page number.
  39062. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  39063. */
  39064. static int pagerWalFrames(
  39065. Pager *pPager, /* Pager object */
  39066. PgHdr *pList, /* List of frames to log */
  39067. Pgno nTruncate, /* Database size after this commit */
  39068. int isCommit /* True if this is a commit */
  39069. ){
  39070. int rc; /* Return code */
  39071. int nList; /* Number of pages in pList */
  39072. #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
  39073. PgHdr *p; /* For looping over pages */
  39074. #endif
  39075. assert( pPager->pWal );
  39076. assert( pList );
  39077. #ifdef SQLITE_DEBUG
  39078. /* Verify that the page list is in accending order */
  39079. for(p=pList; p && p->pDirty; p=p->pDirty){
  39080. assert( p->pgno < p->pDirty->pgno );
  39081. }
  39082. #endif
  39083. assert( pList->pDirty==0 || isCommit );
  39084. if( isCommit ){
  39085. /* If a WAL transaction is being committed, there is no point in writing
  39086. ** any pages with page numbers greater than nTruncate into the WAL file.
  39087. ** They will never be read by any client. So remove them from the pDirty
  39088. ** list here. */
  39089. PgHdr *p;
  39090. PgHdr **ppNext = &pList;
  39091. nList = 0;
  39092. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  39093. if( p->pgno<=nTruncate ){
  39094. ppNext = &p->pDirty;
  39095. nList++;
  39096. }
  39097. }
  39098. assert( pList );
  39099. }else{
  39100. nList = 1;
  39101. }
  39102. pPager->aStat[PAGER_STAT_WRITE] += nList;
  39103. if( pList->pgno==1 ) pager_write_changecounter(pList);
  39104. rc = sqlite3WalFrames(pPager->pWal,
  39105. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  39106. );
  39107. if( rc==SQLITE_OK && pPager->pBackup ){
  39108. PgHdr *p;
  39109. for(p=pList; p; p=p->pDirty){
  39110. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  39111. }
  39112. }
  39113. #ifdef SQLITE_CHECK_PAGES
  39114. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  39115. for(p=pList; p; p=p->pDirty){
  39116. pager_set_pagehash(p);
  39117. }
  39118. #endif
  39119. return rc;
  39120. }
  39121. /*
  39122. ** Begin a read transaction on the WAL.
  39123. **
  39124. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  39125. ** makes a snapshot of the database at the current point in time and preserves
  39126. ** that snapshot for use by the reader in spite of concurrently changes by
  39127. ** other writers or checkpointers.
  39128. */
  39129. static int pagerBeginReadTransaction(Pager *pPager){
  39130. int rc; /* Return code */
  39131. int changed = 0; /* True if cache must be reset */
  39132. assert( pagerUseWal(pPager) );
  39133. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  39134. /* sqlite3WalEndReadTransaction() was not called for the previous
  39135. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  39136. ** are in locking_mode=NORMAL and EndRead() was previously called,
  39137. ** the duplicate call is harmless.
  39138. */
  39139. sqlite3WalEndReadTransaction(pPager->pWal);
  39140. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  39141. if( rc!=SQLITE_OK || changed ){
  39142. pager_reset(pPager);
  39143. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  39144. }
  39145. return rc;
  39146. }
  39147. #endif
  39148. /*
  39149. ** This function is called as part of the transition from PAGER_OPEN
  39150. ** to PAGER_READER state to determine the size of the database file
  39151. ** in pages (assuming the page size currently stored in Pager.pageSize).
  39152. **
  39153. ** If no error occurs, SQLITE_OK is returned and the size of the database
  39154. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  39155. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  39156. */
  39157. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  39158. Pgno nPage; /* Value to return via *pnPage */
  39159. /* Query the WAL sub-system for the database size. The WalDbsize()
  39160. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  39161. ** if the database size is not available. The database size is not
  39162. ** available from the WAL sub-system if the log file is empty or
  39163. ** contains no valid committed transactions.
  39164. */
  39165. assert( pPager->eState==PAGER_OPEN );
  39166. assert( pPager->eLock>=SHARED_LOCK );
  39167. nPage = sqlite3WalDbsize(pPager->pWal);
  39168. /* If the database size was not available from the WAL sub-system,
  39169. ** determine it based on the size of the database file. If the size
  39170. ** of the database file is not an integer multiple of the page-size,
  39171. ** round down to the nearest page. Except, any file larger than 0
  39172. ** bytes in size is considered to contain at least one page.
  39173. */
  39174. if( nPage==0 ){
  39175. i64 n = 0; /* Size of db file in bytes */
  39176. assert( isOpen(pPager->fd) || pPager->tempFile );
  39177. if( isOpen(pPager->fd) ){
  39178. int rc = sqlite3OsFileSize(pPager->fd, &n);
  39179. if( rc!=SQLITE_OK ){
  39180. return rc;
  39181. }
  39182. }
  39183. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  39184. }
  39185. /* If the current number of pages in the file is greater than the
  39186. ** configured maximum pager number, increase the allowed limit so
  39187. ** that the file can be read.
  39188. */
  39189. if( nPage>pPager->mxPgno ){
  39190. pPager->mxPgno = (Pgno)nPage;
  39191. }
  39192. *pnPage = nPage;
  39193. return SQLITE_OK;
  39194. }
  39195. #ifndef SQLITE_OMIT_WAL
  39196. /*
  39197. ** Check if the *-wal file that corresponds to the database opened by pPager
  39198. ** exists if the database is not empy, or verify that the *-wal file does
  39199. ** not exist (by deleting it) if the database file is empty.
  39200. **
  39201. ** If the database is not empty and the *-wal file exists, open the pager
  39202. ** in WAL mode. If the database is empty or if no *-wal file exists and
  39203. ** if no error occurs, make sure Pager.journalMode is not set to
  39204. ** PAGER_JOURNALMODE_WAL.
  39205. **
  39206. ** Return SQLITE_OK or an error code.
  39207. **
  39208. ** The caller must hold a SHARED lock on the database file to call this
  39209. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  39210. ** a WAL on a none-empty database, this ensures there is no race condition
  39211. ** between the xAccess() below and an xDelete() being executed by some
  39212. ** other connection.
  39213. */
  39214. static int pagerOpenWalIfPresent(Pager *pPager){
  39215. int rc = SQLITE_OK;
  39216. assert( pPager->eState==PAGER_OPEN );
  39217. assert( pPager->eLock>=SHARED_LOCK );
  39218. if( !pPager->tempFile ){
  39219. int isWal; /* True if WAL file exists */
  39220. Pgno nPage; /* Size of the database file */
  39221. rc = pagerPagecount(pPager, &nPage);
  39222. if( rc ) return rc;
  39223. if( nPage==0 ){
  39224. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  39225. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  39226. isWal = 0;
  39227. }else{
  39228. rc = sqlite3OsAccess(
  39229. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  39230. );
  39231. }
  39232. if( rc==SQLITE_OK ){
  39233. if( isWal ){
  39234. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  39235. rc = sqlite3PagerOpenWal(pPager, 0);
  39236. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  39237. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  39238. }
  39239. }
  39240. }
  39241. return rc;
  39242. }
  39243. #endif
  39244. /*
  39245. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  39246. ** the entire master journal file. The case pSavepoint==NULL occurs when
  39247. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  39248. ** savepoint.
  39249. **
  39250. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  39251. ** being rolled back), then the rollback consists of up to three stages,
  39252. ** performed in the order specified:
  39253. **
  39254. ** * Pages are played back from the main journal starting at byte
  39255. ** offset PagerSavepoint.iOffset and continuing to
  39256. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  39257. ** file if PagerSavepoint.iHdrOffset is zero.
  39258. **
  39259. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  39260. ** back starting from the journal header immediately following
  39261. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  39262. **
  39263. ** * Pages are then played back from the sub-journal file, starting
  39264. ** with the PagerSavepoint.iSubRec and continuing to the end of
  39265. ** the journal file.
  39266. **
  39267. ** Throughout the rollback process, each time a page is rolled back, the
  39268. ** corresponding bit is set in a bitvec structure (variable pDone in the
  39269. ** implementation below). This is used to ensure that a page is only
  39270. ** rolled back the first time it is encountered in either journal.
  39271. **
  39272. ** If pSavepoint is NULL, then pages are only played back from the main
  39273. ** journal file. There is no need for a bitvec in this case.
  39274. **
  39275. ** In either case, before playback commences the Pager.dbSize variable
  39276. ** is reset to the value that it held at the start of the savepoint
  39277. ** (or transaction). No page with a page-number greater than this value
  39278. ** is played back. If one is encountered it is simply skipped.
  39279. */
  39280. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  39281. i64 szJ; /* Effective size of the main journal */
  39282. i64 iHdrOff; /* End of first segment of main-journal records */
  39283. int rc = SQLITE_OK; /* Return code */
  39284. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  39285. assert( pPager->eState!=PAGER_ERROR );
  39286. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  39287. /* Allocate a bitvec to use to store the set of pages rolled back */
  39288. if( pSavepoint ){
  39289. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  39290. if( !pDone ){
  39291. return SQLITE_NOMEM;
  39292. }
  39293. }
  39294. /* Set the database size back to the value it was before the savepoint
  39295. ** being reverted was opened.
  39296. */
  39297. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  39298. pPager->changeCountDone = pPager->tempFile;
  39299. if( !pSavepoint && pagerUseWal(pPager) ){
  39300. return pagerRollbackWal(pPager);
  39301. }
  39302. /* Use pPager->journalOff as the effective size of the main rollback
  39303. ** journal. The actual file might be larger than this in
  39304. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  39305. ** past pPager->journalOff is off-limits to us.
  39306. */
  39307. szJ = pPager->journalOff;
  39308. assert( pagerUseWal(pPager)==0 || szJ==0 );
  39309. /* Begin by rolling back records from the main journal starting at
  39310. ** PagerSavepoint.iOffset and continuing to the next journal header.
  39311. ** There might be records in the main journal that have a page number
  39312. ** greater than the current database size (pPager->dbSize) but those
  39313. ** will be skipped automatically. Pages are added to pDone as they
  39314. ** are played back.
  39315. */
  39316. if( pSavepoint && !pagerUseWal(pPager) ){
  39317. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  39318. pPager->journalOff = pSavepoint->iOffset;
  39319. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  39320. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  39321. }
  39322. assert( rc!=SQLITE_DONE );
  39323. }else{
  39324. pPager->journalOff = 0;
  39325. }
  39326. /* Continue rolling back records out of the main journal starting at
  39327. ** the first journal header seen and continuing until the effective end
  39328. ** of the main journal file. Continue to skip out-of-range pages and
  39329. ** continue adding pages rolled back to pDone.
  39330. */
  39331. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  39332. u32 ii; /* Loop counter */
  39333. u32 nJRec = 0; /* Number of Journal Records */
  39334. u32 dummy;
  39335. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  39336. assert( rc!=SQLITE_DONE );
  39337. /*
  39338. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  39339. ** test is related to ticket #2565. See the discussion in the
  39340. ** pager_playback() function for additional information.
  39341. */
  39342. if( nJRec==0
  39343. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  39344. ){
  39345. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  39346. }
  39347. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  39348. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  39349. }
  39350. assert( rc!=SQLITE_DONE );
  39351. }
  39352. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  39353. /* Finally, rollback pages from the sub-journal. Page that were
  39354. ** previously rolled back out of the main journal (and are hence in pDone)
  39355. ** will be skipped. Out-of-range pages are also skipped.
  39356. */
  39357. if( pSavepoint ){
  39358. u32 ii; /* Loop counter */
  39359. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  39360. if( pagerUseWal(pPager) ){
  39361. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  39362. }
  39363. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  39364. assert( offset==(i64)ii*(4+pPager->pageSize) );
  39365. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  39366. }
  39367. assert( rc!=SQLITE_DONE );
  39368. }
  39369. sqlite3BitvecDestroy(pDone);
  39370. if( rc==SQLITE_OK ){
  39371. pPager->journalOff = szJ;
  39372. }
  39373. return rc;
  39374. }
  39375. /*
  39376. ** Change the maximum number of in-memory pages that are allowed.
  39377. */
  39378. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  39379. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  39380. }
  39381. /*
  39382. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  39383. */
  39384. static void pagerFixMaplimit(Pager *pPager){
  39385. #if SQLITE_MAX_MMAP_SIZE>0
  39386. sqlite3_file *fd = pPager->fd;
  39387. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  39388. sqlite3_int64 sz;
  39389. sz = pPager->szMmap;
  39390. pPager->bUseFetch = (sz>0);
  39391. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  39392. }
  39393. #endif
  39394. }
  39395. /*
  39396. ** Change the maximum size of any memory mapping made of the database file.
  39397. */
  39398. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  39399. pPager->szMmap = szMmap;
  39400. pagerFixMaplimit(pPager);
  39401. }
  39402. /*
  39403. ** Free as much memory as possible from the pager.
  39404. */
  39405. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  39406. sqlite3PcacheShrink(pPager->pPCache);
  39407. }
  39408. /*
  39409. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  39410. **
  39411. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  39412. ** of the database to damage due to OS crashes or power failures by
  39413. ** changing the number of syncs()s when writing the journals.
  39414. ** There are three levels:
  39415. **
  39416. ** OFF sqlite3OsSync() is never called. This is the default
  39417. ** for temporary and transient files.
  39418. **
  39419. ** NORMAL The journal is synced once before writes begin on the
  39420. ** database. This is normally adequate protection, but
  39421. ** it is theoretically possible, though very unlikely,
  39422. ** that an inopertune power failure could leave the journal
  39423. ** in a state which would cause damage to the database
  39424. ** when it is rolled back.
  39425. **
  39426. ** FULL The journal is synced twice before writes begin on the
  39427. ** database (with some additional information - the nRec field
  39428. ** of the journal header - being written in between the two
  39429. ** syncs). If we assume that writing a
  39430. ** single disk sector is atomic, then this mode provides
  39431. ** assurance that the journal will not be corrupted to the
  39432. ** point of causing damage to the database during rollback.
  39433. **
  39434. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  39435. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  39436. ** prior to the start of checkpoint and that the database file is synced
  39437. ** at the conclusion of the checkpoint if the entire content of the WAL
  39438. ** was written back into the database. But no sync operations occur for
  39439. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  39440. ** file is synced following each commit operation, in addition to the
  39441. ** syncs associated with NORMAL.
  39442. **
  39443. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  39444. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  39445. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  39446. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  39447. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  39448. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  39449. ** the xSync primitive is called and is relevant to all platforms.
  39450. **
  39451. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  39452. ** and FULL=3.
  39453. */
  39454. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  39455. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  39456. Pager *pPager, /* The pager to set safety level for */
  39457. unsigned pgFlags /* Various flags */
  39458. ){
  39459. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  39460. assert( level>=1 && level<=3 );
  39461. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  39462. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  39463. if( pPager->noSync ){
  39464. pPager->syncFlags = 0;
  39465. pPager->ckptSyncFlags = 0;
  39466. }else if( pgFlags & PAGER_FULLFSYNC ){
  39467. pPager->syncFlags = SQLITE_SYNC_FULL;
  39468. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  39469. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  39470. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  39471. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  39472. }else{
  39473. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  39474. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  39475. }
  39476. pPager->walSyncFlags = pPager->syncFlags;
  39477. if( pPager->fullSync ){
  39478. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  39479. }
  39480. if( pgFlags & PAGER_CACHESPILL ){
  39481. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  39482. }else{
  39483. pPager->doNotSpill |= SPILLFLAG_OFF;
  39484. }
  39485. }
  39486. #endif
  39487. /*
  39488. ** The following global variable is incremented whenever the library
  39489. ** attempts to open a temporary file. This information is used for
  39490. ** testing and analysis only.
  39491. */
  39492. #ifdef SQLITE_TEST
  39493. SQLITE_API int sqlite3_opentemp_count = 0;
  39494. #endif
  39495. /*
  39496. ** Open a temporary file.
  39497. **
  39498. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  39499. ** or some other error code if we fail. The OS will automatically
  39500. ** delete the temporary file when it is closed.
  39501. **
  39502. ** The flags passed to the VFS layer xOpen() call are those specified
  39503. ** by parameter vfsFlags ORed with the following:
  39504. **
  39505. ** SQLITE_OPEN_READWRITE
  39506. ** SQLITE_OPEN_CREATE
  39507. ** SQLITE_OPEN_EXCLUSIVE
  39508. ** SQLITE_OPEN_DELETEONCLOSE
  39509. */
  39510. static int pagerOpentemp(
  39511. Pager *pPager, /* The pager object */
  39512. sqlite3_file *pFile, /* Write the file descriptor here */
  39513. int vfsFlags /* Flags passed through to the VFS */
  39514. ){
  39515. int rc; /* Return code */
  39516. #ifdef SQLITE_TEST
  39517. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  39518. #endif
  39519. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  39520. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  39521. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  39522. assert( rc!=SQLITE_OK || isOpen(pFile) );
  39523. return rc;
  39524. }
  39525. /*
  39526. ** Set the busy handler function.
  39527. **
  39528. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  39529. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  39530. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  39531. ** lock. It does *not* invoke the busy handler when upgrading from
  39532. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  39533. ** (which occurs during hot-journal rollback). Summary:
  39534. **
  39535. ** Transition | Invokes xBusyHandler
  39536. ** --------------------------------------------------------
  39537. ** NO_LOCK -> SHARED_LOCK | Yes
  39538. ** SHARED_LOCK -> RESERVED_LOCK | No
  39539. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  39540. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  39541. **
  39542. ** If the busy-handler callback returns non-zero, the lock is
  39543. ** retried. If it returns zero, then the SQLITE_BUSY error is
  39544. ** returned to the caller of the pager API function.
  39545. */
  39546. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  39547. Pager *pPager, /* Pager object */
  39548. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  39549. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  39550. ){
  39551. pPager->xBusyHandler = xBusyHandler;
  39552. pPager->pBusyHandlerArg = pBusyHandlerArg;
  39553. if( isOpen(pPager->fd) ){
  39554. void **ap = (void **)&pPager->xBusyHandler;
  39555. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  39556. assert( ap[1]==pBusyHandlerArg );
  39557. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  39558. }
  39559. }
  39560. /*
  39561. ** Change the page size used by the Pager object. The new page size
  39562. ** is passed in *pPageSize.
  39563. **
  39564. ** If the pager is in the error state when this function is called, it
  39565. ** is a no-op. The value returned is the error state error code (i.e.
  39566. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  39567. **
  39568. ** Otherwise, if all of the following are true:
  39569. **
  39570. ** * the new page size (value of *pPageSize) is valid (a power
  39571. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  39572. **
  39573. ** * there are no outstanding page references, and
  39574. **
  39575. ** * the database is either not an in-memory database or it is
  39576. ** an in-memory database that currently consists of zero pages.
  39577. **
  39578. ** then the pager object page size is set to *pPageSize.
  39579. **
  39580. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  39581. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  39582. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  39583. ** In all other cases, SQLITE_OK is returned.
  39584. **
  39585. ** If the page size is not changed, either because one of the enumerated
  39586. ** conditions above is not true, the pager was in error state when this
  39587. ** function was called, or because the memory allocation attempt failed,
  39588. ** then *pPageSize is set to the old, retained page size before returning.
  39589. */
  39590. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  39591. int rc = SQLITE_OK;
  39592. /* It is not possible to do a full assert_pager_state() here, as this
  39593. ** function may be called from within PagerOpen(), before the state
  39594. ** of the Pager object is internally consistent.
  39595. **
  39596. ** At one point this function returned an error if the pager was in
  39597. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  39598. ** there is at least one outstanding page reference, this function
  39599. ** is a no-op for that case anyhow.
  39600. */
  39601. u32 pageSize = *pPageSize;
  39602. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  39603. if( (pPager->memDb==0 || pPager->dbSize==0)
  39604. && sqlite3PcacheRefCount(pPager->pPCache)==0
  39605. && pageSize && pageSize!=(u32)pPager->pageSize
  39606. ){
  39607. char *pNew = NULL; /* New temp space */
  39608. i64 nByte = 0;
  39609. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  39610. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  39611. }
  39612. if( rc==SQLITE_OK ){
  39613. pNew = (char *)sqlite3PageMalloc(pageSize);
  39614. if( !pNew ) rc = SQLITE_NOMEM;
  39615. }
  39616. if( rc==SQLITE_OK ){
  39617. pager_reset(pPager);
  39618. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  39619. pPager->pageSize = pageSize;
  39620. sqlite3PageFree(pPager->pTmpSpace);
  39621. pPager->pTmpSpace = pNew;
  39622. sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  39623. }
  39624. }
  39625. *pPageSize = pPager->pageSize;
  39626. if( rc==SQLITE_OK ){
  39627. if( nReserve<0 ) nReserve = pPager->nReserve;
  39628. assert( nReserve>=0 && nReserve<1000 );
  39629. pPager->nReserve = (i16)nReserve;
  39630. pagerReportSize(pPager);
  39631. pagerFixMaplimit(pPager);
  39632. }
  39633. return rc;
  39634. }
  39635. /*
  39636. ** Return a pointer to the "temporary page" buffer held internally
  39637. ** by the pager. This is a buffer that is big enough to hold the
  39638. ** entire content of a database page. This buffer is used internally
  39639. ** during rollback and will be overwritten whenever a rollback
  39640. ** occurs. But other modules are free to use it too, as long as
  39641. ** no rollbacks are happening.
  39642. */
  39643. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  39644. return pPager->pTmpSpace;
  39645. }
  39646. /*
  39647. ** Attempt to set the maximum database page count if mxPage is positive.
  39648. ** Make no changes if mxPage is zero or negative. And never reduce the
  39649. ** maximum page count below the current size of the database.
  39650. **
  39651. ** Regardless of mxPage, return the current maximum page count.
  39652. */
  39653. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  39654. if( mxPage>0 ){
  39655. pPager->mxPgno = mxPage;
  39656. }
  39657. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  39658. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  39659. return pPager->mxPgno;
  39660. }
  39661. /*
  39662. ** The following set of routines are used to disable the simulated
  39663. ** I/O error mechanism. These routines are used to avoid simulated
  39664. ** errors in places where we do not care about errors.
  39665. **
  39666. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  39667. ** and generate no code.
  39668. */
  39669. #ifdef SQLITE_TEST
  39670. SQLITE_API extern int sqlite3_io_error_pending;
  39671. SQLITE_API extern int sqlite3_io_error_hit;
  39672. static int saved_cnt;
  39673. void disable_simulated_io_errors(void){
  39674. saved_cnt = sqlite3_io_error_pending;
  39675. sqlite3_io_error_pending = -1;
  39676. }
  39677. void enable_simulated_io_errors(void){
  39678. sqlite3_io_error_pending = saved_cnt;
  39679. }
  39680. #else
  39681. # define disable_simulated_io_errors()
  39682. # define enable_simulated_io_errors()
  39683. #endif
  39684. /*
  39685. ** Read the first N bytes from the beginning of the file into memory
  39686. ** that pDest points to.
  39687. **
  39688. ** If the pager was opened on a transient file (zFilename==""), or
  39689. ** opened on a file less than N bytes in size, the output buffer is
  39690. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  39691. ** function is used to read database headers, and a new transient or
  39692. ** zero sized database has a header than consists entirely of zeroes.
  39693. **
  39694. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  39695. ** the error code is returned to the caller and the contents of the
  39696. ** output buffer undefined.
  39697. */
  39698. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  39699. int rc = SQLITE_OK;
  39700. memset(pDest, 0, N);
  39701. assert( isOpen(pPager->fd) || pPager->tempFile );
  39702. /* This routine is only called by btree immediately after creating
  39703. ** the Pager object. There has not been an opportunity to transition
  39704. ** to WAL mode yet.
  39705. */
  39706. assert( !pagerUseWal(pPager) );
  39707. if( isOpen(pPager->fd) ){
  39708. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  39709. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  39710. if( rc==SQLITE_IOERR_SHORT_READ ){
  39711. rc = SQLITE_OK;
  39712. }
  39713. }
  39714. return rc;
  39715. }
  39716. /*
  39717. ** This function may only be called when a read-transaction is open on
  39718. ** the pager. It returns the total number of pages in the database.
  39719. **
  39720. ** However, if the file is between 1 and <page-size> bytes in size, then
  39721. ** this is considered a 1 page file.
  39722. */
  39723. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  39724. assert( pPager->eState>=PAGER_READER );
  39725. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  39726. *pnPage = (int)pPager->dbSize;
  39727. }
  39728. /*
  39729. ** Try to obtain a lock of type locktype on the database file. If
  39730. ** a similar or greater lock is already held, this function is a no-op
  39731. ** (returning SQLITE_OK immediately).
  39732. **
  39733. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  39734. ** the busy callback if the lock is currently not available. Repeat
  39735. ** until the busy callback returns false or until the attempt to
  39736. ** obtain the lock succeeds.
  39737. **
  39738. ** Return SQLITE_OK on success and an error code if we cannot obtain
  39739. ** the lock. If the lock is obtained successfully, set the Pager.state
  39740. ** variable to locktype before returning.
  39741. */
  39742. static int pager_wait_on_lock(Pager *pPager, int locktype){
  39743. int rc; /* Return code */
  39744. /* Check that this is either a no-op (because the requested lock is
  39745. ** already held, or one of the transistions that the busy-handler
  39746. ** may be invoked during, according to the comment above
  39747. ** sqlite3PagerSetBusyhandler().
  39748. */
  39749. assert( (pPager->eLock>=locktype)
  39750. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  39751. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  39752. );
  39753. do {
  39754. rc = pagerLockDb(pPager, locktype);
  39755. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  39756. return rc;
  39757. }
  39758. /*
  39759. ** Function assertTruncateConstraint(pPager) checks that one of the
  39760. ** following is true for all dirty pages currently in the page-cache:
  39761. **
  39762. ** a) The page number is less than or equal to the size of the
  39763. ** current database image, in pages, OR
  39764. **
  39765. ** b) if the page content were written at this time, it would not
  39766. ** be necessary to write the current content out to the sub-journal
  39767. ** (as determined by function subjRequiresPage()).
  39768. **
  39769. ** If the condition asserted by this function were not true, and the
  39770. ** dirty page were to be discarded from the cache via the pagerStress()
  39771. ** routine, pagerStress() would not write the current page content to
  39772. ** the database file. If a savepoint transaction were rolled back after
  39773. ** this happened, the correct behavior would be to restore the current
  39774. ** content of the page. However, since this content is not present in either
  39775. ** the database file or the portion of the rollback journal and
  39776. ** sub-journal rolled back the content could not be restored and the
  39777. ** database image would become corrupt. It is therefore fortunate that
  39778. ** this circumstance cannot arise.
  39779. */
  39780. #if defined(SQLITE_DEBUG)
  39781. static void assertTruncateConstraintCb(PgHdr *pPg){
  39782. assert( pPg->flags&PGHDR_DIRTY );
  39783. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  39784. }
  39785. static void assertTruncateConstraint(Pager *pPager){
  39786. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  39787. }
  39788. #else
  39789. # define assertTruncateConstraint(pPager)
  39790. #endif
  39791. /*
  39792. ** Truncate the in-memory database file image to nPage pages. This
  39793. ** function does not actually modify the database file on disk. It
  39794. ** just sets the internal state of the pager object so that the
  39795. ** truncation will be done when the current transaction is committed.
  39796. **
  39797. ** This function is only called right before committing a transaction.
  39798. ** Once this function has been called, the transaction must either be
  39799. ** rolled back or committed. It is not safe to call this function and
  39800. ** then continue writing to the database.
  39801. */
  39802. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  39803. assert( pPager->dbSize>=nPage );
  39804. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  39805. pPager->dbSize = nPage;
  39806. /* At one point the code here called assertTruncateConstraint() to
  39807. ** ensure that all pages being truncated away by this operation are,
  39808. ** if one or more savepoints are open, present in the savepoint
  39809. ** journal so that they can be restored if the savepoint is rolled
  39810. ** back. This is no longer necessary as this function is now only
  39811. ** called right before committing a transaction. So although the
  39812. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  39813. ** they cannot be rolled back. So the assertTruncateConstraint() call
  39814. ** is no longer correct. */
  39815. }
  39816. /*
  39817. ** This function is called before attempting a hot-journal rollback. It
  39818. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  39819. ** size of the journal file so that the pager_playback() routine knows
  39820. ** that the entire journal file has been synced.
  39821. **
  39822. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  39823. ** that if a power-failure occurs during the rollback, the process that
  39824. ** attempts rollback following system recovery sees the same journal
  39825. ** content as this process.
  39826. **
  39827. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  39828. ** an SQLite error code.
  39829. */
  39830. static int pagerSyncHotJournal(Pager *pPager){
  39831. int rc = SQLITE_OK;
  39832. if( !pPager->noSync ){
  39833. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  39834. }
  39835. if( rc==SQLITE_OK ){
  39836. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  39837. }
  39838. return rc;
  39839. }
  39840. /*
  39841. ** Obtain a reference to a memory mapped page object for page number pgno.
  39842. ** The new object will use the pointer pData, obtained from xFetch().
  39843. ** If successful, set *ppPage to point to the new page reference
  39844. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  39845. ** *ppPage to zero.
  39846. **
  39847. ** Page references obtained by calling this function should be released
  39848. ** by calling pagerReleaseMapPage().
  39849. */
  39850. static int pagerAcquireMapPage(
  39851. Pager *pPager, /* Pager object */
  39852. Pgno pgno, /* Page number */
  39853. void *pData, /* xFetch()'d data for this page */
  39854. PgHdr **ppPage /* OUT: Acquired page object */
  39855. ){
  39856. PgHdr *p; /* Memory mapped page to return */
  39857. if( pPager->pMmapFreelist ){
  39858. *ppPage = p = pPager->pMmapFreelist;
  39859. pPager->pMmapFreelist = p->pDirty;
  39860. p->pDirty = 0;
  39861. memset(p->pExtra, 0, pPager->nExtra);
  39862. }else{
  39863. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  39864. if( p==0 ){
  39865. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  39866. return SQLITE_NOMEM;
  39867. }
  39868. p->pExtra = (void *)&p[1];
  39869. p->flags = PGHDR_MMAP;
  39870. p->nRef = 1;
  39871. p->pPager = pPager;
  39872. }
  39873. assert( p->pExtra==(void *)&p[1] );
  39874. assert( p->pPage==0 );
  39875. assert( p->flags==PGHDR_MMAP );
  39876. assert( p->pPager==pPager );
  39877. assert( p->nRef==1 );
  39878. p->pgno = pgno;
  39879. p->pData = pData;
  39880. pPager->nMmapOut++;
  39881. return SQLITE_OK;
  39882. }
  39883. /*
  39884. ** Release a reference to page pPg. pPg must have been returned by an
  39885. ** earlier call to pagerAcquireMapPage().
  39886. */
  39887. static void pagerReleaseMapPage(PgHdr *pPg){
  39888. Pager *pPager = pPg->pPager;
  39889. pPager->nMmapOut--;
  39890. pPg->pDirty = pPager->pMmapFreelist;
  39891. pPager->pMmapFreelist = pPg;
  39892. assert( pPager->fd->pMethods->iVersion>=3 );
  39893. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  39894. }
  39895. /*
  39896. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  39897. */
  39898. static void pagerFreeMapHdrs(Pager *pPager){
  39899. PgHdr *p;
  39900. PgHdr *pNext;
  39901. for(p=pPager->pMmapFreelist; p; p=pNext){
  39902. pNext = p->pDirty;
  39903. sqlite3_free(p);
  39904. }
  39905. }
  39906. /*
  39907. ** Shutdown the page cache. Free all memory and close all files.
  39908. **
  39909. ** If a transaction was in progress when this routine is called, that
  39910. ** transaction is rolled back. All outstanding pages are invalidated
  39911. ** and their memory is freed. Any attempt to use a page associated
  39912. ** with this page cache after this function returns will likely
  39913. ** result in a coredump.
  39914. **
  39915. ** This function always succeeds. If a transaction is active an attempt
  39916. ** is made to roll it back. If an error occurs during the rollback
  39917. ** a hot journal may be left in the filesystem but no error is returned
  39918. ** to the caller.
  39919. */
  39920. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  39921. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  39922. assert( assert_pager_state(pPager) );
  39923. disable_simulated_io_errors();
  39924. sqlite3BeginBenignMalloc();
  39925. pagerFreeMapHdrs(pPager);
  39926. /* pPager->errCode = 0; */
  39927. pPager->exclusiveMode = 0;
  39928. #ifndef SQLITE_OMIT_WAL
  39929. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  39930. pPager->pWal = 0;
  39931. #endif
  39932. pager_reset(pPager);
  39933. if( MEMDB ){
  39934. pager_unlock(pPager);
  39935. }else{
  39936. /* If it is open, sync the journal file before calling UnlockAndRollback.
  39937. ** If this is not done, then an unsynced portion of the open journal
  39938. ** file may be played back into the database. If a power failure occurs
  39939. ** while this is happening, the database could become corrupt.
  39940. **
  39941. ** If an error occurs while trying to sync the journal, shift the pager
  39942. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  39943. ** database and close the journal file without attempting to roll it
  39944. ** back or finalize it. The next database user will have to do hot-journal
  39945. ** rollback before accessing the database file.
  39946. */
  39947. if( isOpen(pPager->jfd) ){
  39948. pager_error(pPager, pagerSyncHotJournal(pPager));
  39949. }
  39950. pagerUnlockAndRollback(pPager);
  39951. }
  39952. sqlite3EndBenignMalloc();
  39953. enable_simulated_io_errors();
  39954. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  39955. IOTRACE(("CLOSE %p\n", pPager))
  39956. sqlite3OsClose(pPager->jfd);
  39957. sqlite3OsClose(pPager->fd);
  39958. sqlite3PageFree(pTmp);
  39959. sqlite3PcacheClose(pPager->pPCache);
  39960. #ifdef SQLITE_HAS_CODEC
  39961. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  39962. #endif
  39963. assert( !pPager->aSavepoint && !pPager->pInJournal );
  39964. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  39965. sqlite3_free(pPager);
  39966. return SQLITE_OK;
  39967. }
  39968. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  39969. /*
  39970. ** Return the page number for page pPg.
  39971. */
  39972. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  39973. return pPg->pgno;
  39974. }
  39975. #endif
  39976. /*
  39977. ** Increment the reference count for page pPg.
  39978. */
  39979. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  39980. sqlite3PcacheRef(pPg);
  39981. }
  39982. /*
  39983. ** Sync the journal. In other words, make sure all the pages that have
  39984. ** been written to the journal have actually reached the surface of the
  39985. ** disk and can be restored in the event of a hot-journal rollback.
  39986. **
  39987. ** If the Pager.noSync flag is set, then this function is a no-op.
  39988. ** Otherwise, the actions required depend on the journal-mode and the
  39989. ** device characteristics of the file-system, as follows:
  39990. **
  39991. ** * If the journal file is an in-memory journal file, no action need
  39992. ** be taken.
  39993. **
  39994. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  39995. ** then the nRec field of the most recently written journal header
  39996. ** is updated to contain the number of journal records that have
  39997. ** been written following it. If the pager is operating in full-sync
  39998. ** mode, then the journal file is synced before this field is updated.
  39999. **
  40000. ** * If the device does not support the SEQUENTIAL property, then
  40001. ** journal file is synced.
  40002. **
  40003. ** Or, in pseudo-code:
  40004. **
  40005. ** if( NOT <in-memory journal> ){
  40006. ** if( NOT SAFE_APPEND ){
  40007. ** if( <full-sync mode> ) xSync(<journal file>);
  40008. ** <update nRec field>
  40009. ** }
  40010. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  40011. ** }
  40012. **
  40013. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  40014. ** page currently held in memory before returning SQLITE_OK. If an IO
  40015. ** error is encountered, then the IO error code is returned to the caller.
  40016. */
  40017. static int syncJournal(Pager *pPager, int newHdr){
  40018. int rc; /* Return code */
  40019. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  40020. || pPager->eState==PAGER_WRITER_DBMOD
  40021. );
  40022. assert( assert_pager_state(pPager) );
  40023. assert( !pagerUseWal(pPager) );
  40024. rc = sqlite3PagerExclusiveLock(pPager);
  40025. if( rc!=SQLITE_OK ) return rc;
  40026. if( !pPager->noSync ){
  40027. assert( !pPager->tempFile );
  40028. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  40029. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  40030. assert( isOpen(pPager->jfd) );
  40031. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  40032. /* This block deals with an obscure problem. If the last connection
  40033. ** that wrote to this database was operating in persistent-journal
  40034. ** mode, then the journal file may at this point actually be larger
  40035. ** than Pager.journalOff bytes. If the next thing in the journal
  40036. ** file happens to be a journal-header (written as part of the
  40037. ** previous connection's transaction), and a crash or power-failure
  40038. ** occurs after nRec is updated but before this connection writes
  40039. ** anything else to the journal file (or commits/rolls back its
  40040. ** transaction), then SQLite may become confused when doing the
  40041. ** hot-journal rollback following recovery. It may roll back all
  40042. ** of this connections data, then proceed to rolling back the old,
  40043. ** out-of-date data that follows it. Database corruption.
  40044. **
  40045. ** To work around this, if the journal file does appear to contain
  40046. ** a valid header following Pager.journalOff, then write a 0x00
  40047. ** byte to the start of it to prevent it from being recognized.
  40048. **
  40049. ** Variable iNextHdrOffset is set to the offset at which this
  40050. ** problematic header will occur, if it exists. aMagic is used
  40051. ** as a temporary buffer to inspect the first couple of bytes of
  40052. ** the potential journal header.
  40053. */
  40054. i64 iNextHdrOffset;
  40055. u8 aMagic[8];
  40056. u8 zHeader[sizeof(aJournalMagic)+4];
  40057. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  40058. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  40059. iNextHdrOffset = journalHdrOffset(pPager);
  40060. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  40061. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  40062. static const u8 zerobyte = 0;
  40063. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  40064. }
  40065. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  40066. return rc;
  40067. }
  40068. /* Write the nRec value into the journal file header. If in
  40069. ** full-synchronous mode, sync the journal first. This ensures that
  40070. ** all data has really hit the disk before nRec is updated to mark
  40071. ** it as a candidate for rollback.
  40072. **
  40073. ** This is not required if the persistent media supports the
  40074. ** SAFE_APPEND property. Because in this case it is not possible
  40075. ** for garbage data to be appended to the file, the nRec field
  40076. ** is populated with 0xFFFFFFFF when the journal header is written
  40077. ** and never needs to be updated.
  40078. */
  40079. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  40080. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  40081. IOTRACE(("JSYNC %p\n", pPager))
  40082. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  40083. if( rc!=SQLITE_OK ) return rc;
  40084. }
  40085. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  40086. rc = sqlite3OsWrite(
  40087. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  40088. );
  40089. if( rc!=SQLITE_OK ) return rc;
  40090. }
  40091. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  40092. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  40093. IOTRACE(("JSYNC %p\n", pPager))
  40094. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  40095. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  40096. );
  40097. if( rc!=SQLITE_OK ) return rc;
  40098. }
  40099. pPager->journalHdr = pPager->journalOff;
  40100. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  40101. pPager->nRec = 0;
  40102. rc = writeJournalHdr(pPager);
  40103. if( rc!=SQLITE_OK ) return rc;
  40104. }
  40105. }else{
  40106. pPager->journalHdr = pPager->journalOff;
  40107. }
  40108. }
  40109. /* Unless the pager is in noSync mode, the journal file was just
  40110. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  40111. ** all pages.
  40112. */
  40113. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  40114. pPager->eState = PAGER_WRITER_DBMOD;
  40115. assert( assert_pager_state(pPager) );
  40116. return SQLITE_OK;
  40117. }
  40118. /*
  40119. ** The argument is the first in a linked list of dirty pages connected
  40120. ** by the PgHdr.pDirty pointer. This function writes each one of the
  40121. ** in-memory pages in the list to the database file. The argument may
  40122. ** be NULL, representing an empty list. In this case this function is
  40123. ** a no-op.
  40124. **
  40125. ** The pager must hold at least a RESERVED lock when this function
  40126. ** is called. Before writing anything to the database file, this lock
  40127. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  40128. ** SQLITE_BUSY is returned and no data is written to the database file.
  40129. **
  40130. ** If the pager is a temp-file pager and the actual file-system file
  40131. ** is not yet open, it is created and opened before any data is
  40132. ** written out.
  40133. **
  40134. ** Once the lock has been upgraded and, if necessary, the file opened,
  40135. ** the pages are written out to the database file in list order. Writing
  40136. ** a page is skipped if it meets either of the following criteria:
  40137. **
  40138. ** * The page number is greater than Pager.dbSize, or
  40139. ** * The PGHDR_DONT_WRITE flag is set on the page.
  40140. **
  40141. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  40142. ** is updated accordingly. If page 1 is written out, then the value cached
  40143. ** in Pager.dbFileVers[] is updated to match the new value stored in
  40144. ** the database file.
  40145. **
  40146. ** If everything is successful, SQLITE_OK is returned. If an IO error
  40147. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  40148. ** be obtained, SQLITE_BUSY is returned.
  40149. */
  40150. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  40151. int rc = SQLITE_OK; /* Return code */
  40152. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  40153. assert( !pagerUseWal(pPager) );
  40154. assert( pPager->eState==PAGER_WRITER_DBMOD );
  40155. assert( pPager->eLock==EXCLUSIVE_LOCK );
  40156. /* If the file is a temp-file has not yet been opened, open it now. It
  40157. ** is not possible for rc to be other than SQLITE_OK if this branch
  40158. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  40159. */
  40160. if( !isOpen(pPager->fd) ){
  40161. assert( pPager->tempFile && rc==SQLITE_OK );
  40162. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  40163. }
  40164. /* Before the first write, give the VFS a hint of what the final
  40165. ** file size will be.
  40166. */
  40167. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  40168. if( rc==SQLITE_OK
  40169. && pPager->dbHintSize<pPager->dbSize
  40170. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  40171. ){
  40172. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  40173. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  40174. pPager->dbHintSize = pPager->dbSize;
  40175. }
  40176. while( rc==SQLITE_OK && pList ){
  40177. Pgno pgno = pList->pgno;
  40178. /* If there are dirty pages in the page cache with page numbers greater
  40179. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  40180. ** make the file smaller (presumably by auto-vacuum code). Do not write
  40181. ** any such pages to the file.
  40182. **
  40183. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  40184. ** set (set by sqlite3PagerDontWrite()).
  40185. */
  40186. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  40187. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  40188. char *pData; /* Data to write */
  40189. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  40190. if( pList->pgno==1 ) pager_write_changecounter(pList);
  40191. /* Encode the database */
  40192. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  40193. /* Write out the page data. */
  40194. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  40195. /* If page 1 was just written, update Pager.dbFileVers to match
  40196. ** the value now stored in the database file. If writing this
  40197. ** page caused the database file to grow, update dbFileSize.
  40198. */
  40199. if( pgno==1 ){
  40200. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  40201. }
  40202. if( pgno>pPager->dbFileSize ){
  40203. pPager->dbFileSize = pgno;
  40204. }
  40205. pPager->aStat[PAGER_STAT_WRITE]++;
  40206. /* Update any backup objects copying the contents of this pager. */
  40207. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  40208. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  40209. PAGERID(pPager), pgno, pager_pagehash(pList)));
  40210. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  40211. PAGER_INCR(sqlite3_pager_writedb_count);
  40212. }else{
  40213. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  40214. }
  40215. pager_set_pagehash(pList);
  40216. pList = pList->pDirty;
  40217. }
  40218. return rc;
  40219. }
  40220. /*
  40221. ** Ensure that the sub-journal file is open. If it is already open, this
  40222. ** function is a no-op.
  40223. **
  40224. ** SQLITE_OK is returned if everything goes according to plan. An
  40225. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  40226. ** fails.
  40227. */
  40228. static int openSubJournal(Pager *pPager){
  40229. int rc = SQLITE_OK;
  40230. if( !isOpen(pPager->sjfd) ){
  40231. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  40232. sqlite3MemJournalOpen(pPager->sjfd);
  40233. }else{
  40234. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  40235. }
  40236. }
  40237. return rc;
  40238. }
  40239. /*
  40240. ** Append a record of the current state of page pPg to the sub-journal.
  40241. ** It is the callers responsibility to use subjRequiresPage() to check
  40242. ** that it is really required before calling this function.
  40243. **
  40244. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  40245. ** for all open savepoints before returning.
  40246. **
  40247. ** This function returns SQLITE_OK if everything is successful, an IO
  40248. ** error code if the attempt to write to the sub-journal fails, or
  40249. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  40250. ** bitvec.
  40251. */
  40252. static int subjournalPage(PgHdr *pPg){
  40253. int rc = SQLITE_OK;
  40254. Pager *pPager = pPg->pPager;
  40255. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  40256. /* Open the sub-journal, if it has not already been opened */
  40257. assert( pPager->useJournal );
  40258. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  40259. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  40260. assert( pagerUseWal(pPager)
  40261. || pageInJournal(pPg)
  40262. || pPg->pgno>pPager->dbOrigSize
  40263. );
  40264. rc = openSubJournal(pPager);
  40265. /* If the sub-journal was opened successfully (or was already open),
  40266. ** write the journal record into the file. */
  40267. if( rc==SQLITE_OK ){
  40268. void *pData = pPg->pData;
  40269. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  40270. char *pData2;
  40271. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  40272. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  40273. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  40274. if( rc==SQLITE_OK ){
  40275. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  40276. }
  40277. }
  40278. }
  40279. if( rc==SQLITE_OK ){
  40280. pPager->nSubRec++;
  40281. assert( pPager->nSavepoint>0 );
  40282. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  40283. }
  40284. return rc;
  40285. }
  40286. /*
  40287. ** This function is called by the pcache layer when it has reached some
  40288. ** soft memory limit. The first argument is a pointer to a Pager object
  40289. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  40290. ** database). The second argument is a reference to a page that is
  40291. ** currently dirty but has no outstanding references. The page
  40292. ** is always associated with the Pager object passed as the first
  40293. ** argument.
  40294. **
  40295. ** The job of this function is to make pPg clean by writing its contents
  40296. ** out to the database file, if possible. This may involve syncing the
  40297. ** journal file.
  40298. **
  40299. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  40300. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  40301. ** page clean, the IO error code is returned. If the page cannot be
  40302. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  40303. ** is returned by sqlite3PcacheMakeClean() is not called.
  40304. */
  40305. static int pagerStress(void *p, PgHdr *pPg){
  40306. Pager *pPager = (Pager *)p;
  40307. int rc = SQLITE_OK;
  40308. assert( pPg->pPager==pPager );
  40309. assert( pPg->flags&PGHDR_DIRTY );
  40310. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  40311. ** journal (and adding a new header) is not allowed. This occurs
  40312. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  40313. ** pages belonging to the same sector.
  40314. **
  40315. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  40316. ** regardless of whether or not a sync is required. This is set during
  40317. ** a rollback or by user request, respectively.
  40318. **
  40319. ** Spilling is also prohibited when in an error state since that could
  40320. ** lead to database corruption. In the current implementaton it
  40321. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
  40322. ** while in the error state, hence it is impossible for this routine to
  40323. ** be called in the error state. Nevertheless, we include a NEVER()
  40324. ** test for the error state as a safeguard against future changes.
  40325. */
  40326. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  40327. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  40328. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  40329. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  40330. if( pPager->doNotSpill
  40331. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  40332. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  40333. ){
  40334. return SQLITE_OK;
  40335. }
  40336. pPg->pDirty = 0;
  40337. if( pagerUseWal(pPager) ){
  40338. /* Write a single frame for this page to the log. */
  40339. if( subjRequiresPage(pPg) ){
  40340. rc = subjournalPage(pPg);
  40341. }
  40342. if( rc==SQLITE_OK ){
  40343. rc = pagerWalFrames(pPager, pPg, 0, 0);
  40344. }
  40345. }else{
  40346. /* Sync the journal file if required. */
  40347. if( pPg->flags&PGHDR_NEED_SYNC
  40348. || pPager->eState==PAGER_WRITER_CACHEMOD
  40349. ){
  40350. rc = syncJournal(pPager, 1);
  40351. }
  40352. /* If the page number of this page is larger than the current size of
  40353. ** the database image, it may need to be written to the sub-journal.
  40354. ** This is because the call to pager_write_pagelist() below will not
  40355. ** actually write data to the file in this case.
  40356. **
  40357. ** Consider the following sequence of events:
  40358. **
  40359. ** BEGIN;
  40360. ** <journal page X>
  40361. ** <modify page X>
  40362. ** SAVEPOINT sp;
  40363. ** <shrink database file to Y pages>
  40364. ** pagerStress(page X)
  40365. ** ROLLBACK TO sp;
  40366. **
  40367. ** If (X>Y), then when pagerStress is called page X will not be written
  40368. ** out to the database file, but will be dropped from the cache. Then,
  40369. ** following the "ROLLBACK TO sp" statement, reading page X will read
  40370. ** data from the database file. This will be the copy of page X as it
  40371. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  40372. ** was executed.
  40373. **
  40374. ** The solution is to write the current data for page X into the
  40375. ** sub-journal file now (if it is not already there), so that it will
  40376. ** be restored to its current value when the "ROLLBACK TO sp" is
  40377. ** executed.
  40378. */
  40379. if( NEVER(
  40380. rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  40381. ) ){
  40382. rc = subjournalPage(pPg);
  40383. }
  40384. /* Write the contents of the page out to the database file. */
  40385. if( rc==SQLITE_OK ){
  40386. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  40387. rc = pager_write_pagelist(pPager, pPg);
  40388. }
  40389. }
  40390. /* Mark the page as clean. */
  40391. if( rc==SQLITE_OK ){
  40392. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  40393. sqlite3PcacheMakeClean(pPg);
  40394. }
  40395. return pager_error(pPager, rc);
  40396. }
  40397. /*
  40398. ** Allocate and initialize a new Pager object and put a pointer to it
  40399. ** in *ppPager. The pager should eventually be freed by passing it
  40400. ** to sqlite3PagerClose().
  40401. **
  40402. ** The zFilename argument is the path to the database file to open.
  40403. ** If zFilename is NULL then a randomly-named temporary file is created
  40404. ** and used as the file to be cached. Temporary files are be deleted
  40405. ** automatically when they are closed. If zFilename is ":memory:" then
  40406. ** all information is held in cache. It is never written to disk.
  40407. ** This can be used to implement an in-memory database.
  40408. **
  40409. ** The nExtra parameter specifies the number of bytes of space allocated
  40410. ** along with each page reference. This space is available to the user
  40411. ** via the sqlite3PagerGetExtra() API.
  40412. **
  40413. ** The flags argument is used to specify properties that affect the
  40414. ** operation of the pager. It should be passed some bitwise combination
  40415. ** of the PAGER_* flags.
  40416. **
  40417. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  40418. ** of the xOpen() method of the supplied VFS when opening files.
  40419. **
  40420. ** If the pager object is allocated and the specified file opened
  40421. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  40422. ** the new pager object. If an error occurs, *ppPager is set to NULL
  40423. ** and error code returned. This function may return SQLITE_NOMEM
  40424. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  40425. ** various SQLITE_IO_XXX errors.
  40426. */
  40427. SQLITE_PRIVATE int sqlite3PagerOpen(
  40428. sqlite3_vfs *pVfs, /* The virtual file system to use */
  40429. Pager **ppPager, /* OUT: Return the Pager structure here */
  40430. const char *zFilename, /* Name of the database file to open */
  40431. int nExtra, /* Extra bytes append to each in-memory page */
  40432. int flags, /* flags controlling this file */
  40433. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  40434. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  40435. ){
  40436. u8 *pPtr;
  40437. Pager *pPager = 0; /* Pager object to allocate and return */
  40438. int rc = SQLITE_OK; /* Return code */
  40439. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  40440. int memDb = 0; /* True if this is an in-memory file */
  40441. int readOnly = 0; /* True if this is a read-only file */
  40442. int journalFileSize; /* Bytes to allocate for each journal fd */
  40443. char *zPathname = 0; /* Full path to database file */
  40444. int nPathname = 0; /* Number of bytes in zPathname */
  40445. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  40446. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  40447. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  40448. const char *zUri = 0; /* URI args to copy */
  40449. int nUri = 0; /* Number of bytes of URI args at *zUri */
  40450. /* Figure out how much space is required for each journal file-handle
  40451. ** (there are two of them, the main journal and the sub-journal). This
  40452. ** is the maximum space required for an in-memory journal file handle
  40453. ** and a regular journal file-handle. Note that a "regular journal-handle"
  40454. ** may be a wrapper capable of caching the first portion of the journal
  40455. ** file in memory to implement the atomic-write optimization (see
  40456. ** source file journal.c).
  40457. */
  40458. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  40459. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  40460. }else{
  40461. journalFileSize = ROUND8(sqlite3MemJournalSize());
  40462. }
  40463. /* Set the output variable to NULL in case an error occurs. */
  40464. *ppPager = 0;
  40465. #ifndef SQLITE_OMIT_MEMORYDB
  40466. if( flags & PAGER_MEMORY ){
  40467. memDb = 1;
  40468. if( zFilename && zFilename[0] ){
  40469. zPathname = sqlite3DbStrDup(0, zFilename);
  40470. if( zPathname==0 ) return SQLITE_NOMEM;
  40471. nPathname = sqlite3Strlen30(zPathname);
  40472. zFilename = 0;
  40473. }
  40474. }
  40475. #endif
  40476. /* Compute and store the full pathname in an allocated buffer pointed
  40477. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  40478. ** leave both nPathname and zPathname set to 0.
  40479. */
  40480. if( zFilename && zFilename[0] ){
  40481. const char *z;
  40482. nPathname = pVfs->mxPathname+1;
  40483. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  40484. if( zPathname==0 ){
  40485. return SQLITE_NOMEM;
  40486. }
  40487. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  40488. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  40489. nPathname = sqlite3Strlen30(zPathname);
  40490. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  40491. while( *z ){
  40492. z += sqlite3Strlen30(z)+1;
  40493. z += sqlite3Strlen30(z)+1;
  40494. }
  40495. nUri = (int)(&z[1] - zUri);
  40496. assert( nUri>=0 );
  40497. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  40498. /* This branch is taken when the journal path required by
  40499. ** the database being opened will be more than pVfs->mxPathname
  40500. ** bytes in length. This means the database cannot be opened,
  40501. ** as it will not be possible to open the journal file or even
  40502. ** check for a hot-journal before reading.
  40503. */
  40504. rc = SQLITE_CANTOPEN_BKPT;
  40505. }
  40506. if( rc!=SQLITE_OK ){
  40507. sqlite3DbFree(0, zPathname);
  40508. return rc;
  40509. }
  40510. }
  40511. /* Allocate memory for the Pager structure, PCache object, the
  40512. ** three file descriptors, the database file name and the journal
  40513. ** file name. The layout in memory is as follows:
  40514. **
  40515. ** Pager object (sizeof(Pager) bytes)
  40516. ** PCache object (sqlite3PcacheSize() bytes)
  40517. ** Database file handle (pVfs->szOsFile bytes)
  40518. ** Sub-journal file handle (journalFileSize bytes)
  40519. ** Main journal file handle (journalFileSize bytes)
  40520. ** Database file name (nPathname+1 bytes)
  40521. ** Journal file name (nPathname+8+1 bytes)
  40522. */
  40523. pPtr = (u8 *)sqlite3MallocZero(
  40524. ROUND8(sizeof(*pPager)) + /* Pager structure */
  40525. ROUND8(pcacheSize) + /* PCache object */
  40526. ROUND8(pVfs->szOsFile) + /* The main db file */
  40527. journalFileSize * 2 + /* The two journal files */
  40528. nPathname + 1 + nUri + /* zFilename */
  40529. nPathname + 8 + 2 /* zJournal */
  40530. #ifndef SQLITE_OMIT_WAL
  40531. + nPathname + 4 + 2 /* zWal */
  40532. #endif
  40533. );
  40534. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  40535. if( !pPtr ){
  40536. sqlite3DbFree(0, zPathname);
  40537. return SQLITE_NOMEM;
  40538. }
  40539. pPager = (Pager*)(pPtr);
  40540. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  40541. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  40542. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  40543. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  40544. pPager->zFilename = (char*)(pPtr += journalFileSize);
  40545. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  40546. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  40547. if( zPathname ){
  40548. assert( nPathname>0 );
  40549. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  40550. memcpy(pPager->zFilename, zPathname, nPathname);
  40551. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  40552. memcpy(pPager->zJournal, zPathname, nPathname);
  40553. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  40554. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  40555. #ifndef SQLITE_OMIT_WAL
  40556. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  40557. memcpy(pPager->zWal, zPathname, nPathname);
  40558. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  40559. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  40560. #endif
  40561. sqlite3DbFree(0, zPathname);
  40562. }
  40563. pPager->pVfs = pVfs;
  40564. pPager->vfsFlags = vfsFlags;
  40565. /* Open the pager file.
  40566. */
  40567. if( zFilename && zFilename[0] ){
  40568. int fout = 0; /* VFS flags returned by xOpen() */
  40569. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  40570. assert( !memDb );
  40571. readOnly = (fout&SQLITE_OPEN_READONLY);
  40572. /* If the file was successfully opened for read/write access,
  40573. ** choose a default page size in case we have to create the
  40574. ** database file. The default page size is the maximum of:
  40575. **
  40576. ** + SQLITE_DEFAULT_PAGE_SIZE,
  40577. ** + The value returned by sqlite3OsSectorSize()
  40578. ** + The largest page size that can be written atomically.
  40579. */
  40580. if( rc==SQLITE_OK && !readOnly ){
  40581. setSectorSize(pPager);
  40582. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  40583. if( szPageDflt<pPager->sectorSize ){
  40584. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  40585. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  40586. }else{
  40587. szPageDflt = (u32)pPager->sectorSize;
  40588. }
  40589. }
  40590. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  40591. {
  40592. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  40593. int ii;
  40594. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  40595. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  40596. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  40597. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  40598. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  40599. szPageDflt = ii;
  40600. }
  40601. }
  40602. }
  40603. #endif
  40604. }
  40605. }else{
  40606. /* If a temporary file is requested, it is not opened immediately.
  40607. ** In this case we accept the default page size and delay actually
  40608. ** opening the file until the first call to OsWrite().
  40609. **
  40610. ** This branch is also run for an in-memory database. An in-memory
  40611. ** database is the same as a temp-file that is never written out to
  40612. ** disk and uses an in-memory rollback journal.
  40613. */
  40614. tempFile = 1;
  40615. pPager->eState = PAGER_READER;
  40616. pPager->eLock = EXCLUSIVE_LOCK;
  40617. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  40618. }
  40619. /* The following call to PagerSetPagesize() serves to set the value of
  40620. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  40621. */
  40622. if( rc==SQLITE_OK ){
  40623. assert( pPager->memDb==0 );
  40624. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  40625. testcase( rc!=SQLITE_OK );
  40626. }
  40627. /* If an error occurred in either of the blocks above, free the
  40628. ** Pager structure and close the file.
  40629. */
  40630. if( rc!=SQLITE_OK ){
  40631. assert( !pPager->pTmpSpace );
  40632. sqlite3OsClose(pPager->fd);
  40633. sqlite3_free(pPager);
  40634. return rc;
  40635. }
  40636. /* Initialize the PCache object. */
  40637. assert( nExtra<1000 );
  40638. nExtra = ROUND8(nExtra);
  40639. sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  40640. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  40641. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  40642. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  40643. pPager->useJournal = (u8)useJournal;
  40644. /* pPager->stmtOpen = 0; */
  40645. /* pPager->stmtInUse = 0; */
  40646. /* pPager->nRef = 0; */
  40647. /* pPager->stmtSize = 0; */
  40648. /* pPager->stmtJSize = 0; */
  40649. /* pPager->nPage = 0; */
  40650. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  40651. /* pPager->state = PAGER_UNLOCK; */
  40652. #if 0
  40653. assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  40654. #endif
  40655. /* pPager->errMask = 0; */
  40656. pPager->tempFile = (u8)tempFile;
  40657. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  40658. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  40659. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  40660. pPager->exclusiveMode = (u8)tempFile;
  40661. pPager->changeCountDone = pPager->tempFile;
  40662. pPager->memDb = (u8)memDb;
  40663. pPager->readOnly = (u8)readOnly;
  40664. assert( useJournal || pPager->tempFile );
  40665. pPager->noSync = pPager->tempFile;
  40666. if( pPager->noSync ){
  40667. assert( pPager->fullSync==0 );
  40668. assert( pPager->syncFlags==0 );
  40669. assert( pPager->walSyncFlags==0 );
  40670. assert( pPager->ckptSyncFlags==0 );
  40671. }else{
  40672. pPager->fullSync = 1;
  40673. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  40674. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  40675. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  40676. }
  40677. /* pPager->pFirst = 0; */
  40678. /* pPager->pFirstSynced = 0; */
  40679. /* pPager->pLast = 0; */
  40680. pPager->nExtra = (u16)nExtra;
  40681. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  40682. assert( isOpen(pPager->fd) || tempFile );
  40683. setSectorSize(pPager);
  40684. if( !useJournal ){
  40685. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  40686. }else if( memDb ){
  40687. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  40688. }
  40689. /* pPager->xBusyHandler = 0; */
  40690. /* pPager->pBusyHandlerArg = 0; */
  40691. pPager->xReiniter = xReinit;
  40692. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  40693. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  40694. *ppPager = pPager;
  40695. return SQLITE_OK;
  40696. }
  40697. /*
  40698. ** This function is called after transitioning from PAGER_UNLOCK to
  40699. ** PAGER_SHARED state. It tests if there is a hot journal present in
  40700. ** the file-system for the given pager. A hot journal is one that
  40701. ** needs to be played back. According to this function, a hot-journal
  40702. ** file exists if the following criteria are met:
  40703. **
  40704. ** * The journal file exists in the file system, and
  40705. ** * No process holds a RESERVED or greater lock on the database file, and
  40706. ** * The database file itself is greater than 0 bytes in size, and
  40707. ** * The first byte of the journal file exists and is not 0x00.
  40708. **
  40709. ** If the current size of the database file is 0 but a journal file
  40710. ** exists, that is probably an old journal left over from a prior
  40711. ** database with the same name. In this case the journal file is
  40712. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  40713. ** is returned.
  40714. **
  40715. ** This routine does not check if there is a master journal filename
  40716. ** at the end of the file. If there is, and that master journal file
  40717. ** does not exist, then the journal file is not really hot. In this
  40718. ** case this routine will return a false-positive. The pager_playback()
  40719. ** routine will discover that the journal file is not really hot and
  40720. ** will not roll it back.
  40721. **
  40722. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  40723. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  40724. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  40725. ** to determine whether or not a hot-journal file exists, the IO error
  40726. ** code is returned and the value of *pExists is undefined.
  40727. */
  40728. static int hasHotJournal(Pager *pPager, int *pExists){
  40729. sqlite3_vfs * const pVfs = pPager->pVfs;
  40730. int rc = SQLITE_OK; /* Return code */
  40731. int exists = 1; /* True if a journal file is present */
  40732. int jrnlOpen = !!isOpen(pPager->jfd);
  40733. assert( pPager->useJournal );
  40734. assert( isOpen(pPager->fd) );
  40735. assert( pPager->eState==PAGER_OPEN );
  40736. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  40737. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  40738. ));
  40739. *pExists = 0;
  40740. if( !jrnlOpen ){
  40741. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  40742. }
  40743. if( rc==SQLITE_OK && exists ){
  40744. int locked = 0; /* True if some process holds a RESERVED lock */
  40745. /* Race condition here: Another process might have been holding the
  40746. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  40747. ** call above, but then delete the journal and drop the lock before
  40748. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  40749. ** is the case, this routine might think there is a hot journal when
  40750. ** in fact there is none. This results in a false-positive which will
  40751. ** be dealt with by the playback routine. Ticket #3883.
  40752. */
  40753. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  40754. if( rc==SQLITE_OK && !locked ){
  40755. Pgno nPage; /* Number of pages in database file */
  40756. /* Check the size of the database file. If it consists of 0 pages,
  40757. ** then delete the journal file. See the header comment above for
  40758. ** the reasoning here. Delete the obsolete journal file under
  40759. ** a RESERVED lock to avoid race conditions and to avoid violating
  40760. ** [H33020].
  40761. */
  40762. rc = pagerPagecount(pPager, &nPage);
  40763. if( rc==SQLITE_OK ){
  40764. if( nPage==0 ){
  40765. sqlite3BeginBenignMalloc();
  40766. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  40767. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  40768. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  40769. }
  40770. sqlite3EndBenignMalloc();
  40771. }else{
  40772. /* The journal file exists and no other connection has a reserved
  40773. ** or greater lock on the database file. Now check that there is
  40774. ** at least one non-zero bytes at the start of the journal file.
  40775. ** If there is, then we consider this journal to be hot. If not,
  40776. ** it can be ignored.
  40777. */
  40778. if( !jrnlOpen ){
  40779. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  40780. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  40781. }
  40782. if( rc==SQLITE_OK ){
  40783. u8 first = 0;
  40784. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  40785. if( rc==SQLITE_IOERR_SHORT_READ ){
  40786. rc = SQLITE_OK;
  40787. }
  40788. if( !jrnlOpen ){
  40789. sqlite3OsClose(pPager->jfd);
  40790. }
  40791. *pExists = (first!=0);
  40792. }else if( rc==SQLITE_CANTOPEN ){
  40793. /* If we cannot open the rollback journal file in order to see if
  40794. ** its has a zero header, that might be due to an I/O error, or
  40795. ** it might be due to the race condition described above and in
  40796. ** ticket #3883. Either way, assume that the journal is hot.
  40797. ** This might be a false positive. But if it is, then the
  40798. ** automatic journal playback and recovery mechanism will deal
  40799. ** with it under an EXCLUSIVE lock where we do not need to
  40800. ** worry so much with race conditions.
  40801. */
  40802. *pExists = 1;
  40803. rc = SQLITE_OK;
  40804. }
  40805. }
  40806. }
  40807. }
  40808. }
  40809. return rc;
  40810. }
  40811. /*
  40812. ** This function is called to obtain a shared lock on the database file.
  40813. ** It is illegal to call sqlite3PagerAcquire() until after this function
  40814. ** has been successfully called. If a shared-lock is already held when
  40815. ** this function is called, it is a no-op.
  40816. **
  40817. ** The following operations are also performed by this function.
  40818. **
  40819. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  40820. ** on the database file), then an attempt is made to obtain a
  40821. ** SHARED lock on the database file. Immediately after obtaining
  40822. ** the SHARED lock, the file-system is checked for a hot-journal,
  40823. ** which is played back if present. Following any hot-journal
  40824. ** rollback, the contents of the cache are validated by checking
  40825. ** the 'change-counter' field of the database file header and
  40826. ** discarded if they are found to be invalid.
  40827. **
  40828. ** 2) If the pager is running in exclusive-mode, and there are currently
  40829. ** no outstanding references to any pages, and is in the error state,
  40830. ** then an attempt is made to clear the error state by discarding
  40831. ** the contents of the page cache and rolling back any open journal
  40832. ** file.
  40833. **
  40834. ** If everything is successful, SQLITE_OK is returned. If an IO error
  40835. ** occurs while locking the database, checking for a hot-journal file or
  40836. ** rolling back a journal file, the IO error code is returned.
  40837. */
  40838. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  40839. int rc = SQLITE_OK; /* Return code */
  40840. /* This routine is only called from b-tree and only when there are no
  40841. ** outstanding pages. This implies that the pager state should either
  40842. ** be OPEN or READER. READER is only possible if the pager is or was in
  40843. ** exclusive access mode.
  40844. */
  40845. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  40846. assert( assert_pager_state(pPager) );
  40847. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  40848. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  40849. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  40850. int bHotJournal = 1; /* True if there exists a hot journal-file */
  40851. assert( !MEMDB );
  40852. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  40853. if( rc!=SQLITE_OK ){
  40854. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  40855. goto failed;
  40856. }
  40857. /* If a journal file exists, and there is no RESERVED lock on the
  40858. ** database file, then it either needs to be played back or deleted.
  40859. */
  40860. if( pPager->eLock<=SHARED_LOCK ){
  40861. rc = hasHotJournal(pPager, &bHotJournal);
  40862. }
  40863. if( rc!=SQLITE_OK ){
  40864. goto failed;
  40865. }
  40866. if( bHotJournal ){
  40867. if( pPager->readOnly ){
  40868. rc = SQLITE_READONLY_ROLLBACK;
  40869. goto failed;
  40870. }
  40871. /* Get an EXCLUSIVE lock on the database file. At this point it is
  40872. ** important that a RESERVED lock is not obtained on the way to the
  40873. ** EXCLUSIVE lock. If it were, another process might open the
  40874. ** database file, detect the RESERVED lock, and conclude that the
  40875. ** database is safe to read while this process is still rolling the
  40876. ** hot-journal back.
  40877. **
  40878. ** Because the intermediate RESERVED lock is not requested, any
  40879. ** other process attempting to access the database file will get to
  40880. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  40881. ** on the database file.
  40882. **
  40883. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  40884. ** downgraded to SHARED_LOCK before this function returns.
  40885. */
  40886. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  40887. if( rc!=SQLITE_OK ){
  40888. goto failed;
  40889. }
  40890. /* If it is not already open and the file exists on disk, open the
  40891. ** journal for read/write access. Write access is required because
  40892. ** in exclusive-access mode the file descriptor will be kept open
  40893. ** and possibly used for a transaction later on. Also, write-access
  40894. ** is usually required to finalize the journal in journal_mode=persist
  40895. ** mode (and also for journal_mode=truncate on some systems).
  40896. **
  40897. ** If the journal does not exist, it usually means that some
  40898. ** other connection managed to get in and roll it back before
  40899. ** this connection obtained the exclusive lock above. Or, it
  40900. ** may mean that the pager was in the error-state when this
  40901. ** function was called and the journal file does not exist.
  40902. */
  40903. if( !isOpen(pPager->jfd) ){
  40904. sqlite3_vfs * const pVfs = pPager->pVfs;
  40905. int bExists; /* True if journal file exists */
  40906. rc = sqlite3OsAccess(
  40907. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  40908. if( rc==SQLITE_OK && bExists ){
  40909. int fout = 0;
  40910. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  40911. assert( !pPager->tempFile );
  40912. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  40913. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  40914. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  40915. rc = SQLITE_CANTOPEN_BKPT;
  40916. sqlite3OsClose(pPager->jfd);
  40917. }
  40918. }
  40919. }
  40920. /* Playback and delete the journal. Drop the database write
  40921. ** lock and reacquire the read lock. Purge the cache before
  40922. ** playing back the hot-journal so that we don't end up with
  40923. ** an inconsistent cache. Sync the hot journal before playing
  40924. ** it back since the process that crashed and left the hot journal
  40925. ** probably did not sync it and we are required to always sync
  40926. ** the journal before playing it back.
  40927. */
  40928. if( isOpen(pPager->jfd) ){
  40929. assert( rc==SQLITE_OK );
  40930. rc = pagerSyncHotJournal(pPager);
  40931. if( rc==SQLITE_OK ){
  40932. rc = pager_playback(pPager, 1);
  40933. pPager->eState = PAGER_OPEN;
  40934. }
  40935. }else if( !pPager->exclusiveMode ){
  40936. pagerUnlockDb(pPager, SHARED_LOCK);
  40937. }
  40938. if( rc!=SQLITE_OK ){
  40939. /* This branch is taken if an error occurs while trying to open
  40940. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  40941. ** pager_unlock() routine will be called before returning to unlock
  40942. ** the file. If the unlock attempt fails, then Pager.eLock must be
  40943. ** set to UNKNOWN_LOCK (see the comment above the #define for
  40944. ** UNKNOWN_LOCK above for an explanation).
  40945. **
  40946. ** In order to get pager_unlock() to do this, set Pager.eState to
  40947. ** PAGER_ERROR now. This is not actually counted as a transition
  40948. ** to ERROR state in the state diagram at the top of this file,
  40949. ** since we know that the same call to pager_unlock() will very
  40950. ** shortly transition the pager object to the OPEN state. Calling
  40951. ** assert_pager_state() would fail now, as it should not be possible
  40952. ** to be in ERROR state when there are zero outstanding page
  40953. ** references.
  40954. */
  40955. pager_error(pPager, rc);
  40956. goto failed;
  40957. }
  40958. assert( pPager->eState==PAGER_OPEN );
  40959. assert( (pPager->eLock==SHARED_LOCK)
  40960. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  40961. );
  40962. }
  40963. if( !pPager->tempFile && (
  40964. pPager->pBackup
  40965. || sqlite3PcachePagecount(pPager->pPCache)>0
  40966. || USEFETCH(pPager)
  40967. )){
  40968. /* The shared-lock has just been acquired on the database file
  40969. ** and there are already pages in the cache (from a previous
  40970. ** read or write transaction). Check to see if the database
  40971. ** has been modified. If the database has changed, flush the
  40972. ** cache.
  40973. **
  40974. ** Database changes is detected by looking at 15 bytes beginning
  40975. ** at offset 24 into the file. The first 4 of these 16 bytes are
  40976. ** a 32-bit counter that is incremented with each change. The
  40977. ** other bytes change randomly with each file change when
  40978. ** a codec is in use.
  40979. **
  40980. ** There is a vanishingly small chance that a change will not be
  40981. ** detected. The chance of an undetected change is so small that
  40982. ** it can be neglected.
  40983. */
  40984. Pgno nPage = 0;
  40985. char dbFileVers[sizeof(pPager->dbFileVers)];
  40986. rc = pagerPagecount(pPager, &nPage);
  40987. if( rc ) goto failed;
  40988. if( nPage>0 ){
  40989. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  40990. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  40991. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  40992. goto failed;
  40993. }
  40994. }else{
  40995. memset(dbFileVers, 0, sizeof(dbFileVers));
  40996. }
  40997. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  40998. pager_reset(pPager);
  40999. /* Unmap the database file. It is possible that external processes
  41000. ** may have truncated the database file and then extended it back
  41001. ** to its original size while this process was not holding a lock.
  41002. ** In this case there may exist a Pager.pMap mapping that appears
  41003. ** to be the right size but is not actually valid. Avoid this
  41004. ** possibility by unmapping the db here. */
  41005. if( USEFETCH(pPager) ){
  41006. sqlite3OsUnfetch(pPager->fd, 0, 0);
  41007. }
  41008. }
  41009. }
  41010. /* If there is a WAL file in the file-system, open this database in WAL
  41011. ** mode. Otherwise, the following function call is a no-op.
  41012. */
  41013. rc = pagerOpenWalIfPresent(pPager);
  41014. #ifndef SQLITE_OMIT_WAL
  41015. assert( pPager->pWal==0 || rc==SQLITE_OK );
  41016. #endif
  41017. }
  41018. if( pagerUseWal(pPager) ){
  41019. assert( rc==SQLITE_OK );
  41020. rc = pagerBeginReadTransaction(pPager);
  41021. }
  41022. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  41023. rc = pagerPagecount(pPager, &pPager->dbSize);
  41024. }
  41025. failed:
  41026. if( rc!=SQLITE_OK ){
  41027. assert( !MEMDB );
  41028. pager_unlock(pPager);
  41029. assert( pPager->eState==PAGER_OPEN );
  41030. }else{
  41031. pPager->eState = PAGER_READER;
  41032. }
  41033. return rc;
  41034. }
  41035. /*
  41036. ** If the reference count has reached zero, rollback any active
  41037. ** transaction and unlock the pager.
  41038. **
  41039. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  41040. ** the rollback journal, the unlock is not performed and there is
  41041. ** nothing to rollback, so this routine is a no-op.
  41042. */
  41043. static void pagerUnlockIfUnused(Pager *pPager){
  41044. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  41045. pagerUnlockAndRollback(pPager);
  41046. }
  41047. }
  41048. /*
  41049. ** Acquire a reference to page number pgno in pager pPager (a page
  41050. ** reference has type DbPage*). If the requested reference is
  41051. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  41052. **
  41053. ** If the requested page is already in the cache, it is returned.
  41054. ** Otherwise, a new page object is allocated and populated with data
  41055. ** read from the database file. In some cases, the pcache module may
  41056. ** choose not to allocate a new page object and may reuse an existing
  41057. ** object with no outstanding references.
  41058. **
  41059. ** The extra data appended to a page is always initialized to zeros the
  41060. ** first time a page is loaded into memory. If the page requested is
  41061. ** already in the cache when this function is called, then the extra
  41062. ** data is left as it was when the page object was last used.
  41063. **
  41064. ** If the database image is smaller than the requested page or if a
  41065. ** non-zero value is passed as the noContent parameter and the
  41066. ** requested page is not already stored in the cache, then no
  41067. ** actual disk read occurs. In this case the memory image of the
  41068. ** page is initialized to all zeros.
  41069. **
  41070. ** If noContent is true, it means that we do not care about the contents
  41071. ** of the page. This occurs in two scenarios:
  41072. **
  41073. ** a) When reading a free-list leaf page from the database, and
  41074. **
  41075. ** b) When a savepoint is being rolled back and we need to load
  41076. ** a new page into the cache to be filled with the data read
  41077. ** from the savepoint journal.
  41078. **
  41079. ** If noContent is true, then the data returned is zeroed instead of
  41080. ** being read from the database. Additionally, the bits corresponding
  41081. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  41082. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  41083. ** savepoints are set. This means if the page is made writable at any
  41084. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  41085. ** will not be journaled. This saves IO.
  41086. **
  41087. ** The acquisition might fail for several reasons. In all cases,
  41088. ** an appropriate error code is returned and *ppPage is set to NULL.
  41089. **
  41090. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  41091. ** to find a page in the in-memory cache first. If the page is not already
  41092. ** in memory, this routine goes to disk to read it in whereas Lookup()
  41093. ** just returns 0. This routine acquires a read-lock the first time it
  41094. ** has to go to disk, and could also playback an old journal if necessary.
  41095. ** Since Lookup() never goes to disk, it never has to deal with locks
  41096. ** or journal files.
  41097. */
  41098. SQLITE_PRIVATE int sqlite3PagerAcquire(
  41099. Pager *pPager, /* The pager open on the database file */
  41100. Pgno pgno, /* Page number to fetch */
  41101. DbPage **ppPage, /* Write a pointer to the page here */
  41102. int flags /* PAGER_GET_XXX flags */
  41103. ){
  41104. int rc = SQLITE_OK;
  41105. PgHdr *pPg = 0;
  41106. u32 iFrame = 0; /* Frame to read from WAL file */
  41107. const int noContent = (flags & PAGER_GET_NOCONTENT);
  41108. /* It is acceptable to use a read-only (mmap) page for any page except
  41109. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  41110. ** flag was specified by the caller. And so long as the db is not a
  41111. ** temporary or in-memory database. */
  41112. const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
  41113. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  41114. #ifdef SQLITE_HAS_CODEC
  41115. && pPager->xCodec==0
  41116. #endif
  41117. );
  41118. assert( pPager->eState>=PAGER_READER );
  41119. assert( assert_pager_state(pPager) );
  41120. assert( noContent==0 || bMmapOk==0 );
  41121. if( pgno==0 ){
  41122. return SQLITE_CORRUPT_BKPT;
  41123. }
  41124. /* If the pager is in the error state, return an error immediately.
  41125. ** Otherwise, request the page from the PCache layer. */
  41126. if( pPager->errCode!=SQLITE_OK ){
  41127. rc = pPager->errCode;
  41128. }else{
  41129. if( bMmapOk && pagerUseWal(pPager) ){
  41130. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  41131. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  41132. }
  41133. if( iFrame==0 && bMmapOk ){
  41134. void *pData = 0;
  41135. rc = sqlite3OsFetch(pPager->fd,
  41136. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  41137. );
  41138. if( rc==SQLITE_OK && pData ){
  41139. if( pPager->eState>PAGER_READER ){
  41140. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  41141. }
  41142. if( pPg==0 ){
  41143. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  41144. }else{
  41145. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  41146. }
  41147. if( pPg ){
  41148. assert( rc==SQLITE_OK );
  41149. *ppPage = pPg;
  41150. return SQLITE_OK;
  41151. }
  41152. }
  41153. if( rc!=SQLITE_OK ){
  41154. goto pager_acquire_err;
  41155. }
  41156. }
  41157. rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
  41158. }
  41159. if( rc!=SQLITE_OK ){
  41160. /* Either the call to sqlite3PcacheFetch() returned an error or the
  41161. ** pager was already in the error-state when this function was called.
  41162. ** Set pPg to 0 and jump to the exception handler. */
  41163. pPg = 0;
  41164. goto pager_acquire_err;
  41165. }
  41166. assert( (*ppPage)->pgno==pgno );
  41167. assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
  41168. if( (*ppPage)->pPager && !noContent ){
  41169. /* In this case the pcache already contains an initialized copy of
  41170. ** the page. Return without further ado. */
  41171. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  41172. pPager->aStat[PAGER_STAT_HIT]++;
  41173. return SQLITE_OK;
  41174. }else{
  41175. /* The pager cache has created a new page. Its content needs to
  41176. ** be initialized. */
  41177. pPg = *ppPage;
  41178. pPg->pPager = pPager;
  41179. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  41180. ** number greater than this, or the unused locking-page, is requested. */
  41181. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  41182. rc = SQLITE_CORRUPT_BKPT;
  41183. goto pager_acquire_err;
  41184. }
  41185. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  41186. if( pgno>pPager->mxPgno ){
  41187. rc = SQLITE_FULL;
  41188. goto pager_acquire_err;
  41189. }
  41190. if( noContent ){
  41191. /* Failure to set the bits in the InJournal bit-vectors is benign.
  41192. ** It merely means that we might do some extra work to journal a
  41193. ** page that does not need to be journaled. Nevertheless, be sure
  41194. ** to test the case where a malloc error occurs while trying to set
  41195. ** a bit in a bit vector.
  41196. */
  41197. sqlite3BeginBenignMalloc();
  41198. if( pgno<=pPager->dbOrigSize ){
  41199. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  41200. testcase( rc==SQLITE_NOMEM );
  41201. }
  41202. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  41203. testcase( rc==SQLITE_NOMEM );
  41204. sqlite3EndBenignMalloc();
  41205. }
  41206. memset(pPg->pData, 0, pPager->pageSize);
  41207. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  41208. }else{
  41209. if( pagerUseWal(pPager) && bMmapOk==0 ){
  41210. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  41211. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  41212. }
  41213. assert( pPg->pPager==pPager );
  41214. pPager->aStat[PAGER_STAT_MISS]++;
  41215. rc = readDbPage(pPg, iFrame);
  41216. if( rc!=SQLITE_OK ){
  41217. goto pager_acquire_err;
  41218. }
  41219. }
  41220. pager_set_pagehash(pPg);
  41221. }
  41222. return SQLITE_OK;
  41223. pager_acquire_err:
  41224. assert( rc!=SQLITE_OK );
  41225. if( pPg ){
  41226. sqlite3PcacheDrop(pPg);
  41227. }
  41228. pagerUnlockIfUnused(pPager);
  41229. *ppPage = 0;
  41230. return rc;
  41231. }
  41232. /*
  41233. ** Acquire a page if it is already in the in-memory cache. Do
  41234. ** not read the page from disk. Return a pointer to the page,
  41235. ** or 0 if the page is not in cache.
  41236. **
  41237. ** See also sqlite3PagerGet(). The difference between this routine
  41238. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  41239. ** in the page if the page is not already in cache. This routine
  41240. ** returns NULL if the page is not in cache or if a disk I/O error
  41241. ** has ever happened.
  41242. */
  41243. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  41244. PgHdr *pPg = 0;
  41245. assert( pPager!=0 );
  41246. assert( pgno!=0 );
  41247. assert( pPager->pPCache!=0 );
  41248. assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
  41249. sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  41250. return pPg;
  41251. }
  41252. /*
  41253. ** Release a page reference.
  41254. **
  41255. ** If the number of references to the page drop to zero, then the
  41256. ** page is added to the LRU list. When all references to all pages
  41257. ** are released, a rollback occurs and the lock on the database is
  41258. ** removed.
  41259. */
  41260. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  41261. if( pPg ){
  41262. Pager *pPager = pPg->pPager;
  41263. if( pPg->flags & PGHDR_MMAP ){
  41264. pagerReleaseMapPage(pPg);
  41265. }else{
  41266. sqlite3PcacheRelease(pPg);
  41267. }
  41268. pagerUnlockIfUnused(pPager);
  41269. }
  41270. }
  41271. /*
  41272. ** This function is called at the start of every write transaction.
  41273. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  41274. ** file when this routine is called.
  41275. **
  41276. ** Open the journal file for pager pPager and write a journal header
  41277. ** to the start of it. If there are active savepoints, open the sub-journal
  41278. ** as well. This function is only used when the journal file is being
  41279. ** opened to write a rollback log for a transaction. It is not used
  41280. ** when opening a hot journal file to roll it back.
  41281. **
  41282. ** If the journal file is already open (as it may be in exclusive mode),
  41283. ** then this function just writes a journal header to the start of the
  41284. ** already open file.
  41285. **
  41286. ** Whether or not the journal file is opened by this function, the
  41287. ** Pager.pInJournal bitvec structure is allocated.
  41288. **
  41289. ** Return SQLITE_OK if everything is successful. Otherwise, return
  41290. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  41291. ** an IO error code if opening or writing the journal file fails.
  41292. */
  41293. static int pager_open_journal(Pager *pPager){
  41294. int rc = SQLITE_OK; /* Return code */
  41295. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  41296. assert( pPager->eState==PAGER_WRITER_LOCKED );
  41297. assert( assert_pager_state(pPager) );
  41298. assert( pPager->pInJournal==0 );
  41299. /* If already in the error state, this function is a no-op. But on
  41300. ** the other hand, this routine is never called if we are already in
  41301. ** an error state. */
  41302. if( NEVER(pPager->errCode) ) return pPager->errCode;
  41303. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  41304. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  41305. if( pPager->pInJournal==0 ){
  41306. return SQLITE_NOMEM;
  41307. }
  41308. /* Open the journal file if it is not already open. */
  41309. if( !isOpen(pPager->jfd) ){
  41310. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  41311. sqlite3MemJournalOpen(pPager->jfd);
  41312. }else{
  41313. const int flags = /* VFS flags to open journal file */
  41314. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  41315. (pPager->tempFile ?
  41316. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  41317. (SQLITE_OPEN_MAIN_JOURNAL)
  41318. );
  41319. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  41320. rc = sqlite3JournalOpen(
  41321. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  41322. );
  41323. #else
  41324. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  41325. #endif
  41326. }
  41327. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  41328. }
  41329. /* Write the first journal header to the journal file and open
  41330. ** the sub-journal if necessary.
  41331. */
  41332. if( rc==SQLITE_OK ){
  41333. /* TODO: Check if all of these are really required. */
  41334. pPager->nRec = 0;
  41335. pPager->journalOff = 0;
  41336. pPager->setMaster = 0;
  41337. pPager->journalHdr = 0;
  41338. rc = writeJournalHdr(pPager);
  41339. }
  41340. }
  41341. if( rc!=SQLITE_OK ){
  41342. sqlite3BitvecDestroy(pPager->pInJournal);
  41343. pPager->pInJournal = 0;
  41344. }else{
  41345. assert( pPager->eState==PAGER_WRITER_LOCKED );
  41346. pPager->eState = PAGER_WRITER_CACHEMOD;
  41347. }
  41348. return rc;
  41349. }
  41350. /*
  41351. ** Begin a write-transaction on the specified pager object. If a
  41352. ** write-transaction has already been opened, this function is a no-op.
  41353. **
  41354. ** If the exFlag argument is false, then acquire at least a RESERVED
  41355. ** lock on the database file. If exFlag is true, then acquire at least
  41356. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  41357. ** functions need be called.
  41358. **
  41359. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  41360. ** within this transaction will be opened as an in-memory file. This
  41361. ** has no effect if the sub-journal is already opened (as it may be when
  41362. ** running in exclusive mode) or if the transaction does not require a
  41363. ** sub-journal. If the subjInMemory argument is zero, then any required
  41364. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  41365. ** or using a temporary file otherwise.
  41366. */
  41367. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  41368. int rc = SQLITE_OK;
  41369. if( pPager->errCode ) return pPager->errCode;
  41370. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  41371. pPager->subjInMemory = (u8)subjInMemory;
  41372. if( ALWAYS(pPager->eState==PAGER_READER) ){
  41373. assert( pPager->pInJournal==0 );
  41374. if( pagerUseWal(pPager) ){
  41375. /* If the pager is configured to use locking_mode=exclusive, and an
  41376. ** exclusive lock on the database is not already held, obtain it now.
  41377. */
  41378. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  41379. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  41380. if( rc!=SQLITE_OK ){
  41381. return rc;
  41382. }
  41383. sqlite3WalExclusiveMode(pPager->pWal, 1);
  41384. }
  41385. /* Grab the write lock on the log file. If successful, upgrade to
  41386. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  41387. ** The busy-handler is not invoked if another connection already
  41388. ** holds the write-lock. If possible, the upper layer will call it.
  41389. */
  41390. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  41391. }else{
  41392. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  41393. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  41394. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  41395. ** lock, but not when obtaining the RESERVED lock.
  41396. */
  41397. rc = pagerLockDb(pPager, RESERVED_LOCK);
  41398. if( rc==SQLITE_OK && exFlag ){
  41399. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  41400. }
  41401. }
  41402. if( rc==SQLITE_OK ){
  41403. /* Change to WRITER_LOCKED state.
  41404. **
  41405. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  41406. ** when it has an open transaction, but never to DBMOD or FINISHED.
  41407. ** This is because in those states the code to roll back savepoint
  41408. ** transactions may copy data from the sub-journal into the database
  41409. ** file as well as into the page cache. Which would be incorrect in
  41410. ** WAL mode.
  41411. */
  41412. pPager->eState = PAGER_WRITER_LOCKED;
  41413. pPager->dbHintSize = pPager->dbSize;
  41414. pPager->dbFileSize = pPager->dbSize;
  41415. pPager->dbOrigSize = pPager->dbSize;
  41416. pPager->journalOff = 0;
  41417. }
  41418. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  41419. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  41420. assert( assert_pager_state(pPager) );
  41421. }
  41422. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  41423. return rc;
  41424. }
  41425. /*
  41426. ** Mark a single data page as writeable. The page is written into the
  41427. ** main journal or sub-journal as required. If the page is written into
  41428. ** one of the journals, the corresponding bit is set in the
  41429. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  41430. ** of any open savepoints as appropriate.
  41431. */
  41432. static int pager_write(PgHdr *pPg){
  41433. void *pData = pPg->pData;
  41434. Pager *pPager = pPg->pPager;
  41435. int rc = SQLITE_OK;
  41436. /* This routine is not called unless a write-transaction has already
  41437. ** been started. The journal file may or may not be open at this point.
  41438. ** It is never called in the ERROR state.
  41439. */
  41440. assert( pPager->eState==PAGER_WRITER_LOCKED
  41441. || pPager->eState==PAGER_WRITER_CACHEMOD
  41442. || pPager->eState==PAGER_WRITER_DBMOD
  41443. );
  41444. assert( assert_pager_state(pPager) );
  41445. /* If an error has been previously detected, report the same error
  41446. ** again. This should not happen, but the check provides robustness. */
  41447. if( NEVER(pPager->errCode) ) return pPager->errCode;
  41448. /* Higher-level routines never call this function if database is not
  41449. ** writable. But check anyway, just for robustness. */
  41450. if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
  41451. CHECK_PAGE(pPg);
  41452. /* The journal file needs to be opened. Higher level routines have already
  41453. ** obtained the necessary locks to begin the write-transaction, but the
  41454. ** rollback journal might not yet be open. Open it now if this is the case.
  41455. **
  41456. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  41457. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  41458. ** an error might occur and the pager would end up in WRITER_LOCKED state
  41459. ** with pages marked as dirty in the cache.
  41460. */
  41461. if( pPager->eState==PAGER_WRITER_LOCKED ){
  41462. rc = pager_open_journal(pPager);
  41463. if( rc!=SQLITE_OK ) return rc;
  41464. }
  41465. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  41466. assert( assert_pager_state(pPager) );
  41467. /* Mark the page as dirty. If the page has already been written
  41468. ** to the journal then we can return right away.
  41469. */
  41470. sqlite3PcacheMakeDirty(pPg);
  41471. if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
  41472. assert( !pagerUseWal(pPager) );
  41473. }else{
  41474. /* The transaction journal now exists and we have a RESERVED or an
  41475. ** EXCLUSIVE lock on the main database file. Write the current page to
  41476. ** the transaction journal if it is not there already.
  41477. */
  41478. if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
  41479. assert( pagerUseWal(pPager)==0 );
  41480. if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
  41481. u32 cksum;
  41482. char *pData2;
  41483. i64 iOff = pPager->journalOff;
  41484. /* We should never write to the journal file the page that
  41485. ** contains the database locks. The following assert verifies
  41486. ** that we do not. */
  41487. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  41488. assert( pPager->journalHdr<=pPager->journalOff );
  41489. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  41490. cksum = pager_cksum(pPager, (u8*)pData2);
  41491. /* Even if an IO or diskfull error occurs while journalling the
  41492. ** page in the block above, set the need-sync flag for the page.
  41493. ** Otherwise, when the transaction is rolled back, the logic in
  41494. ** playback_one_page() will think that the page needs to be restored
  41495. ** in the database file. And if an IO error occurs while doing so,
  41496. ** then corruption may follow.
  41497. */
  41498. pPg->flags |= PGHDR_NEED_SYNC;
  41499. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  41500. if( rc!=SQLITE_OK ) return rc;
  41501. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  41502. if( rc!=SQLITE_OK ) return rc;
  41503. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  41504. if( rc!=SQLITE_OK ) return rc;
  41505. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  41506. pPager->journalOff, pPager->pageSize));
  41507. PAGER_INCR(sqlite3_pager_writej_count);
  41508. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  41509. PAGERID(pPager), pPg->pgno,
  41510. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  41511. pPager->journalOff += 8 + pPager->pageSize;
  41512. pPager->nRec++;
  41513. assert( pPager->pInJournal!=0 );
  41514. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  41515. testcase( rc==SQLITE_NOMEM );
  41516. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  41517. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  41518. if( rc!=SQLITE_OK ){
  41519. assert( rc==SQLITE_NOMEM );
  41520. return rc;
  41521. }
  41522. }else{
  41523. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  41524. pPg->flags |= PGHDR_NEED_SYNC;
  41525. }
  41526. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  41527. PAGERID(pPager), pPg->pgno,
  41528. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  41529. }
  41530. }
  41531. /* If the statement journal is open and the page is not in it,
  41532. ** then write the current page to the statement journal. Note that
  41533. ** the statement journal format differs from the standard journal format
  41534. ** in that it omits the checksums and the header.
  41535. */
  41536. if( subjRequiresPage(pPg) ){
  41537. rc = subjournalPage(pPg);
  41538. }
  41539. }
  41540. /* Update the database size and return.
  41541. */
  41542. if( pPager->dbSize<pPg->pgno ){
  41543. pPager->dbSize = pPg->pgno;
  41544. }
  41545. return rc;
  41546. }
  41547. /*
  41548. ** Mark a data page as writeable. This routine must be called before
  41549. ** making changes to a page. The caller must check the return value
  41550. ** of this function and be careful not to change any page data unless
  41551. ** this routine returns SQLITE_OK.
  41552. **
  41553. ** The difference between this function and pager_write() is that this
  41554. ** function also deals with the special case where 2 or more pages
  41555. ** fit on a single disk sector. In this case all co-resident pages
  41556. ** must have been written to the journal file before returning.
  41557. **
  41558. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  41559. ** as appropriate. Otherwise, SQLITE_OK.
  41560. */
  41561. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  41562. int rc = SQLITE_OK;
  41563. PgHdr *pPg = pDbPage;
  41564. Pager *pPager = pPg->pPager;
  41565. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  41566. assert( (pPg->flags & PGHDR_MMAP)==0 );
  41567. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  41568. assert( pPager->eState!=PAGER_ERROR );
  41569. assert( assert_pager_state(pPager) );
  41570. if( nPagePerSector>1 ){
  41571. Pgno nPageCount; /* Total number of pages in database file */
  41572. Pgno pg1; /* First page of the sector pPg is located on. */
  41573. int nPage = 0; /* Number of pages starting at pg1 to journal */
  41574. int ii; /* Loop counter */
  41575. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  41576. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  41577. ** a journal header to be written between the pages journaled by
  41578. ** this function.
  41579. */
  41580. assert( !MEMDB );
  41581. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  41582. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  41583. /* This trick assumes that both the page-size and sector-size are
  41584. ** an integer power of 2. It sets variable pg1 to the identifier
  41585. ** of the first page of the sector pPg is located on.
  41586. */
  41587. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  41588. nPageCount = pPager->dbSize;
  41589. if( pPg->pgno>nPageCount ){
  41590. nPage = (pPg->pgno - pg1)+1;
  41591. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  41592. nPage = nPageCount+1-pg1;
  41593. }else{
  41594. nPage = nPagePerSector;
  41595. }
  41596. assert(nPage>0);
  41597. assert(pg1<=pPg->pgno);
  41598. assert((pg1+nPage)>pPg->pgno);
  41599. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  41600. Pgno pg = pg1+ii;
  41601. PgHdr *pPage;
  41602. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  41603. if( pg!=PAGER_MJ_PGNO(pPager) ){
  41604. rc = sqlite3PagerGet(pPager, pg, &pPage);
  41605. if( rc==SQLITE_OK ){
  41606. rc = pager_write(pPage);
  41607. if( pPage->flags&PGHDR_NEED_SYNC ){
  41608. needSync = 1;
  41609. }
  41610. sqlite3PagerUnref(pPage);
  41611. }
  41612. }
  41613. }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
  41614. if( pPage->flags&PGHDR_NEED_SYNC ){
  41615. needSync = 1;
  41616. }
  41617. sqlite3PagerUnref(pPage);
  41618. }
  41619. }
  41620. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  41621. ** starting at pg1, then it needs to be set for all of them. Because
  41622. ** writing to any of these nPage pages may damage the others, the
  41623. ** journal file must contain sync()ed copies of all of them
  41624. ** before any of them can be written out to the database file.
  41625. */
  41626. if( rc==SQLITE_OK && needSync ){
  41627. assert( !MEMDB );
  41628. for(ii=0; ii<nPage; ii++){
  41629. PgHdr *pPage = pager_lookup(pPager, pg1+ii);
  41630. if( pPage ){
  41631. pPage->flags |= PGHDR_NEED_SYNC;
  41632. sqlite3PagerUnref(pPage);
  41633. }
  41634. }
  41635. }
  41636. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  41637. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  41638. }else{
  41639. rc = pager_write(pDbPage);
  41640. }
  41641. return rc;
  41642. }
  41643. /*
  41644. ** Return TRUE if the page given in the argument was previously passed
  41645. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  41646. ** to change the content of the page.
  41647. */
  41648. #ifndef NDEBUG
  41649. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  41650. return pPg->flags&PGHDR_DIRTY;
  41651. }
  41652. #endif
  41653. /*
  41654. ** A call to this routine tells the pager that it is not necessary to
  41655. ** write the information on page pPg back to the disk, even though
  41656. ** that page might be marked as dirty. This happens, for example, when
  41657. ** the page has been added as a leaf of the freelist and so its
  41658. ** content no longer matters.
  41659. **
  41660. ** The overlying software layer calls this routine when all of the data
  41661. ** on the given page is unused. The pager marks the page as clean so
  41662. ** that it does not get written to disk.
  41663. **
  41664. ** Tests show that this optimization can quadruple the speed of large
  41665. ** DELETE operations.
  41666. */
  41667. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  41668. Pager *pPager = pPg->pPager;
  41669. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  41670. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  41671. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  41672. pPg->flags |= PGHDR_DONT_WRITE;
  41673. pager_set_pagehash(pPg);
  41674. }
  41675. }
  41676. /*
  41677. ** This routine is called to increment the value of the database file
  41678. ** change-counter, stored as a 4-byte big-endian integer starting at
  41679. ** byte offset 24 of the pager file. The secondary change counter at
  41680. ** 92 is also updated, as is the SQLite version number at offset 96.
  41681. **
  41682. ** But this only happens if the pPager->changeCountDone flag is false.
  41683. ** To avoid excess churning of page 1, the update only happens once.
  41684. ** See also the pager_write_changecounter() routine that does an
  41685. ** unconditional update of the change counters.
  41686. **
  41687. ** If the isDirectMode flag is zero, then this is done by calling
  41688. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  41689. ** page data. In this case the file will be updated when the current
  41690. ** transaction is committed.
  41691. **
  41692. ** The isDirectMode flag may only be non-zero if the library was compiled
  41693. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  41694. ** if isDirect is non-zero, then the database file is updated directly
  41695. ** by writing an updated version of page 1 using a call to the
  41696. ** sqlite3OsWrite() function.
  41697. */
  41698. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  41699. int rc = SQLITE_OK;
  41700. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  41701. || pPager->eState==PAGER_WRITER_DBMOD
  41702. );
  41703. assert( assert_pager_state(pPager) );
  41704. /* Declare and initialize constant integer 'isDirect'. If the
  41705. ** atomic-write optimization is enabled in this build, then isDirect
  41706. ** is initialized to the value passed as the isDirectMode parameter
  41707. ** to this function. Otherwise, it is always set to zero.
  41708. **
  41709. ** The idea is that if the atomic-write optimization is not
  41710. ** enabled at compile time, the compiler can omit the tests of
  41711. ** 'isDirect' below, as well as the block enclosed in the
  41712. ** "if( isDirect )" condition.
  41713. */
  41714. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  41715. # define DIRECT_MODE 0
  41716. assert( isDirectMode==0 );
  41717. UNUSED_PARAMETER(isDirectMode);
  41718. #else
  41719. # define DIRECT_MODE isDirectMode
  41720. #endif
  41721. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  41722. PgHdr *pPgHdr; /* Reference to page 1 */
  41723. assert( !pPager->tempFile && isOpen(pPager->fd) );
  41724. /* Open page 1 of the file for writing. */
  41725. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  41726. assert( pPgHdr==0 || rc==SQLITE_OK );
  41727. /* If page one was fetched successfully, and this function is not
  41728. ** operating in direct-mode, make page 1 writable. When not in
  41729. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  41730. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  41731. */
  41732. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  41733. rc = sqlite3PagerWrite(pPgHdr);
  41734. }
  41735. if( rc==SQLITE_OK ){
  41736. /* Actually do the update of the change counter */
  41737. pager_write_changecounter(pPgHdr);
  41738. /* If running in direct mode, write the contents of page 1 to the file. */
  41739. if( DIRECT_MODE ){
  41740. const void *zBuf;
  41741. assert( pPager->dbFileSize>0 );
  41742. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  41743. if( rc==SQLITE_OK ){
  41744. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  41745. pPager->aStat[PAGER_STAT_WRITE]++;
  41746. }
  41747. if( rc==SQLITE_OK ){
  41748. /* Update the pager's copy of the change-counter. Otherwise, the
  41749. ** next time a read transaction is opened the cache will be
  41750. ** flushed (as the change-counter values will not match). */
  41751. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  41752. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  41753. pPager->changeCountDone = 1;
  41754. }
  41755. }else{
  41756. pPager->changeCountDone = 1;
  41757. }
  41758. }
  41759. /* Release the page reference. */
  41760. sqlite3PagerUnref(pPgHdr);
  41761. }
  41762. return rc;
  41763. }
  41764. /*
  41765. ** Sync the database file to disk. This is a no-op for in-memory databases
  41766. ** or pages with the Pager.noSync flag set.
  41767. **
  41768. ** If successful, or if called on a pager for which it is a no-op, this
  41769. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  41770. */
  41771. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  41772. int rc = SQLITE_OK;
  41773. if( !pPager->noSync ){
  41774. assert( !MEMDB );
  41775. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  41776. }else if( isOpen(pPager->fd) ){
  41777. assert( !MEMDB );
  41778. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
  41779. if( rc==SQLITE_NOTFOUND ){
  41780. rc = SQLITE_OK;
  41781. }
  41782. }
  41783. return rc;
  41784. }
  41785. /*
  41786. ** This function may only be called while a write-transaction is active in
  41787. ** rollback. If the connection is in WAL mode, this call is a no-op.
  41788. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  41789. ** the database file, an attempt is made to obtain one.
  41790. **
  41791. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  41792. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  41793. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  41794. ** returned.
  41795. */
  41796. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  41797. int rc = SQLITE_OK;
  41798. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  41799. || pPager->eState==PAGER_WRITER_DBMOD
  41800. || pPager->eState==PAGER_WRITER_LOCKED
  41801. );
  41802. assert( assert_pager_state(pPager) );
  41803. if( 0==pagerUseWal(pPager) ){
  41804. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  41805. }
  41806. return rc;
  41807. }
  41808. /*
  41809. ** Sync the database file for the pager pPager. zMaster points to the name
  41810. ** of a master journal file that should be written into the individual
  41811. ** journal file. zMaster may be NULL, which is interpreted as no master
  41812. ** journal (a single database transaction).
  41813. **
  41814. ** This routine ensures that:
  41815. **
  41816. ** * The database file change-counter is updated,
  41817. ** * the journal is synced (unless the atomic-write optimization is used),
  41818. ** * all dirty pages are written to the database file,
  41819. ** * the database file is truncated (if required), and
  41820. ** * the database file synced.
  41821. **
  41822. ** The only thing that remains to commit the transaction is to finalize
  41823. ** (delete, truncate or zero the first part of) the journal file (or
  41824. ** delete the master journal file if specified).
  41825. **
  41826. ** Note that if zMaster==NULL, this does not overwrite a previous value
  41827. ** passed to an sqlite3PagerCommitPhaseOne() call.
  41828. **
  41829. ** If the final parameter - noSync - is true, then the database file itself
  41830. ** is not synced. The caller must call sqlite3PagerSync() directly to
  41831. ** sync the database file before calling CommitPhaseTwo() to delete the
  41832. ** journal file in this case.
  41833. */
  41834. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  41835. Pager *pPager, /* Pager object */
  41836. const char *zMaster, /* If not NULL, the master journal name */
  41837. int noSync /* True to omit the xSync on the db file */
  41838. ){
  41839. int rc = SQLITE_OK; /* Return code */
  41840. assert( pPager->eState==PAGER_WRITER_LOCKED
  41841. || pPager->eState==PAGER_WRITER_CACHEMOD
  41842. || pPager->eState==PAGER_WRITER_DBMOD
  41843. || pPager->eState==PAGER_ERROR
  41844. );
  41845. assert( assert_pager_state(pPager) );
  41846. /* If a prior error occurred, report that error again. */
  41847. if( NEVER(pPager->errCode) ) return pPager->errCode;
  41848. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  41849. pPager->zFilename, zMaster, pPager->dbSize));
  41850. /* If no database changes have been made, return early. */
  41851. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  41852. if( MEMDB ){
  41853. /* If this is an in-memory db, or no pages have been written to, or this
  41854. ** function has already been called, it is mostly a no-op. However, any
  41855. ** backup in progress needs to be restarted.
  41856. */
  41857. sqlite3BackupRestart(pPager->pBackup);
  41858. }else{
  41859. if( pagerUseWal(pPager) ){
  41860. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  41861. PgHdr *pPageOne = 0;
  41862. if( pList==0 ){
  41863. /* Must have at least one page for the WAL commit flag.
  41864. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  41865. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  41866. pList = pPageOne;
  41867. pList->pDirty = 0;
  41868. }
  41869. assert( rc==SQLITE_OK );
  41870. if( ALWAYS(pList) ){
  41871. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  41872. }
  41873. sqlite3PagerUnref(pPageOne);
  41874. if( rc==SQLITE_OK ){
  41875. sqlite3PcacheCleanAll(pPager->pPCache);
  41876. }
  41877. }else{
  41878. /* The following block updates the change-counter. Exactly how it
  41879. ** does this depends on whether or not the atomic-update optimization
  41880. ** was enabled at compile time, and if this transaction meets the
  41881. ** runtime criteria to use the operation:
  41882. **
  41883. ** * The file-system supports the atomic-write property for
  41884. ** blocks of size page-size, and
  41885. ** * This commit is not part of a multi-file transaction, and
  41886. ** * Exactly one page has been modified and store in the journal file.
  41887. **
  41888. ** If the optimization was not enabled at compile time, then the
  41889. ** pager_incr_changecounter() function is called to update the change
  41890. ** counter in 'indirect-mode'. If the optimization is compiled in but
  41891. ** is not applicable to this transaction, call sqlite3JournalCreate()
  41892. ** to make sure the journal file has actually been created, then call
  41893. ** pager_incr_changecounter() to update the change-counter in indirect
  41894. ** mode.
  41895. **
  41896. ** Otherwise, if the optimization is both enabled and applicable,
  41897. ** then call pager_incr_changecounter() to update the change-counter
  41898. ** in 'direct' mode. In this case the journal file will never be
  41899. ** created for this transaction.
  41900. */
  41901. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  41902. PgHdr *pPg;
  41903. assert( isOpen(pPager->jfd)
  41904. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  41905. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  41906. );
  41907. if( !zMaster && isOpen(pPager->jfd)
  41908. && pPager->journalOff==jrnlBufferSize(pPager)
  41909. && pPager->dbSize>=pPager->dbOrigSize
  41910. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  41911. ){
  41912. /* Update the db file change counter via the direct-write method. The
  41913. ** following call will modify the in-memory representation of page 1
  41914. ** to include the updated change counter and then write page 1
  41915. ** directly to the database file. Because of the atomic-write
  41916. ** property of the host file-system, this is safe.
  41917. */
  41918. rc = pager_incr_changecounter(pPager, 1);
  41919. }else{
  41920. rc = sqlite3JournalCreate(pPager->jfd);
  41921. if( rc==SQLITE_OK ){
  41922. rc = pager_incr_changecounter(pPager, 0);
  41923. }
  41924. }
  41925. #else
  41926. rc = pager_incr_changecounter(pPager, 0);
  41927. #endif
  41928. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  41929. /* Write the master journal name into the journal file. If a master
  41930. ** journal file name has already been written to the journal file,
  41931. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  41932. */
  41933. rc = writeMasterJournal(pPager, zMaster);
  41934. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  41935. /* Sync the journal file and write all dirty pages to the database.
  41936. ** If the atomic-update optimization is being used, this sync will not
  41937. ** create the journal file or perform any real IO.
  41938. **
  41939. ** Because the change-counter page was just modified, unless the
  41940. ** atomic-update optimization is used it is almost certain that the
  41941. ** journal requires a sync here. However, in locking_mode=exclusive
  41942. ** on a system under memory pressure it is just possible that this is
  41943. ** not the case. In this case it is likely enough that the redundant
  41944. ** xSync() call will be changed to a no-op by the OS anyhow.
  41945. */
  41946. rc = syncJournal(pPager, 0);
  41947. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  41948. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  41949. if( rc!=SQLITE_OK ){
  41950. assert( rc!=SQLITE_IOERR_BLOCKED );
  41951. goto commit_phase_one_exit;
  41952. }
  41953. sqlite3PcacheCleanAll(pPager->pPCache);
  41954. /* If the file on disk is smaller than the database image, use
  41955. ** pager_truncate to grow the file here. This can happen if the database
  41956. ** image was extended as part of the current transaction and then the
  41957. ** last page in the db image moved to the free-list. In this case the
  41958. ** last page is never written out to disk, leaving the database file
  41959. ** undersized. Fix this now if it is the case. */
  41960. if( pPager->dbSize>pPager->dbFileSize ){
  41961. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  41962. assert( pPager->eState==PAGER_WRITER_DBMOD );
  41963. rc = pager_truncate(pPager, nNew);
  41964. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  41965. }
  41966. /* Finally, sync the database file. */
  41967. if( !noSync ){
  41968. rc = sqlite3PagerSync(pPager);
  41969. }
  41970. IOTRACE(("DBSYNC %p\n", pPager))
  41971. }
  41972. }
  41973. commit_phase_one_exit:
  41974. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  41975. pPager->eState = PAGER_WRITER_FINISHED;
  41976. }
  41977. return rc;
  41978. }
  41979. /*
  41980. ** When this function is called, the database file has been completely
  41981. ** updated to reflect the changes made by the current transaction and
  41982. ** synced to disk. The journal file still exists in the file-system
  41983. ** though, and if a failure occurs at this point it will eventually
  41984. ** be used as a hot-journal and the current transaction rolled back.
  41985. **
  41986. ** This function finalizes the journal file, either by deleting,
  41987. ** truncating or partially zeroing it, so that it cannot be used
  41988. ** for hot-journal rollback. Once this is done the transaction is
  41989. ** irrevocably committed.
  41990. **
  41991. ** If an error occurs, an IO error code is returned and the pager
  41992. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  41993. */
  41994. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  41995. int rc = SQLITE_OK; /* Return code */
  41996. /* This routine should not be called if a prior error has occurred.
  41997. ** But if (due to a coding error elsewhere in the system) it does get
  41998. ** called, just return the same error code without doing anything. */
  41999. if( NEVER(pPager->errCode) ) return pPager->errCode;
  42000. assert( pPager->eState==PAGER_WRITER_LOCKED
  42001. || pPager->eState==PAGER_WRITER_FINISHED
  42002. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  42003. );
  42004. assert( assert_pager_state(pPager) );
  42005. /* An optimization. If the database was not actually modified during
  42006. ** this transaction, the pager is running in exclusive-mode and is
  42007. ** using persistent journals, then this function is a no-op.
  42008. **
  42009. ** The start of the journal file currently contains a single journal
  42010. ** header with the nRec field set to 0. If such a journal is used as
  42011. ** a hot-journal during hot-journal rollback, 0 changes will be made
  42012. ** to the database file. So there is no need to zero the journal
  42013. ** header. Since the pager is in exclusive mode, there is no need
  42014. ** to drop any locks either.
  42015. */
  42016. if( pPager->eState==PAGER_WRITER_LOCKED
  42017. && pPager->exclusiveMode
  42018. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  42019. ){
  42020. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  42021. pPager->eState = PAGER_READER;
  42022. return SQLITE_OK;
  42023. }
  42024. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  42025. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  42026. return pager_error(pPager, rc);
  42027. }
  42028. /*
  42029. ** If a write transaction is open, then all changes made within the
  42030. ** transaction are reverted and the current write-transaction is closed.
  42031. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  42032. ** state if an error occurs.
  42033. **
  42034. ** If the pager is already in PAGER_ERROR state when this function is called,
  42035. ** it returns Pager.errCode immediately. No work is performed in this case.
  42036. **
  42037. ** Otherwise, in rollback mode, this function performs two functions:
  42038. **
  42039. ** 1) It rolls back the journal file, restoring all database file and
  42040. ** in-memory cache pages to the state they were in when the transaction
  42041. ** was opened, and
  42042. **
  42043. ** 2) It finalizes the journal file, so that it is not used for hot
  42044. ** rollback at any point in the future.
  42045. **
  42046. ** Finalization of the journal file (task 2) is only performed if the
  42047. ** rollback is successful.
  42048. **
  42049. ** In WAL mode, all cache-entries containing data modified within the
  42050. ** current transaction are either expelled from the cache or reverted to
  42051. ** their pre-transaction state by re-reading data from the database or
  42052. ** WAL files. The WAL transaction is then closed.
  42053. */
  42054. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  42055. int rc = SQLITE_OK; /* Return code */
  42056. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  42057. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  42058. ** the pager is already in the ERROR state, the rollback is not
  42059. ** attempted here. Instead, the error code is returned to the caller.
  42060. */
  42061. assert( assert_pager_state(pPager) );
  42062. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  42063. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  42064. if( pagerUseWal(pPager) ){
  42065. int rc2;
  42066. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  42067. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  42068. if( rc==SQLITE_OK ) rc = rc2;
  42069. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  42070. int eState = pPager->eState;
  42071. rc = pager_end_transaction(pPager, 0, 0);
  42072. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  42073. /* This can happen using journal_mode=off. Move the pager to the error
  42074. ** state to indicate that the contents of the cache may not be trusted.
  42075. ** Any active readers will get SQLITE_ABORT.
  42076. */
  42077. pPager->errCode = SQLITE_ABORT;
  42078. pPager->eState = PAGER_ERROR;
  42079. return rc;
  42080. }
  42081. }else{
  42082. rc = pager_playback(pPager, 0);
  42083. }
  42084. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  42085. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  42086. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
  42087. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  42088. ** cache. So call pager_error() on the way out to make any error persistent.
  42089. */
  42090. return pager_error(pPager, rc);
  42091. }
  42092. /*
  42093. ** Return TRUE if the database file is opened read-only. Return FALSE
  42094. ** if the database is (in theory) writable.
  42095. */
  42096. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  42097. return pPager->readOnly;
  42098. }
  42099. /*
  42100. ** Return the number of references to the pager.
  42101. */
  42102. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  42103. return sqlite3PcacheRefCount(pPager->pPCache);
  42104. }
  42105. /*
  42106. ** Return the approximate number of bytes of memory currently
  42107. ** used by the pager and its associated cache.
  42108. */
  42109. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  42110. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  42111. + 5*sizeof(void*);
  42112. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  42113. + sqlite3MallocSize(pPager)
  42114. + pPager->pageSize;
  42115. }
  42116. /*
  42117. ** Return the number of references to the specified page.
  42118. */
  42119. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  42120. return sqlite3PcachePageRefcount(pPage);
  42121. }
  42122. #ifdef SQLITE_TEST
  42123. /*
  42124. ** This routine is used for testing and analysis only.
  42125. */
  42126. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  42127. static int a[11];
  42128. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  42129. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  42130. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  42131. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  42132. a[4] = pPager->eState;
  42133. a[5] = pPager->errCode;
  42134. a[6] = pPager->aStat[PAGER_STAT_HIT];
  42135. a[7] = pPager->aStat[PAGER_STAT_MISS];
  42136. a[8] = 0; /* Used to be pPager->nOvfl */
  42137. a[9] = pPager->nRead;
  42138. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  42139. return a;
  42140. }
  42141. #endif
  42142. /*
  42143. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  42144. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  42145. ** current cache hit or miss count, according to the value of eStat. If the
  42146. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  42147. ** returning.
  42148. */
  42149. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  42150. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  42151. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  42152. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  42153. );
  42154. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  42155. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  42156. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  42157. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  42158. if( reset ){
  42159. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  42160. }
  42161. }
  42162. /*
  42163. ** Return true if this is an in-memory pager.
  42164. */
  42165. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  42166. return MEMDB;
  42167. }
  42168. /*
  42169. ** Check that there are at least nSavepoint savepoints open. If there are
  42170. ** currently less than nSavepoints open, then open one or more savepoints
  42171. ** to make up the difference. If the number of savepoints is already
  42172. ** equal to nSavepoint, then this function is a no-op.
  42173. **
  42174. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  42175. ** occurs while opening the sub-journal file, then an IO error code is
  42176. ** returned. Otherwise, SQLITE_OK.
  42177. */
  42178. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  42179. int rc = SQLITE_OK; /* Return code */
  42180. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  42181. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  42182. assert( assert_pager_state(pPager) );
  42183. if( nSavepoint>nCurrent && pPager->useJournal ){
  42184. int ii; /* Iterator variable */
  42185. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  42186. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  42187. ** if the allocation fails. Otherwise, zero the new portion in case a
  42188. ** malloc failure occurs while populating it in the for(...) loop below.
  42189. */
  42190. aNew = (PagerSavepoint *)sqlite3Realloc(
  42191. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  42192. );
  42193. if( !aNew ){
  42194. return SQLITE_NOMEM;
  42195. }
  42196. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  42197. pPager->aSavepoint = aNew;
  42198. /* Populate the PagerSavepoint structures just allocated. */
  42199. for(ii=nCurrent; ii<nSavepoint; ii++){
  42200. aNew[ii].nOrig = pPager->dbSize;
  42201. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  42202. aNew[ii].iOffset = pPager->journalOff;
  42203. }else{
  42204. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  42205. }
  42206. aNew[ii].iSubRec = pPager->nSubRec;
  42207. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  42208. if( !aNew[ii].pInSavepoint ){
  42209. return SQLITE_NOMEM;
  42210. }
  42211. if( pagerUseWal(pPager) ){
  42212. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  42213. }
  42214. pPager->nSavepoint = ii+1;
  42215. }
  42216. assert( pPager->nSavepoint==nSavepoint );
  42217. assertTruncateConstraint(pPager);
  42218. }
  42219. return rc;
  42220. }
  42221. /*
  42222. ** This function is called to rollback or release (commit) a savepoint.
  42223. ** The savepoint to release or rollback need not be the most recently
  42224. ** created savepoint.
  42225. **
  42226. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  42227. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  42228. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  42229. ** that have occurred since the specified savepoint was created.
  42230. **
  42231. ** The savepoint to rollback or release is identified by parameter
  42232. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  42233. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  42234. ** on the most recently created savepoint. If iSavepoint is greater than
  42235. ** (Pager.nSavepoint-1), then this function is a no-op.
  42236. **
  42237. ** If a negative value is passed to this function, then the current
  42238. ** transaction is rolled back. This is different to calling
  42239. ** sqlite3PagerRollback() because this function does not terminate
  42240. ** the transaction or unlock the database, it just restores the
  42241. ** contents of the database to its original state.
  42242. **
  42243. ** In any case, all savepoints with an index greater than iSavepoint
  42244. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  42245. ** then savepoint iSavepoint is also destroyed.
  42246. **
  42247. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  42248. ** or an IO error code if an IO error occurs while rolling back a
  42249. ** savepoint. If no errors occur, SQLITE_OK is returned.
  42250. */
  42251. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  42252. int rc = pPager->errCode; /* Return code */
  42253. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  42254. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  42255. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  42256. int ii; /* Iterator variable */
  42257. int nNew; /* Number of remaining savepoints after this op. */
  42258. /* Figure out how many savepoints will still be active after this
  42259. ** operation. Store this value in nNew. Then free resources associated
  42260. ** with any savepoints that are destroyed by this operation.
  42261. */
  42262. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  42263. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  42264. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  42265. }
  42266. pPager->nSavepoint = nNew;
  42267. /* If this is a release of the outermost savepoint, truncate
  42268. ** the sub-journal to zero bytes in size. */
  42269. if( op==SAVEPOINT_RELEASE ){
  42270. if( nNew==0 && isOpen(pPager->sjfd) ){
  42271. /* Only truncate if it is an in-memory sub-journal. */
  42272. if( sqlite3IsMemJournal(pPager->sjfd) ){
  42273. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  42274. assert( rc==SQLITE_OK );
  42275. }
  42276. pPager->nSubRec = 0;
  42277. }
  42278. }
  42279. /* Else this is a rollback operation, playback the specified savepoint.
  42280. ** If this is a temp-file, it is possible that the journal file has
  42281. ** not yet been opened. In this case there have been no changes to
  42282. ** the database file, so the playback operation can be skipped.
  42283. */
  42284. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  42285. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  42286. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  42287. assert(rc!=SQLITE_DONE);
  42288. }
  42289. }
  42290. return rc;
  42291. }
  42292. /*
  42293. ** Return the full pathname of the database file.
  42294. **
  42295. ** Except, if the pager is in-memory only, then return an empty string if
  42296. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  42297. ** used to report the filename to the user, for compatibility with legacy
  42298. ** behavior. But when the Btree needs to know the filename for matching to
  42299. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  42300. ** participate in shared-cache.
  42301. */
  42302. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  42303. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  42304. }
  42305. /*
  42306. ** Return the VFS structure for the pager.
  42307. */
  42308. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  42309. return pPager->pVfs;
  42310. }
  42311. /*
  42312. ** Return the file handle for the database file associated
  42313. ** with the pager. This might return NULL if the file has
  42314. ** not yet been opened.
  42315. */
  42316. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  42317. return pPager->fd;
  42318. }
  42319. /*
  42320. ** Return the full pathname of the journal file.
  42321. */
  42322. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  42323. return pPager->zJournal;
  42324. }
  42325. /*
  42326. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  42327. ** if fsync()s are executed normally.
  42328. */
  42329. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  42330. return pPager->noSync;
  42331. }
  42332. #ifdef SQLITE_HAS_CODEC
  42333. /*
  42334. ** Set or retrieve the codec for this pager
  42335. */
  42336. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  42337. Pager *pPager,
  42338. void *(*xCodec)(void*,void*,Pgno,int),
  42339. void (*xCodecSizeChng)(void*,int,int),
  42340. void (*xCodecFree)(void*),
  42341. void *pCodec
  42342. ){
  42343. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  42344. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  42345. pPager->xCodecSizeChng = xCodecSizeChng;
  42346. pPager->xCodecFree = xCodecFree;
  42347. pPager->pCodec = pCodec;
  42348. pagerReportSize(pPager);
  42349. }
  42350. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  42351. return pPager->pCodec;
  42352. }
  42353. /*
  42354. ** This function is called by the wal module when writing page content
  42355. ** into the log file.
  42356. **
  42357. ** This function returns a pointer to a buffer containing the encrypted
  42358. ** page content. If a malloc fails, this function may return NULL.
  42359. */
  42360. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  42361. void *aData = 0;
  42362. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  42363. return aData;
  42364. }
  42365. /*
  42366. ** Return the current pager state
  42367. */
  42368. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  42369. return pPager->eState;
  42370. }
  42371. #endif /* SQLITE_HAS_CODEC */
  42372. #ifndef SQLITE_OMIT_AUTOVACUUM
  42373. /*
  42374. ** Move the page pPg to location pgno in the file.
  42375. **
  42376. ** There must be no references to the page previously located at
  42377. ** pgno (which we call pPgOld) though that page is allowed to be
  42378. ** in cache. If the page previously located at pgno is not already
  42379. ** in the rollback journal, it is not put there by by this routine.
  42380. **
  42381. ** References to the page pPg remain valid. Updating any
  42382. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  42383. ** allocated along with the page) is the responsibility of the caller.
  42384. **
  42385. ** A transaction must be active when this routine is called. It used to be
  42386. ** required that a statement transaction was not active, but this restriction
  42387. ** has been removed (CREATE INDEX needs to move a page when a statement
  42388. ** transaction is active).
  42389. **
  42390. ** If the fourth argument, isCommit, is non-zero, then this page is being
  42391. ** moved as part of a database reorganization just before the transaction
  42392. ** is being committed. In this case, it is guaranteed that the database page
  42393. ** pPg refers to will not be written to again within this transaction.
  42394. **
  42395. ** This function may return SQLITE_NOMEM or an IO error code if an error
  42396. ** occurs. Otherwise, it returns SQLITE_OK.
  42397. */
  42398. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  42399. PgHdr *pPgOld; /* The page being overwritten. */
  42400. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  42401. int rc; /* Return code */
  42402. Pgno origPgno; /* The original page number */
  42403. assert( pPg->nRef>0 );
  42404. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  42405. || pPager->eState==PAGER_WRITER_DBMOD
  42406. );
  42407. assert( assert_pager_state(pPager) );
  42408. /* In order to be able to rollback, an in-memory database must journal
  42409. ** the page we are moving from.
  42410. */
  42411. if( MEMDB ){
  42412. rc = sqlite3PagerWrite(pPg);
  42413. if( rc ) return rc;
  42414. }
  42415. /* If the page being moved is dirty and has not been saved by the latest
  42416. ** savepoint, then save the current contents of the page into the
  42417. ** sub-journal now. This is required to handle the following scenario:
  42418. **
  42419. ** BEGIN;
  42420. ** <journal page X, then modify it in memory>
  42421. ** SAVEPOINT one;
  42422. ** <Move page X to location Y>
  42423. ** ROLLBACK TO one;
  42424. **
  42425. ** If page X were not written to the sub-journal here, it would not
  42426. ** be possible to restore its contents when the "ROLLBACK TO one"
  42427. ** statement were is processed.
  42428. **
  42429. ** subjournalPage() may need to allocate space to store pPg->pgno into
  42430. ** one or more savepoint bitvecs. This is the reason this function
  42431. ** may return SQLITE_NOMEM.
  42432. */
  42433. if( pPg->flags&PGHDR_DIRTY
  42434. && subjRequiresPage(pPg)
  42435. && SQLITE_OK!=(rc = subjournalPage(pPg))
  42436. ){
  42437. return rc;
  42438. }
  42439. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  42440. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  42441. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  42442. /* If the journal needs to be sync()ed before page pPg->pgno can
  42443. ** be written to, store pPg->pgno in local variable needSyncPgno.
  42444. **
  42445. ** If the isCommit flag is set, there is no need to remember that
  42446. ** the journal needs to be sync()ed before database page pPg->pgno
  42447. ** can be written to. The caller has already promised not to write to it.
  42448. */
  42449. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  42450. needSyncPgno = pPg->pgno;
  42451. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  42452. pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  42453. assert( pPg->flags&PGHDR_DIRTY );
  42454. }
  42455. /* If the cache contains a page with page-number pgno, remove it
  42456. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  42457. ** page pgno before the 'move' operation, it needs to be retained
  42458. ** for the page moved there.
  42459. */
  42460. pPg->flags &= ~PGHDR_NEED_SYNC;
  42461. pPgOld = pager_lookup(pPager, pgno);
  42462. assert( !pPgOld || pPgOld->nRef==1 );
  42463. if( pPgOld ){
  42464. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  42465. if( MEMDB ){
  42466. /* Do not discard pages from an in-memory database since we might
  42467. ** need to rollback later. Just move the page out of the way. */
  42468. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  42469. }else{
  42470. sqlite3PcacheDrop(pPgOld);
  42471. }
  42472. }
  42473. origPgno = pPg->pgno;
  42474. sqlite3PcacheMove(pPg, pgno);
  42475. sqlite3PcacheMakeDirty(pPg);
  42476. /* For an in-memory database, make sure the original page continues
  42477. ** to exist, in case the transaction needs to roll back. Use pPgOld
  42478. ** as the original page since it has already been allocated.
  42479. */
  42480. if( MEMDB ){
  42481. assert( pPgOld );
  42482. sqlite3PcacheMove(pPgOld, origPgno);
  42483. sqlite3PagerUnref(pPgOld);
  42484. }
  42485. if( needSyncPgno ){
  42486. /* If needSyncPgno is non-zero, then the journal file needs to be
  42487. ** sync()ed before any data is written to database file page needSyncPgno.
  42488. ** Currently, no such page exists in the page-cache and the
  42489. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  42490. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  42491. ** flag.
  42492. **
  42493. ** If the attempt to load the page into the page-cache fails, (due
  42494. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  42495. ** array. Otherwise, if the page is loaded and written again in
  42496. ** this transaction, it may be written to the database file before
  42497. ** it is synced into the journal file. This way, it may end up in
  42498. ** the journal file twice, but that is not a problem.
  42499. */
  42500. PgHdr *pPgHdr;
  42501. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  42502. if( rc!=SQLITE_OK ){
  42503. if( needSyncPgno<=pPager->dbOrigSize ){
  42504. assert( pPager->pTmpSpace!=0 );
  42505. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  42506. }
  42507. return rc;
  42508. }
  42509. pPgHdr->flags |= PGHDR_NEED_SYNC;
  42510. sqlite3PcacheMakeDirty(pPgHdr);
  42511. sqlite3PagerUnref(pPgHdr);
  42512. }
  42513. return SQLITE_OK;
  42514. }
  42515. #endif
  42516. /*
  42517. ** Return a pointer to the data for the specified page.
  42518. */
  42519. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  42520. assert( pPg->nRef>0 || pPg->pPager->memDb );
  42521. return pPg->pData;
  42522. }
  42523. /*
  42524. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  42525. ** allocated along with the specified page.
  42526. */
  42527. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  42528. return pPg->pExtra;
  42529. }
  42530. /*
  42531. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  42532. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  42533. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  42534. ** the locking-mode is set to the value specified.
  42535. **
  42536. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  42537. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  42538. ** locking-mode.
  42539. */
  42540. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  42541. assert( eMode==PAGER_LOCKINGMODE_QUERY
  42542. || eMode==PAGER_LOCKINGMODE_NORMAL
  42543. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  42544. assert( PAGER_LOCKINGMODE_QUERY<0 );
  42545. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  42546. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  42547. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  42548. pPager->exclusiveMode = (u8)eMode;
  42549. }
  42550. return (int)pPager->exclusiveMode;
  42551. }
  42552. /*
  42553. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  42554. **
  42555. ** PAGER_JOURNALMODE_DELETE
  42556. ** PAGER_JOURNALMODE_TRUNCATE
  42557. ** PAGER_JOURNALMODE_PERSIST
  42558. ** PAGER_JOURNALMODE_OFF
  42559. ** PAGER_JOURNALMODE_MEMORY
  42560. ** PAGER_JOURNALMODE_WAL
  42561. **
  42562. ** The journalmode is set to the value specified if the change is allowed.
  42563. ** The change may be disallowed for the following reasons:
  42564. **
  42565. ** * An in-memory database can only have its journal_mode set to _OFF
  42566. ** or _MEMORY.
  42567. **
  42568. ** * Temporary databases cannot have _WAL journalmode.
  42569. **
  42570. ** The returned indicate the current (possibly updated) journal-mode.
  42571. */
  42572. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  42573. u8 eOld = pPager->journalMode; /* Prior journalmode */
  42574. #ifdef SQLITE_DEBUG
  42575. /* The print_pager_state() routine is intended to be used by the debugger
  42576. ** only. We invoke it once here to suppress a compiler warning. */
  42577. print_pager_state(pPager);
  42578. #endif
  42579. /* The eMode parameter is always valid */
  42580. assert( eMode==PAGER_JOURNALMODE_DELETE
  42581. || eMode==PAGER_JOURNALMODE_TRUNCATE
  42582. || eMode==PAGER_JOURNALMODE_PERSIST
  42583. || eMode==PAGER_JOURNALMODE_OFF
  42584. || eMode==PAGER_JOURNALMODE_WAL
  42585. || eMode==PAGER_JOURNALMODE_MEMORY );
  42586. /* This routine is only called from the OP_JournalMode opcode, and
  42587. ** the logic there will never allow a temporary file to be changed
  42588. ** to WAL mode.
  42589. */
  42590. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  42591. /* Do allow the journalmode of an in-memory database to be set to
  42592. ** anything other than MEMORY or OFF
  42593. */
  42594. if( MEMDB ){
  42595. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  42596. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  42597. eMode = eOld;
  42598. }
  42599. }
  42600. if( eMode!=eOld ){
  42601. /* Change the journal mode. */
  42602. assert( pPager->eState!=PAGER_ERROR );
  42603. pPager->journalMode = (u8)eMode;
  42604. /* When transistioning from TRUNCATE or PERSIST to any other journal
  42605. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  42606. ** delete the journal file.
  42607. */
  42608. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  42609. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  42610. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  42611. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  42612. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  42613. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  42614. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  42615. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  42616. /* In this case we would like to delete the journal file. If it is
  42617. ** not possible, then that is not a problem. Deleting the journal file
  42618. ** here is an optimization only.
  42619. **
  42620. ** Before deleting the journal file, obtain a RESERVED lock on the
  42621. ** database file. This ensures that the journal file is not deleted
  42622. ** while it is in use by some other client.
  42623. */
  42624. sqlite3OsClose(pPager->jfd);
  42625. if( pPager->eLock>=RESERVED_LOCK ){
  42626. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  42627. }else{
  42628. int rc = SQLITE_OK;
  42629. int state = pPager->eState;
  42630. assert( state==PAGER_OPEN || state==PAGER_READER );
  42631. if( state==PAGER_OPEN ){
  42632. rc = sqlite3PagerSharedLock(pPager);
  42633. }
  42634. if( pPager->eState==PAGER_READER ){
  42635. assert( rc==SQLITE_OK );
  42636. rc = pagerLockDb(pPager, RESERVED_LOCK);
  42637. }
  42638. if( rc==SQLITE_OK ){
  42639. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  42640. }
  42641. if( rc==SQLITE_OK && state==PAGER_READER ){
  42642. pagerUnlockDb(pPager, SHARED_LOCK);
  42643. }else if( state==PAGER_OPEN ){
  42644. pager_unlock(pPager);
  42645. }
  42646. assert( state==pPager->eState );
  42647. }
  42648. }
  42649. }
  42650. /* Return the new journal mode */
  42651. return (int)pPager->journalMode;
  42652. }
  42653. /*
  42654. ** Return the current journal mode.
  42655. */
  42656. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  42657. return (int)pPager->journalMode;
  42658. }
  42659. /*
  42660. ** Return TRUE if the pager is in a state where it is OK to change the
  42661. ** journalmode. Journalmode changes can only happen when the database
  42662. ** is unmodified.
  42663. */
  42664. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  42665. assert( assert_pager_state(pPager) );
  42666. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  42667. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  42668. return 1;
  42669. }
  42670. /*
  42671. ** Get/set the size-limit used for persistent journal files.
  42672. **
  42673. ** Setting the size limit to -1 means no limit is enforced.
  42674. ** An attempt to set a limit smaller than -1 is a no-op.
  42675. */
  42676. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  42677. if( iLimit>=-1 ){
  42678. pPager->journalSizeLimit = iLimit;
  42679. sqlite3WalLimit(pPager->pWal, iLimit);
  42680. }
  42681. return pPager->journalSizeLimit;
  42682. }
  42683. /*
  42684. ** Return a pointer to the pPager->pBackup variable. The backup module
  42685. ** in backup.c maintains the content of this variable. This module
  42686. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  42687. ** sqlite3BackupUpdate() only.
  42688. */
  42689. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  42690. return &pPager->pBackup;
  42691. }
  42692. #ifndef SQLITE_OMIT_VACUUM
  42693. /*
  42694. ** Unless this is an in-memory or temporary database, clear the pager cache.
  42695. */
  42696. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  42697. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  42698. }
  42699. #endif
  42700. #ifndef SQLITE_OMIT_WAL
  42701. /*
  42702. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  42703. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  42704. ** or wal_blocking_checkpoint() API functions.
  42705. **
  42706. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  42707. */
  42708. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  42709. int rc = SQLITE_OK;
  42710. if( pPager->pWal ){
  42711. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  42712. pPager->xBusyHandler, pPager->pBusyHandlerArg,
  42713. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  42714. pnLog, pnCkpt
  42715. );
  42716. }
  42717. return rc;
  42718. }
  42719. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  42720. return sqlite3WalCallback(pPager->pWal);
  42721. }
  42722. /*
  42723. ** Return true if the underlying VFS for the given pager supports the
  42724. ** primitives necessary for write-ahead logging.
  42725. */
  42726. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  42727. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  42728. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  42729. }
  42730. /*
  42731. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  42732. ** is obtained instead, immediately release it.
  42733. */
  42734. static int pagerExclusiveLock(Pager *pPager){
  42735. int rc; /* Return code */
  42736. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  42737. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  42738. if( rc!=SQLITE_OK ){
  42739. /* If the attempt to grab the exclusive lock failed, release the
  42740. ** pending lock that may have been obtained instead. */
  42741. pagerUnlockDb(pPager, SHARED_LOCK);
  42742. }
  42743. return rc;
  42744. }
  42745. /*
  42746. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  42747. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  42748. ** lock on the database file and use heap-memory to store the wal-index
  42749. ** in. Otherwise, use the normal shared-memory.
  42750. */
  42751. static int pagerOpenWal(Pager *pPager){
  42752. int rc = SQLITE_OK;
  42753. assert( pPager->pWal==0 && pPager->tempFile==0 );
  42754. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  42755. /* If the pager is already in exclusive-mode, the WAL module will use
  42756. ** heap-memory for the wal-index instead of the VFS shared-memory
  42757. ** implementation. Take the exclusive lock now, before opening the WAL
  42758. ** file, to make sure this is safe.
  42759. */
  42760. if( pPager->exclusiveMode ){
  42761. rc = pagerExclusiveLock(pPager);
  42762. }
  42763. /* Open the connection to the log file. If this operation fails,
  42764. ** (e.g. due to malloc() failure), return an error code.
  42765. */
  42766. if( rc==SQLITE_OK ){
  42767. rc = sqlite3WalOpen(pPager->pVfs,
  42768. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  42769. pPager->journalSizeLimit, &pPager->pWal
  42770. );
  42771. }
  42772. pagerFixMaplimit(pPager);
  42773. return rc;
  42774. }
  42775. /*
  42776. ** The caller must be holding a SHARED lock on the database file to call
  42777. ** this function.
  42778. **
  42779. ** If the pager passed as the first argument is open on a real database
  42780. ** file (not a temp file or an in-memory database), and the WAL file
  42781. ** is not already open, make an attempt to open it now. If successful,
  42782. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  42783. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  42784. ** not modified in either case.
  42785. **
  42786. ** If the pager is open on a temp-file (or in-memory database), or if
  42787. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  42788. ** without doing anything.
  42789. */
  42790. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  42791. Pager *pPager, /* Pager object */
  42792. int *pbOpen /* OUT: Set to true if call is a no-op */
  42793. ){
  42794. int rc = SQLITE_OK; /* Return code */
  42795. assert( assert_pager_state(pPager) );
  42796. assert( pPager->eState==PAGER_OPEN || pbOpen );
  42797. assert( pPager->eState==PAGER_READER || !pbOpen );
  42798. assert( pbOpen==0 || *pbOpen==0 );
  42799. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  42800. if( !pPager->tempFile && !pPager->pWal ){
  42801. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  42802. /* Close any rollback journal previously open */
  42803. sqlite3OsClose(pPager->jfd);
  42804. rc = pagerOpenWal(pPager);
  42805. if( rc==SQLITE_OK ){
  42806. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  42807. pPager->eState = PAGER_OPEN;
  42808. }
  42809. }else{
  42810. *pbOpen = 1;
  42811. }
  42812. return rc;
  42813. }
  42814. /*
  42815. ** This function is called to close the connection to the log file prior
  42816. ** to switching from WAL to rollback mode.
  42817. **
  42818. ** Before closing the log file, this function attempts to take an
  42819. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  42820. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  42821. ** If successful, the EXCLUSIVE lock is not released before returning.
  42822. */
  42823. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  42824. int rc = SQLITE_OK;
  42825. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  42826. /* If the log file is not already open, but does exist in the file-system,
  42827. ** it may need to be checkpointed before the connection can switch to
  42828. ** rollback mode. Open it now so this can happen.
  42829. */
  42830. if( !pPager->pWal ){
  42831. int logexists = 0;
  42832. rc = pagerLockDb(pPager, SHARED_LOCK);
  42833. if( rc==SQLITE_OK ){
  42834. rc = sqlite3OsAccess(
  42835. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  42836. );
  42837. }
  42838. if( rc==SQLITE_OK && logexists ){
  42839. rc = pagerOpenWal(pPager);
  42840. }
  42841. }
  42842. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  42843. ** the database file, the log and log-summary files will be deleted.
  42844. */
  42845. if( rc==SQLITE_OK && pPager->pWal ){
  42846. rc = pagerExclusiveLock(pPager);
  42847. if( rc==SQLITE_OK ){
  42848. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  42849. pPager->pageSize, (u8*)pPager->pTmpSpace);
  42850. pPager->pWal = 0;
  42851. pagerFixMaplimit(pPager);
  42852. }
  42853. }
  42854. return rc;
  42855. }
  42856. #endif /* !SQLITE_OMIT_WAL */
  42857. #ifdef SQLITE_ENABLE_ZIPVFS
  42858. /*
  42859. ** A read-lock must be held on the pager when this function is called. If
  42860. ** the pager is in WAL mode and the WAL file currently contains one or more
  42861. ** frames, return the size in bytes of the page images stored within the
  42862. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  42863. ** is empty, return 0.
  42864. */
  42865. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  42866. assert( pPager->eState==PAGER_READER );
  42867. return sqlite3WalFramesize(pPager->pWal);
  42868. }
  42869. #endif
  42870. #endif /* SQLITE_OMIT_DISKIO */
  42871. /************** End of pager.c ***********************************************/
  42872. /************** Begin file wal.c *********************************************/
  42873. /*
  42874. ** 2010 February 1
  42875. **
  42876. ** The author disclaims copyright to this source code. In place of
  42877. ** a legal notice, here is a blessing:
  42878. **
  42879. ** May you do good and not evil.
  42880. ** May you find forgiveness for yourself and forgive others.
  42881. ** May you share freely, never taking more than you give.
  42882. **
  42883. *************************************************************************
  42884. **
  42885. ** This file contains the implementation of a write-ahead log (WAL) used in
  42886. ** "journal_mode=WAL" mode.
  42887. **
  42888. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  42889. **
  42890. ** A WAL file consists of a header followed by zero or more "frames".
  42891. ** Each frame records the revised content of a single page from the
  42892. ** database file. All changes to the database are recorded by writing
  42893. ** frames into the WAL. Transactions commit when a frame is written that
  42894. ** contains a commit marker. A single WAL can and usually does record
  42895. ** multiple transactions. Periodically, the content of the WAL is
  42896. ** transferred back into the database file in an operation called a
  42897. ** "checkpoint".
  42898. **
  42899. ** A single WAL file can be used multiple times. In other words, the
  42900. ** WAL can fill up with frames and then be checkpointed and then new
  42901. ** frames can overwrite the old ones. A WAL always grows from beginning
  42902. ** toward the end. Checksums and counters attached to each frame are
  42903. ** used to determine which frames within the WAL are valid and which
  42904. ** are leftovers from prior checkpoints.
  42905. **
  42906. ** The WAL header is 32 bytes in size and consists of the following eight
  42907. ** big-endian 32-bit unsigned integer values:
  42908. **
  42909. ** 0: Magic number. 0x377f0682 or 0x377f0683
  42910. ** 4: File format version. Currently 3007000
  42911. ** 8: Database page size. Example: 1024
  42912. ** 12: Checkpoint sequence number
  42913. ** 16: Salt-1, random integer incremented with each checkpoint
  42914. ** 20: Salt-2, a different random integer changing with each ckpt
  42915. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  42916. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  42917. **
  42918. ** Immediately following the wal-header are zero or more frames. Each
  42919. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  42920. ** of page data. The frame-header is six big-endian 32-bit unsigned
  42921. ** integer values, as follows:
  42922. **
  42923. ** 0: Page number.
  42924. ** 4: For commit records, the size of the database image in pages
  42925. ** after the commit. For all other records, zero.
  42926. ** 8: Salt-1 (copied from the header)
  42927. ** 12: Salt-2 (copied from the header)
  42928. ** 16: Checksum-1.
  42929. ** 20: Checksum-2.
  42930. **
  42931. ** A frame is considered valid if and only if the following conditions are
  42932. ** true:
  42933. **
  42934. ** (1) The salt-1 and salt-2 values in the frame-header match
  42935. ** salt values in the wal-header
  42936. **
  42937. ** (2) The checksum values in the final 8 bytes of the frame-header
  42938. ** exactly match the checksum computed consecutively on the
  42939. ** WAL header and the first 8 bytes and the content of all frames
  42940. ** up to and including the current frame.
  42941. **
  42942. ** The checksum is computed using 32-bit big-endian integers if the
  42943. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  42944. ** is computed using little-endian if the magic number is 0x377f0682.
  42945. ** The checksum values are always stored in the frame header in a
  42946. ** big-endian format regardless of which byte order is used to compute
  42947. ** the checksum. The checksum is computed by interpreting the input as
  42948. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  42949. ** algorithm used for the checksum is as follows:
  42950. **
  42951. ** for i from 0 to n-1 step 2:
  42952. ** s0 += x[i] + s1;
  42953. ** s1 += x[i+1] + s0;
  42954. ** endfor
  42955. **
  42956. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  42957. ** in reverse order (the largest fibonacci weight occurs on the first element
  42958. ** of the sequence being summed.) The s1 value spans all 32-bit
  42959. ** terms of the sequence whereas s0 omits the final term.
  42960. **
  42961. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  42962. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  42963. ** The VFS.xSync operations serve as write barriers - all writes launched
  42964. ** before the xSync must complete before any write that launches after the
  42965. ** xSync begins.
  42966. **
  42967. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  42968. ** value is randomized. This prevents old and new frames in the WAL from
  42969. ** being considered valid at the same time and being checkpointing together
  42970. ** following a crash.
  42971. **
  42972. ** READER ALGORITHM
  42973. **
  42974. ** To read a page from the database (call it page number P), a reader
  42975. ** first checks the WAL to see if it contains page P. If so, then the
  42976. ** last valid instance of page P that is a followed by a commit frame
  42977. ** or is a commit frame itself becomes the value read. If the WAL
  42978. ** contains no copies of page P that are valid and which are a commit
  42979. ** frame or are followed by a commit frame, then page P is read from
  42980. ** the database file.
  42981. **
  42982. ** To start a read transaction, the reader records the index of the last
  42983. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  42984. ** for all subsequent read operations. New transactions can be appended
  42985. ** to the WAL, but as long as the reader uses its original mxFrame value
  42986. ** and ignores the newly appended content, it will see a consistent snapshot
  42987. ** of the database from a single point in time. This technique allows
  42988. ** multiple concurrent readers to view different versions of the database
  42989. ** content simultaneously.
  42990. **
  42991. ** The reader algorithm in the previous paragraphs works correctly, but
  42992. ** because frames for page P can appear anywhere within the WAL, the
  42993. ** reader has to scan the entire WAL looking for page P frames. If the
  42994. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  42995. ** and read performance suffers. To overcome this problem, a separate
  42996. ** data structure called the wal-index is maintained to expedite the
  42997. ** search for frames of a particular page.
  42998. **
  42999. ** WAL-INDEX FORMAT
  43000. **
  43001. ** Conceptually, the wal-index is shared memory, though VFS implementations
  43002. ** might choose to implement the wal-index using a mmapped file. Because
  43003. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  43004. ** on a network filesystem. All users of the database must be able to
  43005. ** share memory.
  43006. **
  43007. ** The wal-index is transient. After a crash, the wal-index can (and should
  43008. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  43009. ** to either truncate or zero the header of the wal-index when the last
  43010. ** connection to it closes. Because the wal-index is transient, it can
  43011. ** use an architecture-specific format; it does not have to be cross-platform.
  43012. ** Hence, unlike the database and WAL file formats which store all values
  43013. ** as big endian, the wal-index can store multi-byte values in the native
  43014. ** byte order of the host computer.
  43015. **
  43016. ** The purpose of the wal-index is to answer this question quickly: Given
  43017. ** a page number P and a maximum frame index M, return the index of the
  43018. ** last frame in the wal before frame M for page P in the WAL, or return
  43019. ** NULL if there are no frames for page P in the WAL prior to M.
  43020. **
  43021. ** The wal-index consists of a header region, followed by an one or
  43022. ** more index blocks.
  43023. **
  43024. ** The wal-index header contains the total number of frames within the WAL
  43025. ** in the mxFrame field.
  43026. **
  43027. ** Each index block except for the first contains information on
  43028. ** HASHTABLE_NPAGE frames. The first index block contains information on
  43029. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  43030. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  43031. ** first index block are the same size as all other index blocks in the
  43032. ** wal-index.
  43033. **
  43034. ** Each index block contains two sections, a page-mapping that contains the
  43035. ** database page number associated with each wal frame, and a hash-table
  43036. ** that allows readers to query an index block for a specific page number.
  43037. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  43038. ** for the first index block) 32-bit page numbers. The first entry in the
  43039. ** first index-block contains the database page number corresponding to the
  43040. ** first frame in the WAL file. The first entry in the second index block
  43041. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  43042. ** the log, and so on.
  43043. **
  43044. ** The last index block in a wal-index usually contains less than the full
  43045. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  43046. ** depending on the contents of the WAL file. This does not change the
  43047. ** allocated size of the page-mapping array - the page-mapping array merely
  43048. ** contains unused entries.
  43049. **
  43050. ** Even without using the hash table, the last frame for page P
  43051. ** can be found by scanning the page-mapping sections of each index block
  43052. ** starting with the last index block and moving toward the first, and
  43053. ** within each index block, starting at the end and moving toward the
  43054. ** beginning. The first entry that equals P corresponds to the frame
  43055. ** holding the content for that page.
  43056. **
  43057. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  43058. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  43059. ** hash table for each page number in the mapping section, so the hash
  43060. ** table is never more than half full. The expected number of collisions
  43061. ** prior to finding a match is 1. Each entry of the hash table is an
  43062. ** 1-based index of an entry in the mapping section of the same
  43063. ** index block. Let K be the 1-based index of the largest entry in
  43064. ** the mapping section. (For index blocks other than the last, K will
  43065. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  43066. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  43067. ** contain a value of 0.
  43068. **
  43069. ** To look for page P in the hash table, first compute a hash iKey on
  43070. ** P as follows:
  43071. **
  43072. ** iKey = (P * 383) % HASHTABLE_NSLOT
  43073. **
  43074. ** Then start scanning entries of the hash table, starting with iKey
  43075. ** (wrapping around to the beginning when the end of the hash table is
  43076. ** reached) until an unused hash slot is found. Let the first unused slot
  43077. ** be at index iUnused. (iUnused might be less than iKey if there was
  43078. ** wrap-around.) Because the hash table is never more than half full,
  43079. ** the search is guaranteed to eventually hit an unused entry. Let
  43080. ** iMax be the value between iKey and iUnused, closest to iUnused,
  43081. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  43082. ** no hash slot such that aHash[i]==p) then page P is not in the
  43083. ** current index block. Otherwise the iMax-th mapping entry of the
  43084. ** current index block corresponds to the last entry that references
  43085. ** page P.
  43086. **
  43087. ** A hash search begins with the last index block and moves toward the
  43088. ** first index block, looking for entries corresponding to page P. On
  43089. ** average, only two or three slots in each index block need to be
  43090. ** examined in order to either find the last entry for page P, or to
  43091. ** establish that no such entry exists in the block. Each index block
  43092. ** holds over 4000 entries. So two or three index blocks are sufficient
  43093. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  43094. ** comparisons (on average) suffice to either locate a frame in the
  43095. ** WAL or to establish that the frame does not exist in the WAL. This
  43096. ** is much faster than scanning the entire 10MB WAL.
  43097. **
  43098. ** Note that entries are added in order of increasing K. Hence, one
  43099. ** reader might be using some value K0 and a second reader that started
  43100. ** at a later time (after additional transactions were added to the WAL
  43101. ** and to the wal-index) might be using a different value K1, where K1>K0.
  43102. ** Both readers can use the same hash table and mapping section to get
  43103. ** the correct result. There may be entries in the hash table with
  43104. ** K>K0 but to the first reader, those entries will appear to be unused
  43105. ** slots in the hash table and so the first reader will get an answer as
  43106. ** if no values greater than K0 had ever been inserted into the hash table
  43107. ** in the first place - which is what reader one wants. Meanwhile, the
  43108. ** second reader using K1 will see additional values that were inserted
  43109. ** later, which is exactly what reader two wants.
  43110. **
  43111. ** When a rollback occurs, the value of K is decreased. Hash table entries
  43112. ** that correspond to frames greater than the new K value are removed
  43113. ** from the hash table at this point.
  43114. */
  43115. #ifndef SQLITE_OMIT_WAL
  43116. /*
  43117. ** Trace output macros
  43118. */
  43119. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  43120. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  43121. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  43122. #else
  43123. # define WALTRACE(X)
  43124. #endif
  43125. /*
  43126. ** The maximum (and only) versions of the wal and wal-index formats
  43127. ** that may be interpreted by this version of SQLite.
  43128. **
  43129. ** If a client begins recovering a WAL file and finds that (a) the checksum
  43130. ** values in the wal-header are correct and (b) the version field is not
  43131. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  43132. **
  43133. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  43134. ** checksum test is successful) and finds that the version field is not
  43135. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  43136. ** returns SQLITE_CANTOPEN.
  43137. */
  43138. #define WAL_MAX_VERSION 3007000
  43139. #define WALINDEX_MAX_VERSION 3007000
  43140. /*
  43141. ** Indices of various locking bytes. WAL_NREADER is the number
  43142. ** of available reader locks and should be at least 3.
  43143. */
  43144. #define WAL_WRITE_LOCK 0
  43145. #define WAL_ALL_BUT_WRITE 1
  43146. #define WAL_CKPT_LOCK 1
  43147. #define WAL_RECOVER_LOCK 2
  43148. #define WAL_READ_LOCK(I) (3+(I))
  43149. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  43150. /* Object declarations */
  43151. typedef struct WalIndexHdr WalIndexHdr;
  43152. typedef struct WalIterator WalIterator;
  43153. typedef struct WalCkptInfo WalCkptInfo;
  43154. /*
  43155. ** The following object holds a copy of the wal-index header content.
  43156. **
  43157. ** The actual header in the wal-index consists of two copies of this
  43158. ** object.
  43159. **
  43160. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  43161. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  43162. ** added in 3.7.1 when support for 64K pages was added.
  43163. */
  43164. struct WalIndexHdr {
  43165. u32 iVersion; /* Wal-index version */
  43166. u32 unused; /* Unused (padding) field */
  43167. u32 iChange; /* Counter incremented each transaction */
  43168. u8 isInit; /* 1 when initialized */
  43169. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  43170. u16 szPage; /* Database page size in bytes. 1==64K */
  43171. u32 mxFrame; /* Index of last valid frame in the WAL */
  43172. u32 nPage; /* Size of database in pages */
  43173. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  43174. u32 aSalt[2]; /* Two salt values copied from WAL header */
  43175. u32 aCksum[2]; /* Checksum over all prior fields */
  43176. };
  43177. /*
  43178. ** A copy of the following object occurs in the wal-index immediately
  43179. ** following the second copy of the WalIndexHdr. This object stores
  43180. ** information used by checkpoint.
  43181. **
  43182. ** nBackfill is the number of frames in the WAL that have been written
  43183. ** back into the database. (We call the act of moving content from WAL to
  43184. ** database "backfilling".) The nBackfill number is never greater than
  43185. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  43186. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  43187. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  43188. ** mxFrame back to zero when the WAL is reset.
  43189. **
  43190. ** There is one entry in aReadMark[] for each reader lock. If a reader
  43191. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  43192. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  43193. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  43194. ** a special case; its value is never used and it exists as a place-holder
  43195. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  43196. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  43197. ** directly from the database.
  43198. **
  43199. ** The value of aReadMark[K] may only be changed by a thread that
  43200. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  43201. ** aReadMark[K] cannot changed while there is a reader is using that mark
  43202. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  43203. **
  43204. ** The checkpointer may only transfer frames from WAL to database where
  43205. ** the frame numbers are less than or equal to every aReadMark[] that is
  43206. ** in use (that is, every aReadMark[j] for which there is a corresponding
  43207. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  43208. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  43209. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  43210. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  43211. ** in the WAL has been backfilled into the database) then new readers
  43212. ** will choose aReadMark[0] which has value 0 and hence such reader will
  43213. ** get all their all content directly from the database file and ignore
  43214. ** the WAL.
  43215. **
  43216. ** Writers normally append new frames to the end of the WAL. However,
  43217. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  43218. ** written back into the database) and if no readers are using the WAL
  43219. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  43220. ** the writer will first "reset" the WAL back to the beginning and start
  43221. ** writing new content beginning at frame 1.
  43222. **
  43223. ** We assume that 32-bit loads are atomic and so no locks are needed in
  43224. ** order to read from any aReadMark[] entries.
  43225. */
  43226. struct WalCkptInfo {
  43227. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  43228. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  43229. };
  43230. #define READMARK_NOT_USED 0xffffffff
  43231. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  43232. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  43233. ** only support mandatory file-locks, we do not read or write data
  43234. ** from the region of the file on which locks are applied.
  43235. */
  43236. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  43237. #define WALINDEX_LOCK_RESERVED 16
  43238. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  43239. /* Size of header before each frame in wal */
  43240. #define WAL_FRAME_HDRSIZE 24
  43241. /* Size of write ahead log header, including checksum. */
  43242. /* #define WAL_HDRSIZE 24 */
  43243. #define WAL_HDRSIZE 32
  43244. /* WAL magic value. Either this value, or the same value with the least
  43245. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  43246. ** big-endian format in the first 4 bytes of a WAL file.
  43247. **
  43248. ** If the LSB is set, then the checksums for each frame within the WAL
  43249. ** file are calculated by treating all data as an array of 32-bit
  43250. ** big-endian words. Otherwise, they are calculated by interpreting
  43251. ** all data as 32-bit little-endian words.
  43252. */
  43253. #define WAL_MAGIC 0x377f0682
  43254. /*
  43255. ** Return the offset of frame iFrame in the write-ahead log file,
  43256. ** assuming a database page size of szPage bytes. The offset returned
  43257. ** is to the start of the write-ahead log frame-header.
  43258. */
  43259. #define walFrameOffset(iFrame, szPage) ( \
  43260. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  43261. )
  43262. /*
  43263. ** An open write-ahead log file is represented by an instance of the
  43264. ** following object.
  43265. */
  43266. struct Wal {
  43267. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  43268. sqlite3_file *pDbFd; /* File handle for the database file */
  43269. sqlite3_file *pWalFd; /* File handle for WAL file */
  43270. u32 iCallback; /* Value to pass to log callback (or 0) */
  43271. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  43272. int nWiData; /* Size of array apWiData */
  43273. int szFirstBlock; /* Size of first block written to WAL file */
  43274. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  43275. u32 szPage; /* Database page size */
  43276. i16 readLock; /* Which read lock is being held. -1 for none */
  43277. u8 syncFlags; /* Flags to use to sync header writes */
  43278. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  43279. u8 writeLock; /* True if in a write transaction */
  43280. u8 ckptLock; /* True if holding a checkpoint lock */
  43281. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  43282. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  43283. u8 syncHeader; /* Fsync the WAL header if true */
  43284. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  43285. WalIndexHdr hdr; /* Wal-index header for current transaction */
  43286. const char *zWalName; /* Name of WAL file */
  43287. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  43288. #ifdef SQLITE_DEBUG
  43289. u8 lockError; /* True if a locking error has occurred */
  43290. #endif
  43291. };
  43292. /*
  43293. ** Candidate values for Wal.exclusiveMode.
  43294. */
  43295. #define WAL_NORMAL_MODE 0
  43296. #define WAL_EXCLUSIVE_MODE 1
  43297. #define WAL_HEAPMEMORY_MODE 2
  43298. /*
  43299. ** Possible values for WAL.readOnly
  43300. */
  43301. #define WAL_RDWR 0 /* Normal read/write connection */
  43302. #define WAL_RDONLY 1 /* The WAL file is readonly */
  43303. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  43304. /*
  43305. ** Each page of the wal-index mapping contains a hash-table made up of
  43306. ** an array of HASHTABLE_NSLOT elements of the following type.
  43307. */
  43308. typedef u16 ht_slot;
  43309. /*
  43310. ** This structure is used to implement an iterator that loops through
  43311. ** all frames in the WAL in database page order. Where two or more frames
  43312. ** correspond to the same database page, the iterator visits only the
  43313. ** frame most recently written to the WAL (in other words, the frame with
  43314. ** the largest index).
  43315. **
  43316. ** The internals of this structure are only accessed by:
  43317. **
  43318. ** walIteratorInit() - Create a new iterator,
  43319. ** walIteratorNext() - Step an iterator,
  43320. ** walIteratorFree() - Free an iterator.
  43321. **
  43322. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  43323. */
  43324. struct WalIterator {
  43325. int iPrior; /* Last result returned from the iterator */
  43326. int nSegment; /* Number of entries in aSegment[] */
  43327. struct WalSegment {
  43328. int iNext; /* Next slot in aIndex[] not yet returned */
  43329. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  43330. u32 *aPgno; /* Array of page numbers. */
  43331. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  43332. int iZero; /* Frame number associated with aPgno[0] */
  43333. } aSegment[1]; /* One for every 32KB page in the wal-index */
  43334. };
  43335. /*
  43336. ** Define the parameters of the hash tables in the wal-index file. There
  43337. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  43338. ** wal-index.
  43339. **
  43340. ** Changing any of these constants will alter the wal-index format and
  43341. ** create incompatibilities.
  43342. */
  43343. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  43344. #define HASHTABLE_HASH_1 383 /* Should be prime */
  43345. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  43346. /*
  43347. ** The block of page numbers associated with the first hash-table in a
  43348. ** wal-index is smaller than usual. This is so that there is a complete
  43349. ** hash-table on each aligned 32KB page of the wal-index.
  43350. */
  43351. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  43352. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  43353. #define WALINDEX_PGSZ ( \
  43354. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  43355. )
  43356. /*
  43357. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  43358. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  43359. ** numbered from zero.
  43360. **
  43361. ** If this call is successful, *ppPage is set to point to the wal-index
  43362. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  43363. ** then an SQLite error code is returned and *ppPage is set to 0.
  43364. */
  43365. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  43366. int rc = SQLITE_OK;
  43367. /* Enlarge the pWal->apWiData[] array if required */
  43368. if( pWal->nWiData<=iPage ){
  43369. int nByte = sizeof(u32*)*(iPage+1);
  43370. volatile u32 **apNew;
  43371. apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
  43372. if( !apNew ){
  43373. *ppPage = 0;
  43374. return SQLITE_NOMEM;
  43375. }
  43376. memset((void*)&apNew[pWal->nWiData], 0,
  43377. sizeof(u32*)*(iPage+1-pWal->nWiData));
  43378. pWal->apWiData = apNew;
  43379. pWal->nWiData = iPage+1;
  43380. }
  43381. /* Request a pointer to the required page from the VFS */
  43382. if( pWal->apWiData[iPage]==0 ){
  43383. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  43384. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  43385. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  43386. }else{
  43387. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  43388. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  43389. );
  43390. if( rc==SQLITE_READONLY ){
  43391. pWal->readOnly |= WAL_SHM_RDONLY;
  43392. rc = SQLITE_OK;
  43393. }
  43394. }
  43395. }
  43396. *ppPage = pWal->apWiData[iPage];
  43397. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  43398. return rc;
  43399. }
  43400. /*
  43401. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  43402. */
  43403. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  43404. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  43405. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  43406. }
  43407. /*
  43408. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  43409. */
  43410. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  43411. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  43412. return (volatile WalIndexHdr*)pWal->apWiData[0];
  43413. }
  43414. /*
  43415. ** The argument to this macro must be of type u32. On a little-endian
  43416. ** architecture, it returns the u32 value that results from interpreting
  43417. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  43418. ** returns the value that would be produced by intepreting the 4 bytes
  43419. ** of the input value as a little-endian integer.
  43420. */
  43421. #define BYTESWAP32(x) ( \
  43422. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  43423. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  43424. )
  43425. /*
  43426. ** Generate or extend an 8 byte checksum based on the data in
  43427. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  43428. ** initial values of 0 and 0 if aIn==NULL).
  43429. **
  43430. ** The checksum is written back into aOut[] before returning.
  43431. **
  43432. ** nByte must be a positive multiple of 8.
  43433. */
  43434. static void walChecksumBytes(
  43435. int nativeCksum, /* True for native byte-order, false for non-native */
  43436. u8 *a, /* Content to be checksummed */
  43437. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  43438. const u32 *aIn, /* Initial checksum value input */
  43439. u32 *aOut /* OUT: Final checksum value output */
  43440. ){
  43441. u32 s1, s2;
  43442. u32 *aData = (u32 *)a;
  43443. u32 *aEnd = (u32 *)&a[nByte];
  43444. if( aIn ){
  43445. s1 = aIn[0];
  43446. s2 = aIn[1];
  43447. }else{
  43448. s1 = s2 = 0;
  43449. }
  43450. assert( nByte>=8 );
  43451. assert( (nByte&0x00000007)==0 );
  43452. if( nativeCksum ){
  43453. do {
  43454. s1 += *aData++ + s2;
  43455. s2 += *aData++ + s1;
  43456. }while( aData<aEnd );
  43457. }else{
  43458. do {
  43459. s1 += BYTESWAP32(aData[0]) + s2;
  43460. s2 += BYTESWAP32(aData[1]) + s1;
  43461. aData += 2;
  43462. }while( aData<aEnd );
  43463. }
  43464. aOut[0] = s1;
  43465. aOut[1] = s2;
  43466. }
  43467. static void walShmBarrier(Wal *pWal){
  43468. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  43469. sqlite3OsShmBarrier(pWal->pDbFd);
  43470. }
  43471. }
  43472. /*
  43473. ** Write the header information in pWal->hdr into the wal-index.
  43474. **
  43475. ** The checksum on pWal->hdr is updated before it is written.
  43476. */
  43477. static void walIndexWriteHdr(Wal *pWal){
  43478. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  43479. const int nCksum = offsetof(WalIndexHdr, aCksum);
  43480. assert( pWal->writeLock );
  43481. pWal->hdr.isInit = 1;
  43482. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  43483. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  43484. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  43485. walShmBarrier(pWal);
  43486. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  43487. }
  43488. /*
  43489. ** This function encodes a single frame header and writes it to a buffer
  43490. ** supplied by the caller. A frame-header is made up of a series of
  43491. ** 4-byte big-endian integers, as follows:
  43492. **
  43493. ** 0: Page number.
  43494. ** 4: For commit records, the size of the database image in pages
  43495. ** after the commit. For all other records, zero.
  43496. ** 8: Salt-1 (copied from the wal-header)
  43497. ** 12: Salt-2 (copied from the wal-header)
  43498. ** 16: Checksum-1.
  43499. ** 20: Checksum-2.
  43500. */
  43501. static void walEncodeFrame(
  43502. Wal *pWal, /* The write-ahead log */
  43503. u32 iPage, /* Database page number for frame */
  43504. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  43505. u8 *aData, /* Pointer to page data */
  43506. u8 *aFrame /* OUT: Write encoded frame here */
  43507. ){
  43508. int nativeCksum; /* True for native byte-order checksums */
  43509. u32 *aCksum = pWal->hdr.aFrameCksum;
  43510. assert( WAL_FRAME_HDRSIZE==24 );
  43511. sqlite3Put4byte(&aFrame[0], iPage);
  43512. sqlite3Put4byte(&aFrame[4], nTruncate);
  43513. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  43514. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  43515. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  43516. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  43517. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  43518. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  43519. }
  43520. /*
  43521. ** Check to see if the frame with header in aFrame[] and content
  43522. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  43523. ** *pnTruncate and return true. Return if the frame is not valid.
  43524. */
  43525. static int walDecodeFrame(
  43526. Wal *pWal, /* The write-ahead log */
  43527. u32 *piPage, /* OUT: Database page number for frame */
  43528. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  43529. u8 *aData, /* Pointer to page data (for checksum) */
  43530. u8 *aFrame /* Frame data */
  43531. ){
  43532. int nativeCksum; /* True for native byte-order checksums */
  43533. u32 *aCksum = pWal->hdr.aFrameCksum;
  43534. u32 pgno; /* Page number of the frame */
  43535. assert( WAL_FRAME_HDRSIZE==24 );
  43536. /* A frame is only valid if the salt values in the frame-header
  43537. ** match the salt values in the wal-header.
  43538. */
  43539. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  43540. return 0;
  43541. }
  43542. /* A frame is only valid if the page number is creater than zero.
  43543. */
  43544. pgno = sqlite3Get4byte(&aFrame[0]);
  43545. if( pgno==0 ){
  43546. return 0;
  43547. }
  43548. /* A frame is only valid if a checksum of the WAL header,
  43549. ** all prior frams, the first 16 bytes of this frame-header,
  43550. ** and the frame-data matches the checksum in the last 8
  43551. ** bytes of this frame-header.
  43552. */
  43553. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  43554. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  43555. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  43556. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  43557. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  43558. ){
  43559. /* Checksum failed. */
  43560. return 0;
  43561. }
  43562. /* If we reach this point, the frame is valid. Return the page number
  43563. ** and the new database size.
  43564. */
  43565. *piPage = pgno;
  43566. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  43567. return 1;
  43568. }
  43569. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  43570. /*
  43571. ** Names of locks. This routine is used to provide debugging output and is not
  43572. ** a part of an ordinary build.
  43573. */
  43574. static const char *walLockName(int lockIdx){
  43575. if( lockIdx==WAL_WRITE_LOCK ){
  43576. return "WRITE-LOCK";
  43577. }else if( lockIdx==WAL_CKPT_LOCK ){
  43578. return "CKPT-LOCK";
  43579. }else if( lockIdx==WAL_RECOVER_LOCK ){
  43580. return "RECOVER-LOCK";
  43581. }else{
  43582. static char zName[15];
  43583. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  43584. lockIdx-WAL_READ_LOCK(0));
  43585. return zName;
  43586. }
  43587. }
  43588. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  43589. /*
  43590. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  43591. ** A lock cannot be moved directly between shared and exclusive - it must go
  43592. ** through the unlocked state first.
  43593. **
  43594. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  43595. */
  43596. static int walLockShared(Wal *pWal, int lockIdx){
  43597. int rc;
  43598. if( pWal->exclusiveMode ) return SQLITE_OK;
  43599. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  43600. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  43601. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  43602. walLockName(lockIdx), rc ? "failed" : "ok"));
  43603. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  43604. return rc;
  43605. }
  43606. static void walUnlockShared(Wal *pWal, int lockIdx){
  43607. if( pWal->exclusiveMode ) return;
  43608. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  43609. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  43610. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  43611. }
  43612. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  43613. int rc;
  43614. if( pWal->exclusiveMode ) return SQLITE_OK;
  43615. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  43616. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  43617. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  43618. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  43619. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  43620. return rc;
  43621. }
  43622. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  43623. if( pWal->exclusiveMode ) return;
  43624. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  43625. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  43626. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  43627. walLockName(lockIdx), n));
  43628. }
  43629. /*
  43630. ** Compute a hash on a page number. The resulting hash value must land
  43631. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  43632. ** the hash to the next value in the event of a collision.
  43633. */
  43634. static int walHash(u32 iPage){
  43635. assert( iPage>0 );
  43636. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  43637. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  43638. }
  43639. static int walNextHash(int iPriorHash){
  43640. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  43641. }
  43642. /*
  43643. ** Return pointers to the hash table and page number array stored on
  43644. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  43645. ** numbered starting from 0.
  43646. **
  43647. ** Set output variable *paHash to point to the start of the hash table
  43648. ** in the wal-index file. Set *piZero to one less than the frame
  43649. ** number of the first frame indexed by this hash table. If a
  43650. ** slot in the hash table is set to N, it refers to frame number
  43651. ** (*piZero+N) in the log.
  43652. **
  43653. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  43654. ** first frame indexed by the hash table, frame (*piZero+1).
  43655. */
  43656. static int walHashGet(
  43657. Wal *pWal, /* WAL handle */
  43658. int iHash, /* Find the iHash'th table */
  43659. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  43660. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  43661. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  43662. ){
  43663. int rc; /* Return code */
  43664. volatile u32 *aPgno;
  43665. rc = walIndexPage(pWal, iHash, &aPgno);
  43666. assert( rc==SQLITE_OK || iHash>0 );
  43667. if( rc==SQLITE_OK ){
  43668. u32 iZero;
  43669. volatile ht_slot *aHash;
  43670. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  43671. if( iHash==0 ){
  43672. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  43673. iZero = 0;
  43674. }else{
  43675. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  43676. }
  43677. *paPgno = &aPgno[-1];
  43678. *paHash = aHash;
  43679. *piZero = iZero;
  43680. }
  43681. return rc;
  43682. }
  43683. /*
  43684. ** Return the number of the wal-index page that contains the hash-table
  43685. ** and page-number array that contain entries corresponding to WAL frame
  43686. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  43687. ** are numbered starting from 0.
  43688. */
  43689. static int walFramePage(u32 iFrame){
  43690. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  43691. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  43692. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  43693. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  43694. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  43695. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  43696. );
  43697. return iHash;
  43698. }
  43699. /*
  43700. ** Return the page number associated with frame iFrame in this WAL.
  43701. */
  43702. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  43703. int iHash = walFramePage(iFrame);
  43704. if( iHash==0 ){
  43705. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  43706. }
  43707. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  43708. }
  43709. /*
  43710. ** Remove entries from the hash table that point to WAL slots greater
  43711. ** than pWal->hdr.mxFrame.
  43712. **
  43713. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  43714. ** to a rollback or savepoint.
  43715. **
  43716. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  43717. ** updated. Any later hash tables will be automatically cleared when
  43718. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  43719. ** actually needed.
  43720. */
  43721. static void walCleanupHash(Wal *pWal){
  43722. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  43723. volatile u32 *aPgno = 0; /* Page number array for hash table */
  43724. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  43725. int iLimit = 0; /* Zero values greater than this */
  43726. int nByte; /* Number of bytes to zero in aPgno[] */
  43727. int i; /* Used to iterate through aHash[] */
  43728. assert( pWal->writeLock );
  43729. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  43730. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  43731. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  43732. if( pWal->hdr.mxFrame==0 ) return;
  43733. /* Obtain pointers to the hash-table and page-number array containing
  43734. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  43735. ** that the page said hash-table and array reside on is already mapped.
  43736. */
  43737. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  43738. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  43739. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  43740. /* Zero all hash-table entries that correspond to frame numbers greater
  43741. ** than pWal->hdr.mxFrame.
  43742. */
  43743. iLimit = pWal->hdr.mxFrame - iZero;
  43744. assert( iLimit>0 );
  43745. for(i=0; i<HASHTABLE_NSLOT; i++){
  43746. if( aHash[i]>iLimit ){
  43747. aHash[i] = 0;
  43748. }
  43749. }
  43750. /* Zero the entries in the aPgno array that correspond to frames with
  43751. ** frame numbers greater than pWal->hdr.mxFrame.
  43752. */
  43753. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  43754. memset((void *)&aPgno[iLimit+1], 0, nByte);
  43755. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  43756. /* Verify that the every entry in the mapping region is still reachable
  43757. ** via the hash table even after the cleanup.
  43758. */
  43759. if( iLimit ){
  43760. int i; /* Loop counter */
  43761. int iKey; /* Hash key */
  43762. for(i=1; i<=iLimit; i++){
  43763. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  43764. if( aHash[iKey]==i ) break;
  43765. }
  43766. assert( aHash[iKey]==i );
  43767. }
  43768. }
  43769. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  43770. }
  43771. /*
  43772. ** Set an entry in the wal-index that will map database page number
  43773. ** pPage into WAL frame iFrame.
  43774. */
  43775. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  43776. int rc; /* Return code */
  43777. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  43778. volatile u32 *aPgno = 0; /* Page number array */
  43779. volatile ht_slot *aHash = 0; /* Hash table */
  43780. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  43781. /* Assuming the wal-index file was successfully mapped, populate the
  43782. ** page number array and hash table entry.
  43783. */
  43784. if( rc==SQLITE_OK ){
  43785. int iKey; /* Hash table key */
  43786. int idx; /* Value to write to hash-table slot */
  43787. int nCollide; /* Number of hash collisions */
  43788. idx = iFrame - iZero;
  43789. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  43790. /* If this is the first entry to be added to this hash-table, zero the
  43791. ** entire hash table and aPgno[] array before proceding.
  43792. */
  43793. if( idx==1 ){
  43794. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  43795. memset((void*)&aPgno[1], 0, nByte);
  43796. }
  43797. /* If the entry in aPgno[] is already set, then the previous writer
  43798. ** must have exited unexpectedly in the middle of a transaction (after
  43799. ** writing one or more dirty pages to the WAL to free up memory).
  43800. ** Remove the remnants of that writers uncommitted transaction from
  43801. ** the hash-table before writing any new entries.
  43802. */
  43803. if( aPgno[idx] ){
  43804. walCleanupHash(pWal);
  43805. assert( !aPgno[idx] );
  43806. }
  43807. /* Write the aPgno[] array entry and the hash-table slot. */
  43808. nCollide = idx;
  43809. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  43810. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  43811. }
  43812. aPgno[idx] = iPage;
  43813. aHash[iKey] = (ht_slot)idx;
  43814. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  43815. /* Verify that the number of entries in the hash table exactly equals
  43816. ** the number of entries in the mapping region.
  43817. */
  43818. {
  43819. int i; /* Loop counter */
  43820. int nEntry = 0; /* Number of entries in the hash table */
  43821. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  43822. assert( nEntry==idx );
  43823. }
  43824. /* Verify that the every entry in the mapping region is reachable
  43825. ** via the hash table. This turns out to be a really, really expensive
  43826. ** thing to check, so only do this occasionally - not on every
  43827. ** iteration.
  43828. */
  43829. if( (idx&0x3ff)==0 ){
  43830. int i; /* Loop counter */
  43831. for(i=1; i<=idx; i++){
  43832. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  43833. if( aHash[iKey]==i ) break;
  43834. }
  43835. assert( aHash[iKey]==i );
  43836. }
  43837. }
  43838. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  43839. }
  43840. return rc;
  43841. }
  43842. /*
  43843. ** Recover the wal-index by reading the write-ahead log file.
  43844. **
  43845. ** This routine first tries to establish an exclusive lock on the
  43846. ** wal-index to prevent other threads/processes from doing anything
  43847. ** with the WAL or wal-index while recovery is running. The
  43848. ** WAL_RECOVER_LOCK is also held so that other threads will know
  43849. ** that this thread is running recovery. If unable to establish
  43850. ** the necessary locks, this routine returns SQLITE_BUSY.
  43851. */
  43852. static int walIndexRecover(Wal *pWal){
  43853. int rc; /* Return Code */
  43854. i64 nSize; /* Size of log file */
  43855. u32 aFrameCksum[2] = {0, 0};
  43856. int iLock; /* Lock offset to lock for checkpoint */
  43857. int nLock; /* Number of locks to hold */
  43858. /* Obtain an exclusive lock on all byte in the locking range not already
  43859. ** locked by the caller. The caller is guaranteed to have locked the
  43860. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  43861. ** If successful, the same bytes that are locked here are unlocked before
  43862. ** this function returns.
  43863. */
  43864. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  43865. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  43866. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  43867. assert( pWal->writeLock );
  43868. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  43869. nLock = SQLITE_SHM_NLOCK - iLock;
  43870. rc = walLockExclusive(pWal, iLock, nLock);
  43871. if( rc ){
  43872. return rc;
  43873. }
  43874. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  43875. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  43876. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  43877. if( rc!=SQLITE_OK ){
  43878. goto recovery_error;
  43879. }
  43880. if( nSize>WAL_HDRSIZE ){
  43881. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  43882. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  43883. int szFrame; /* Number of bytes in buffer aFrame[] */
  43884. u8 *aData; /* Pointer to data part of aFrame buffer */
  43885. int iFrame; /* Index of last frame read */
  43886. i64 iOffset; /* Next offset to read from log file */
  43887. int szPage; /* Page size according to the log */
  43888. u32 magic; /* Magic value read from WAL header */
  43889. u32 version; /* Magic value read from WAL header */
  43890. int isValid; /* True if this frame is valid */
  43891. /* Read in the WAL header. */
  43892. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  43893. if( rc!=SQLITE_OK ){
  43894. goto recovery_error;
  43895. }
  43896. /* If the database page size is not a power of two, or is greater than
  43897. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  43898. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  43899. ** WAL file.
  43900. */
  43901. magic = sqlite3Get4byte(&aBuf[0]);
  43902. szPage = sqlite3Get4byte(&aBuf[8]);
  43903. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  43904. || szPage&(szPage-1)
  43905. || szPage>SQLITE_MAX_PAGE_SIZE
  43906. || szPage<512
  43907. ){
  43908. goto finished;
  43909. }
  43910. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  43911. pWal->szPage = szPage;
  43912. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  43913. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  43914. /* Verify that the WAL header checksum is correct */
  43915. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  43916. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  43917. );
  43918. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  43919. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  43920. ){
  43921. goto finished;
  43922. }
  43923. /* Verify that the version number on the WAL format is one that
  43924. ** are able to understand */
  43925. version = sqlite3Get4byte(&aBuf[4]);
  43926. if( version!=WAL_MAX_VERSION ){
  43927. rc = SQLITE_CANTOPEN_BKPT;
  43928. goto finished;
  43929. }
  43930. /* Malloc a buffer to read frames into. */
  43931. szFrame = szPage + WAL_FRAME_HDRSIZE;
  43932. aFrame = (u8 *)sqlite3_malloc(szFrame);
  43933. if( !aFrame ){
  43934. rc = SQLITE_NOMEM;
  43935. goto recovery_error;
  43936. }
  43937. aData = &aFrame[WAL_FRAME_HDRSIZE];
  43938. /* Read all frames from the log file. */
  43939. iFrame = 0;
  43940. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  43941. u32 pgno; /* Database page number for frame */
  43942. u32 nTruncate; /* dbsize field from frame header */
  43943. /* Read and decode the next log frame. */
  43944. iFrame++;
  43945. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  43946. if( rc!=SQLITE_OK ) break;
  43947. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  43948. if( !isValid ) break;
  43949. rc = walIndexAppend(pWal, iFrame, pgno);
  43950. if( rc!=SQLITE_OK ) break;
  43951. /* If nTruncate is non-zero, this is a commit record. */
  43952. if( nTruncate ){
  43953. pWal->hdr.mxFrame = iFrame;
  43954. pWal->hdr.nPage = nTruncate;
  43955. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  43956. testcase( szPage<=32768 );
  43957. testcase( szPage>=65536 );
  43958. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  43959. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  43960. }
  43961. }
  43962. sqlite3_free(aFrame);
  43963. }
  43964. finished:
  43965. if( rc==SQLITE_OK ){
  43966. volatile WalCkptInfo *pInfo;
  43967. int i;
  43968. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  43969. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  43970. walIndexWriteHdr(pWal);
  43971. /* Reset the checkpoint-header. This is safe because this thread is
  43972. ** currently holding locks that exclude all other readers, writers and
  43973. ** checkpointers.
  43974. */
  43975. pInfo = walCkptInfo(pWal);
  43976. pInfo->nBackfill = 0;
  43977. pInfo->aReadMark[0] = 0;
  43978. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  43979. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  43980. /* If more than one frame was recovered from the log file, report an
  43981. ** event via sqlite3_log(). This is to help with identifying performance
  43982. ** problems caused by applications routinely shutting down without
  43983. ** checkpointing the log file.
  43984. */
  43985. if( pWal->hdr.nPage ){
  43986. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  43987. "recovered %d frames from WAL file %s",
  43988. pWal->hdr.mxFrame, pWal->zWalName
  43989. );
  43990. }
  43991. }
  43992. recovery_error:
  43993. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  43994. walUnlockExclusive(pWal, iLock, nLock);
  43995. return rc;
  43996. }
  43997. /*
  43998. ** Close an open wal-index.
  43999. */
  44000. static void walIndexClose(Wal *pWal, int isDelete){
  44001. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  44002. int i;
  44003. for(i=0; i<pWal->nWiData; i++){
  44004. sqlite3_free((void *)pWal->apWiData[i]);
  44005. pWal->apWiData[i] = 0;
  44006. }
  44007. }else{
  44008. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  44009. }
  44010. }
  44011. /*
  44012. ** Open a connection to the WAL file zWalName. The database file must
  44013. ** already be opened on connection pDbFd. The buffer that zWalName points
  44014. ** to must remain valid for the lifetime of the returned Wal* handle.
  44015. **
  44016. ** A SHARED lock should be held on the database file when this function
  44017. ** is called. The purpose of this SHARED lock is to prevent any other
  44018. ** client from unlinking the WAL or wal-index file. If another process
  44019. ** were to do this just after this client opened one of these files, the
  44020. ** system would be badly broken.
  44021. **
  44022. ** If the log file is successfully opened, SQLITE_OK is returned and
  44023. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  44024. ** an SQLite error code is returned and *ppWal is left unmodified.
  44025. */
  44026. SQLITE_PRIVATE int sqlite3WalOpen(
  44027. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  44028. sqlite3_file *pDbFd, /* The open database file */
  44029. const char *zWalName, /* Name of the WAL file */
  44030. int bNoShm, /* True to run in heap-memory mode */
  44031. i64 mxWalSize, /* Truncate WAL to this size on reset */
  44032. Wal **ppWal /* OUT: Allocated Wal handle */
  44033. ){
  44034. int rc; /* Return Code */
  44035. Wal *pRet; /* Object to allocate and return */
  44036. int flags; /* Flags passed to OsOpen() */
  44037. assert( zWalName && zWalName[0] );
  44038. assert( pDbFd );
  44039. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  44040. ** this source file. Verify that the #defines of the locking byte offsets
  44041. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  44042. */
  44043. #ifdef WIN_SHM_BASE
  44044. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  44045. #endif
  44046. #ifdef UNIX_SHM_BASE
  44047. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  44048. #endif
  44049. /* Allocate an instance of struct Wal to return. */
  44050. *ppWal = 0;
  44051. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  44052. if( !pRet ){
  44053. return SQLITE_NOMEM;
  44054. }
  44055. pRet->pVfs = pVfs;
  44056. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  44057. pRet->pDbFd = pDbFd;
  44058. pRet->readLock = -1;
  44059. pRet->mxWalSize = mxWalSize;
  44060. pRet->zWalName = zWalName;
  44061. pRet->syncHeader = 1;
  44062. pRet->padToSectorBoundary = 1;
  44063. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  44064. /* Open file handle on the write-ahead log file. */
  44065. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  44066. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  44067. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  44068. pRet->readOnly = WAL_RDONLY;
  44069. }
  44070. if( rc!=SQLITE_OK ){
  44071. walIndexClose(pRet, 0);
  44072. sqlite3OsClose(pRet->pWalFd);
  44073. sqlite3_free(pRet);
  44074. }else{
  44075. int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
  44076. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  44077. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  44078. pRet->padToSectorBoundary = 0;
  44079. }
  44080. *ppWal = pRet;
  44081. WALTRACE(("WAL%d: opened\n", pRet));
  44082. }
  44083. return rc;
  44084. }
  44085. /*
  44086. ** Change the size to which the WAL file is trucated on each reset.
  44087. */
  44088. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  44089. if( pWal ) pWal->mxWalSize = iLimit;
  44090. }
  44091. /*
  44092. ** Find the smallest page number out of all pages held in the WAL that
  44093. ** has not been returned by any prior invocation of this method on the
  44094. ** same WalIterator object. Write into *piFrame the frame index where
  44095. ** that page was last written into the WAL. Write into *piPage the page
  44096. ** number.
  44097. **
  44098. ** Return 0 on success. If there are no pages in the WAL with a page
  44099. ** number larger than *piPage, then return 1.
  44100. */
  44101. static int walIteratorNext(
  44102. WalIterator *p, /* Iterator */
  44103. u32 *piPage, /* OUT: The page number of the next page */
  44104. u32 *piFrame /* OUT: Wal frame index of next page */
  44105. ){
  44106. u32 iMin; /* Result pgno must be greater than iMin */
  44107. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  44108. int i; /* For looping through segments */
  44109. iMin = p->iPrior;
  44110. assert( iMin<0xffffffff );
  44111. for(i=p->nSegment-1; i>=0; i--){
  44112. struct WalSegment *pSegment = &p->aSegment[i];
  44113. while( pSegment->iNext<pSegment->nEntry ){
  44114. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  44115. if( iPg>iMin ){
  44116. if( iPg<iRet ){
  44117. iRet = iPg;
  44118. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  44119. }
  44120. break;
  44121. }
  44122. pSegment->iNext++;
  44123. }
  44124. }
  44125. *piPage = p->iPrior = iRet;
  44126. return (iRet==0xFFFFFFFF);
  44127. }
  44128. /*
  44129. ** This function merges two sorted lists into a single sorted list.
  44130. **
  44131. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  44132. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  44133. ** is guaranteed for all J<K:
  44134. **
  44135. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  44136. ** aContent[aRight[J]] < aContent[aRight[K]]
  44137. **
  44138. ** This routine overwrites aRight[] with a new (probably longer) sequence
  44139. ** of indices such that the aRight[] contains every index that appears in
  44140. ** either aLeft[] or the old aRight[] and such that the second condition
  44141. ** above is still met.
  44142. **
  44143. ** The aContent[aLeft[X]] values will be unique for all X. And the
  44144. ** aContent[aRight[X]] values will be unique too. But there might be
  44145. ** one or more combinations of X and Y such that
  44146. **
  44147. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  44148. **
  44149. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  44150. */
  44151. static void walMerge(
  44152. const u32 *aContent, /* Pages in wal - keys for the sort */
  44153. ht_slot *aLeft, /* IN: Left hand input list */
  44154. int nLeft, /* IN: Elements in array *paLeft */
  44155. ht_slot **paRight, /* IN/OUT: Right hand input list */
  44156. int *pnRight, /* IN/OUT: Elements in *paRight */
  44157. ht_slot *aTmp /* Temporary buffer */
  44158. ){
  44159. int iLeft = 0; /* Current index in aLeft */
  44160. int iRight = 0; /* Current index in aRight */
  44161. int iOut = 0; /* Current index in output buffer */
  44162. int nRight = *pnRight;
  44163. ht_slot *aRight = *paRight;
  44164. assert( nLeft>0 && nRight>0 );
  44165. while( iRight<nRight || iLeft<nLeft ){
  44166. ht_slot logpage;
  44167. Pgno dbpage;
  44168. if( (iLeft<nLeft)
  44169. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  44170. ){
  44171. logpage = aLeft[iLeft++];
  44172. }else{
  44173. logpage = aRight[iRight++];
  44174. }
  44175. dbpage = aContent[logpage];
  44176. aTmp[iOut++] = logpage;
  44177. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  44178. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  44179. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  44180. }
  44181. *paRight = aLeft;
  44182. *pnRight = iOut;
  44183. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  44184. }
  44185. /*
  44186. ** Sort the elements in list aList using aContent[] as the sort key.
  44187. ** Remove elements with duplicate keys, preferring to keep the
  44188. ** larger aList[] values.
  44189. **
  44190. ** The aList[] entries are indices into aContent[]. The values in
  44191. ** aList[] are to be sorted so that for all J<K:
  44192. **
  44193. ** aContent[aList[J]] < aContent[aList[K]]
  44194. **
  44195. ** For any X and Y such that
  44196. **
  44197. ** aContent[aList[X]] == aContent[aList[Y]]
  44198. **
  44199. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  44200. ** the smaller.
  44201. */
  44202. static void walMergesort(
  44203. const u32 *aContent, /* Pages in wal */
  44204. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  44205. ht_slot *aList, /* IN/OUT: List to sort */
  44206. int *pnList /* IN/OUT: Number of elements in aList[] */
  44207. ){
  44208. struct Sublist {
  44209. int nList; /* Number of elements in aList */
  44210. ht_slot *aList; /* Pointer to sub-list content */
  44211. };
  44212. const int nList = *pnList; /* Size of input list */
  44213. int nMerge = 0; /* Number of elements in list aMerge */
  44214. ht_slot *aMerge = 0; /* List to be merged */
  44215. int iList; /* Index into input list */
  44216. int iSub = 0; /* Index into aSub array */
  44217. struct Sublist aSub[13]; /* Array of sub-lists */
  44218. memset(aSub, 0, sizeof(aSub));
  44219. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  44220. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  44221. for(iList=0; iList<nList; iList++){
  44222. nMerge = 1;
  44223. aMerge = &aList[iList];
  44224. for(iSub=0; iList & (1<<iSub); iSub++){
  44225. struct Sublist *p = &aSub[iSub];
  44226. assert( p->aList && p->nList<=(1<<iSub) );
  44227. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  44228. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  44229. }
  44230. aSub[iSub].aList = aMerge;
  44231. aSub[iSub].nList = nMerge;
  44232. }
  44233. for(iSub++; iSub<ArraySize(aSub); iSub++){
  44234. if( nList & (1<<iSub) ){
  44235. struct Sublist *p = &aSub[iSub];
  44236. assert( p->nList<=(1<<iSub) );
  44237. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  44238. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  44239. }
  44240. }
  44241. assert( aMerge==aList );
  44242. *pnList = nMerge;
  44243. #ifdef SQLITE_DEBUG
  44244. {
  44245. int i;
  44246. for(i=1; i<*pnList; i++){
  44247. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  44248. }
  44249. }
  44250. #endif
  44251. }
  44252. /*
  44253. ** Free an iterator allocated by walIteratorInit().
  44254. */
  44255. static void walIteratorFree(WalIterator *p){
  44256. sqlite3ScratchFree(p);
  44257. }
  44258. /*
  44259. ** Construct a WalInterator object that can be used to loop over all
  44260. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  44261. ** lock.
  44262. **
  44263. ** On success, make *pp point to the newly allocated WalInterator object
  44264. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  44265. ** returns an error, the value of *pp is undefined.
  44266. **
  44267. ** The calling routine should invoke walIteratorFree() to destroy the
  44268. ** WalIterator object when it has finished with it.
  44269. */
  44270. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  44271. WalIterator *p; /* Return value */
  44272. int nSegment; /* Number of segments to merge */
  44273. u32 iLast; /* Last frame in log */
  44274. int nByte; /* Number of bytes to allocate */
  44275. int i; /* Iterator variable */
  44276. ht_slot *aTmp; /* Temp space used by merge-sort */
  44277. int rc = SQLITE_OK; /* Return Code */
  44278. /* This routine only runs while holding the checkpoint lock. And
  44279. ** it only runs if there is actually content in the log (mxFrame>0).
  44280. */
  44281. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  44282. iLast = pWal->hdr.mxFrame;
  44283. /* Allocate space for the WalIterator object. */
  44284. nSegment = walFramePage(iLast) + 1;
  44285. nByte = sizeof(WalIterator)
  44286. + (nSegment-1)*sizeof(struct WalSegment)
  44287. + iLast*sizeof(ht_slot);
  44288. p = (WalIterator *)sqlite3ScratchMalloc(nByte);
  44289. if( !p ){
  44290. return SQLITE_NOMEM;
  44291. }
  44292. memset(p, 0, nByte);
  44293. p->nSegment = nSegment;
  44294. /* Allocate temporary space used by the merge-sort routine. This block
  44295. ** of memory will be freed before this function returns.
  44296. */
  44297. aTmp = (ht_slot *)sqlite3ScratchMalloc(
  44298. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  44299. );
  44300. if( !aTmp ){
  44301. rc = SQLITE_NOMEM;
  44302. }
  44303. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  44304. volatile ht_slot *aHash;
  44305. u32 iZero;
  44306. volatile u32 *aPgno;
  44307. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  44308. if( rc==SQLITE_OK ){
  44309. int j; /* Counter variable */
  44310. int nEntry; /* Number of entries in this segment */
  44311. ht_slot *aIndex; /* Sorted index for this segment */
  44312. aPgno++;
  44313. if( (i+1)==nSegment ){
  44314. nEntry = (int)(iLast - iZero);
  44315. }else{
  44316. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  44317. }
  44318. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  44319. iZero++;
  44320. for(j=0; j<nEntry; j++){
  44321. aIndex[j] = (ht_slot)j;
  44322. }
  44323. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  44324. p->aSegment[i].iZero = iZero;
  44325. p->aSegment[i].nEntry = nEntry;
  44326. p->aSegment[i].aIndex = aIndex;
  44327. p->aSegment[i].aPgno = (u32 *)aPgno;
  44328. }
  44329. }
  44330. sqlite3ScratchFree(aTmp);
  44331. if( rc!=SQLITE_OK ){
  44332. walIteratorFree(p);
  44333. }
  44334. *pp = p;
  44335. return rc;
  44336. }
  44337. /*
  44338. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  44339. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  44340. ** busy-handler function. Invoke it and retry the lock until either the
  44341. ** lock is successfully obtained or the busy-handler returns 0.
  44342. */
  44343. static int walBusyLock(
  44344. Wal *pWal, /* WAL connection */
  44345. int (*xBusy)(void*), /* Function to call when busy */
  44346. void *pBusyArg, /* Context argument for xBusyHandler */
  44347. int lockIdx, /* Offset of first byte to lock */
  44348. int n /* Number of bytes to lock */
  44349. ){
  44350. int rc;
  44351. do {
  44352. rc = walLockExclusive(pWal, lockIdx, n);
  44353. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  44354. return rc;
  44355. }
  44356. /*
  44357. ** The cache of the wal-index header must be valid to call this function.
  44358. ** Return the page-size in bytes used by the database.
  44359. */
  44360. static int walPagesize(Wal *pWal){
  44361. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  44362. }
  44363. /*
  44364. ** Copy as much content as we can from the WAL back into the database file
  44365. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  44366. **
  44367. ** The amount of information copies from WAL to database might be limited
  44368. ** by active readers. This routine will never overwrite a database page
  44369. ** that a concurrent reader might be using.
  44370. **
  44371. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  44372. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  44373. ** checkpoints are always run by a background thread or background
  44374. ** process, foreground threads will never block on a lengthy fsync call.
  44375. **
  44376. ** Fsync is called on the WAL before writing content out of the WAL and
  44377. ** into the database. This ensures that if the new content is persistent
  44378. ** in the WAL and can be recovered following a power-loss or hard reset.
  44379. **
  44380. ** Fsync is also called on the database file if (and only if) the entire
  44381. ** WAL content is copied into the database file. This second fsync makes
  44382. ** it safe to delete the WAL since the new content will persist in the
  44383. ** database file.
  44384. **
  44385. ** This routine uses and updates the nBackfill field of the wal-index header.
  44386. ** This is the only routine tha will increase the value of nBackfill.
  44387. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  44388. ** its value.)
  44389. **
  44390. ** The caller must be holding sufficient locks to ensure that no other
  44391. ** checkpoint is running (in any other thread or process) at the same
  44392. ** time.
  44393. */
  44394. static int walCheckpoint(
  44395. Wal *pWal, /* Wal connection */
  44396. int eMode, /* One of PASSIVE, FULL or RESTART */
  44397. int (*xBusyCall)(void*), /* Function to call when busy */
  44398. void *pBusyArg, /* Context argument for xBusyHandler */
  44399. int sync_flags, /* Flags for OsSync() (or 0) */
  44400. u8 *zBuf /* Temporary buffer to use */
  44401. ){
  44402. int rc; /* Return code */
  44403. int szPage; /* Database page-size */
  44404. WalIterator *pIter = 0; /* Wal iterator context */
  44405. u32 iDbpage = 0; /* Next database page to write */
  44406. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  44407. u32 mxSafeFrame; /* Max frame that can be backfilled */
  44408. u32 mxPage; /* Max database page to write */
  44409. int i; /* Loop counter */
  44410. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  44411. int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
  44412. szPage = walPagesize(pWal);
  44413. testcase( szPage<=32768 );
  44414. testcase( szPage>=65536 );
  44415. pInfo = walCkptInfo(pWal);
  44416. if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
  44417. /* Allocate the iterator */
  44418. rc = walIteratorInit(pWal, &pIter);
  44419. if( rc!=SQLITE_OK ){
  44420. return rc;
  44421. }
  44422. assert( pIter );
  44423. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
  44424. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  44425. ** safe to write into the database. Frames beyond mxSafeFrame might
  44426. ** overwrite database pages that are in use by active readers and thus
  44427. ** cannot be backfilled from the WAL.
  44428. */
  44429. mxSafeFrame = pWal->hdr.mxFrame;
  44430. mxPage = pWal->hdr.nPage;
  44431. for(i=1; i<WAL_NREADER; i++){
  44432. u32 y = pInfo->aReadMark[i];
  44433. if( mxSafeFrame>y ){
  44434. assert( y<=pWal->hdr.mxFrame );
  44435. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  44436. if( rc==SQLITE_OK ){
  44437. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  44438. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  44439. }else if( rc==SQLITE_BUSY ){
  44440. mxSafeFrame = y;
  44441. xBusy = 0;
  44442. }else{
  44443. goto walcheckpoint_out;
  44444. }
  44445. }
  44446. }
  44447. if( pInfo->nBackfill<mxSafeFrame
  44448. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
  44449. ){
  44450. i64 nSize; /* Current size of database file */
  44451. u32 nBackfill = pInfo->nBackfill;
  44452. /* Sync the WAL to disk */
  44453. if( sync_flags ){
  44454. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  44455. }
  44456. /* If the database may grow as a result of this checkpoint, hint
  44457. ** about the eventual size of the db file to the VFS layer.
  44458. */
  44459. if( rc==SQLITE_OK ){
  44460. i64 nReq = ((i64)mxPage * szPage);
  44461. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  44462. if( rc==SQLITE_OK && nSize<nReq ){
  44463. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  44464. }
  44465. }
  44466. /* Iterate through the contents of the WAL, copying data to the db file. */
  44467. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  44468. i64 iOffset;
  44469. assert( walFramePgno(pWal, iFrame)==iDbpage );
  44470. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
  44471. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  44472. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  44473. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  44474. if( rc!=SQLITE_OK ) break;
  44475. iOffset = (iDbpage-1)*(i64)szPage;
  44476. testcase( IS_BIG_INT(iOffset) );
  44477. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  44478. if( rc!=SQLITE_OK ) break;
  44479. }
  44480. /* If work was actually accomplished... */
  44481. if( rc==SQLITE_OK ){
  44482. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  44483. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  44484. testcase( IS_BIG_INT(szDb) );
  44485. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  44486. if( rc==SQLITE_OK && sync_flags ){
  44487. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  44488. }
  44489. }
  44490. if( rc==SQLITE_OK ){
  44491. pInfo->nBackfill = mxSafeFrame;
  44492. }
  44493. }
  44494. /* Release the reader lock held while backfilling */
  44495. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  44496. }
  44497. if( rc==SQLITE_BUSY ){
  44498. /* Reset the return code so as not to report a checkpoint failure
  44499. ** just because there are active readers. */
  44500. rc = SQLITE_OK;
  44501. }
  44502. /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
  44503. ** file has been copied into the database file, then block until all
  44504. ** readers have finished using the wal file. This ensures that the next
  44505. ** process to write to the database restarts the wal file.
  44506. */
  44507. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  44508. assert( pWal->writeLock );
  44509. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  44510. rc = SQLITE_BUSY;
  44511. }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
  44512. assert( mxSafeFrame==pWal->hdr.mxFrame );
  44513. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  44514. if( rc==SQLITE_OK ){
  44515. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  44516. }
  44517. }
  44518. }
  44519. walcheckpoint_out:
  44520. walIteratorFree(pIter);
  44521. return rc;
  44522. }
  44523. /*
  44524. ** If the WAL file is currently larger than nMax bytes in size, truncate
  44525. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  44526. */
  44527. static void walLimitSize(Wal *pWal, i64 nMax){
  44528. i64 sz;
  44529. int rx;
  44530. sqlite3BeginBenignMalloc();
  44531. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  44532. if( rx==SQLITE_OK && (sz > nMax ) ){
  44533. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  44534. }
  44535. sqlite3EndBenignMalloc();
  44536. if( rx ){
  44537. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  44538. }
  44539. }
  44540. /*
  44541. ** Close a connection to a log file.
  44542. */
  44543. SQLITE_PRIVATE int sqlite3WalClose(
  44544. Wal *pWal, /* Wal to close */
  44545. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  44546. int nBuf,
  44547. u8 *zBuf /* Buffer of at least nBuf bytes */
  44548. ){
  44549. int rc = SQLITE_OK;
  44550. if( pWal ){
  44551. int isDelete = 0; /* True to unlink wal and wal-index files */
  44552. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  44553. ** ordinary, rollback-mode locking methods, this guarantees that the
  44554. ** connection associated with this log file is the only connection to
  44555. ** the database. In this case checkpoint the database and unlink both
  44556. ** the wal and wal-index files.
  44557. **
  44558. ** The EXCLUSIVE lock is not released before returning.
  44559. */
  44560. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  44561. if( rc==SQLITE_OK ){
  44562. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  44563. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  44564. }
  44565. rc = sqlite3WalCheckpoint(
  44566. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  44567. );
  44568. if( rc==SQLITE_OK ){
  44569. int bPersist = -1;
  44570. sqlite3OsFileControlHint(
  44571. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  44572. );
  44573. if( bPersist!=1 ){
  44574. /* Try to delete the WAL file if the checkpoint completed and
  44575. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  44576. ** mode (!bPersist) */
  44577. isDelete = 1;
  44578. }else if( pWal->mxWalSize>=0 ){
  44579. /* Try to truncate the WAL file to zero bytes if the checkpoint
  44580. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  44581. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  44582. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  44583. ** to zero bytes as truncating to the journal_size_limit might
  44584. ** leave a corrupt WAL file on disk. */
  44585. walLimitSize(pWal, 0);
  44586. }
  44587. }
  44588. }
  44589. walIndexClose(pWal, isDelete);
  44590. sqlite3OsClose(pWal->pWalFd);
  44591. if( isDelete ){
  44592. sqlite3BeginBenignMalloc();
  44593. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  44594. sqlite3EndBenignMalloc();
  44595. }
  44596. WALTRACE(("WAL%p: closed\n", pWal));
  44597. sqlite3_free((void *)pWal->apWiData);
  44598. sqlite3_free(pWal);
  44599. }
  44600. return rc;
  44601. }
  44602. /*
  44603. ** Try to read the wal-index header. Return 0 on success and 1 if
  44604. ** there is a problem.
  44605. **
  44606. ** The wal-index is in shared memory. Another thread or process might
  44607. ** be writing the header at the same time this procedure is trying to
  44608. ** read it, which might result in inconsistency. A dirty read is detected
  44609. ** by verifying that both copies of the header are the same and also by
  44610. ** a checksum on the header.
  44611. **
  44612. ** If and only if the read is consistent and the header is different from
  44613. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  44614. ** and *pChanged is set to 1.
  44615. **
  44616. ** If the checksum cannot be verified return non-zero. If the header
  44617. ** is read successfully and the checksum verified, return zero.
  44618. */
  44619. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  44620. u32 aCksum[2]; /* Checksum on the header content */
  44621. WalIndexHdr h1, h2; /* Two copies of the header content */
  44622. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  44623. /* The first page of the wal-index must be mapped at this point. */
  44624. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  44625. /* Read the header. This might happen concurrently with a write to the
  44626. ** same area of shared memory on a different CPU in a SMP,
  44627. ** meaning it is possible that an inconsistent snapshot is read
  44628. ** from the file. If this happens, return non-zero.
  44629. **
  44630. ** There are two copies of the header at the beginning of the wal-index.
  44631. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  44632. ** Memory barriers are used to prevent the compiler or the hardware from
  44633. ** reordering the reads and writes.
  44634. */
  44635. aHdr = walIndexHdr(pWal);
  44636. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  44637. walShmBarrier(pWal);
  44638. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  44639. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  44640. return 1; /* Dirty read */
  44641. }
  44642. if( h1.isInit==0 ){
  44643. return 1; /* Malformed header - probably all zeros */
  44644. }
  44645. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  44646. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  44647. return 1; /* Checksum does not match */
  44648. }
  44649. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  44650. *pChanged = 1;
  44651. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  44652. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  44653. testcase( pWal->szPage<=32768 );
  44654. testcase( pWal->szPage>=65536 );
  44655. }
  44656. /* The header was successfully read. Return zero. */
  44657. return 0;
  44658. }
  44659. /*
  44660. ** Read the wal-index header from the wal-index and into pWal->hdr.
  44661. ** If the wal-header appears to be corrupt, try to reconstruct the
  44662. ** wal-index from the WAL before returning.
  44663. **
  44664. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  44665. ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
  44666. ** to 0.
  44667. **
  44668. ** If the wal-index header is successfully read, return SQLITE_OK.
  44669. ** Otherwise an SQLite error code.
  44670. */
  44671. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  44672. int rc; /* Return code */
  44673. int badHdr; /* True if a header read failed */
  44674. volatile u32 *page0; /* Chunk of wal-index containing header */
  44675. /* Ensure that page 0 of the wal-index (the page that contains the
  44676. ** wal-index header) is mapped. Return early if an error occurs here.
  44677. */
  44678. assert( pChanged );
  44679. rc = walIndexPage(pWal, 0, &page0);
  44680. if( rc!=SQLITE_OK ){
  44681. return rc;
  44682. };
  44683. assert( page0 || pWal->writeLock==0 );
  44684. /* If the first page of the wal-index has been mapped, try to read the
  44685. ** wal-index header immediately, without holding any lock. This usually
  44686. ** works, but may fail if the wal-index header is corrupt or currently
  44687. ** being modified by another thread or process.
  44688. */
  44689. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  44690. /* If the first attempt failed, it might have been due to a race
  44691. ** with a writer. So get a WRITE lock and try again.
  44692. */
  44693. assert( badHdr==0 || pWal->writeLock==0 );
  44694. if( badHdr ){
  44695. if( pWal->readOnly & WAL_SHM_RDONLY ){
  44696. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  44697. walUnlockShared(pWal, WAL_WRITE_LOCK);
  44698. rc = SQLITE_READONLY_RECOVERY;
  44699. }
  44700. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  44701. pWal->writeLock = 1;
  44702. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  44703. badHdr = walIndexTryHdr(pWal, pChanged);
  44704. if( badHdr ){
  44705. /* If the wal-index header is still malformed even while holding
  44706. ** a WRITE lock, it can only mean that the header is corrupted and
  44707. ** needs to be reconstructed. So run recovery to do exactly that.
  44708. */
  44709. rc = walIndexRecover(pWal);
  44710. *pChanged = 1;
  44711. }
  44712. }
  44713. pWal->writeLock = 0;
  44714. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  44715. }
  44716. }
  44717. /* If the header is read successfully, check the version number to make
  44718. ** sure the wal-index was not constructed with some future format that
  44719. ** this version of SQLite cannot understand.
  44720. */
  44721. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  44722. rc = SQLITE_CANTOPEN_BKPT;
  44723. }
  44724. return rc;
  44725. }
  44726. /*
  44727. ** This is the value that walTryBeginRead returns when it needs to
  44728. ** be retried.
  44729. */
  44730. #define WAL_RETRY (-1)
  44731. /*
  44732. ** Attempt to start a read transaction. This might fail due to a race or
  44733. ** other transient condition. When that happens, it returns WAL_RETRY to
  44734. ** indicate to the caller that it is safe to retry immediately.
  44735. **
  44736. ** On success return SQLITE_OK. On a permanent failure (such an
  44737. ** I/O error or an SQLITE_BUSY because another process is running
  44738. ** recovery) return a positive error code.
  44739. **
  44740. ** The useWal parameter is true to force the use of the WAL and disable
  44741. ** the case where the WAL is bypassed because it has been completely
  44742. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  44743. ** to make a copy of the wal-index header into pWal->hdr. If the
  44744. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  44745. ** to the caller that the local paget cache is obsolete and needs to be
  44746. ** flushed.) When useWal==1, the wal-index header is assumed to already
  44747. ** be loaded and the pChanged parameter is unused.
  44748. **
  44749. ** The caller must set the cnt parameter to the number of prior calls to
  44750. ** this routine during the current read attempt that returned WAL_RETRY.
  44751. ** This routine will start taking more aggressive measures to clear the
  44752. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  44753. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  44754. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  44755. ** and is not honoring the locking protocol. There is a vanishingly small
  44756. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  44757. ** bad luck when there is lots of contention for the wal-index, but that
  44758. ** possibility is so small that it can be safely neglected, we believe.
  44759. **
  44760. ** On success, this routine obtains a read lock on
  44761. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  44762. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  44763. ** that means the Wal does not hold any read lock. The reader must not
  44764. ** access any database page that is modified by a WAL frame up to and
  44765. ** including frame number aReadMark[pWal->readLock]. The reader will
  44766. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  44767. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  44768. ** completely and get all content directly from the database file.
  44769. ** If the useWal parameter is 1 then the WAL will never be ignored and
  44770. ** this routine will always set pWal->readLock>0 on success.
  44771. ** When the read transaction is completed, the caller must release the
  44772. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  44773. **
  44774. ** This routine uses the nBackfill and aReadMark[] fields of the header
  44775. ** to select a particular WAL_READ_LOCK() that strives to let the
  44776. ** checkpoint process do as much work as possible. This routine might
  44777. ** update values of the aReadMark[] array in the header, but if it does
  44778. ** so it takes care to hold an exclusive lock on the corresponding
  44779. ** WAL_READ_LOCK() while changing values.
  44780. */
  44781. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  44782. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  44783. u32 mxReadMark; /* Largest aReadMark[] value */
  44784. int mxI; /* Index of largest aReadMark[] value */
  44785. int i; /* Loop counter */
  44786. int rc = SQLITE_OK; /* Return code */
  44787. assert( pWal->readLock<0 ); /* Not currently locked */
  44788. /* Take steps to avoid spinning forever if there is a protocol error.
  44789. **
  44790. ** Circumstances that cause a RETRY should only last for the briefest
  44791. ** instances of time. No I/O or other system calls are done while the
  44792. ** locks are held, so the locks should not be held for very long. But
  44793. ** if we are unlucky, another process that is holding a lock might get
  44794. ** paged out or take a page-fault that is time-consuming to resolve,
  44795. ** during the few nanoseconds that it is holding the lock. In that case,
  44796. ** it might take longer than normal for the lock to free.
  44797. **
  44798. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  44799. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  44800. ** is more of a scheduler yield than an actual delay. But on the 10th
  44801. ** an subsequent retries, the delays start becoming longer and longer,
  44802. ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
  44803. ** The total delay time before giving up is less than 1 second.
  44804. */
  44805. if( cnt>5 ){
  44806. int nDelay = 1; /* Pause time in microseconds */
  44807. if( cnt>100 ){
  44808. VVA_ONLY( pWal->lockError = 1; )
  44809. return SQLITE_PROTOCOL;
  44810. }
  44811. if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
  44812. sqlite3OsSleep(pWal->pVfs, nDelay);
  44813. }
  44814. if( !useWal ){
  44815. rc = walIndexReadHdr(pWal, pChanged);
  44816. if( rc==SQLITE_BUSY ){
  44817. /* If there is not a recovery running in another thread or process
  44818. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  44819. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  44820. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  44821. ** would be technically correct. But the race is benign since with
  44822. ** WAL_RETRY this routine will be called again and will probably be
  44823. ** right on the second iteration.
  44824. */
  44825. if( pWal->apWiData[0]==0 ){
  44826. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  44827. ** We assume this is a transient condition, so return WAL_RETRY. The
  44828. ** xShmMap() implementation used by the default unix and win32 VFS
  44829. ** modules may return SQLITE_BUSY due to a race condition in the
  44830. ** code that determines whether or not the shared-memory region
  44831. ** must be zeroed before the requested page is returned.
  44832. */
  44833. rc = WAL_RETRY;
  44834. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  44835. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  44836. rc = WAL_RETRY;
  44837. }else if( rc==SQLITE_BUSY ){
  44838. rc = SQLITE_BUSY_RECOVERY;
  44839. }
  44840. }
  44841. if( rc!=SQLITE_OK ){
  44842. return rc;
  44843. }
  44844. }
  44845. pInfo = walCkptInfo(pWal);
  44846. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  44847. /* The WAL has been completely backfilled (or it is empty).
  44848. ** and can be safely ignored.
  44849. */
  44850. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  44851. walShmBarrier(pWal);
  44852. if( rc==SQLITE_OK ){
  44853. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  44854. /* It is not safe to allow the reader to continue here if frames
  44855. ** may have been appended to the log before READ_LOCK(0) was obtained.
  44856. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  44857. ** which implies that the database file contains a trustworthy
  44858. ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
  44859. ** happening, this is usually correct.
  44860. **
  44861. ** However, if frames have been appended to the log (or if the log
  44862. ** is wrapped and written for that matter) before the READ_LOCK(0)
  44863. ** is obtained, that is not necessarily true. A checkpointer may
  44864. ** have started to backfill the appended frames but crashed before
  44865. ** it finished. Leaving a corrupt image in the database file.
  44866. */
  44867. walUnlockShared(pWal, WAL_READ_LOCK(0));
  44868. return WAL_RETRY;
  44869. }
  44870. pWal->readLock = 0;
  44871. return SQLITE_OK;
  44872. }else if( rc!=SQLITE_BUSY ){
  44873. return rc;
  44874. }
  44875. }
  44876. /* If we get this far, it means that the reader will want to use
  44877. ** the WAL to get at content from recent commits. The job now is
  44878. ** to select one of the aReadMark[] entries that is closest to
  44879. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  44880. */
  44881. mxReadMark = 0;
  44882. mxI = 0;
  44883. for(i=1; i<WAL_NREADER; i++){
  44884. u32 thisMark = pInfo->aReadMark[i];
  44885. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  44886. assert( thisMark!=READMARK_NOT_USED );
  44887. mxReadMark = thisMark;
  44888. mxI = i;
  44889. }
  44890. }
  44891. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  44892. {
  44893. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  44894. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  44895. ){
  44896. for(i=1; i<WAL_NREADER; i++){
  44897. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  44898. if( rc==SQLITE_OK ){
  44899. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  44900. mxI = i;
  44901. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  44902. break;
  44903. }else if( rc!=SQLITE_BUSY ){
  44904. return rc;
  44905. }
  44906. }
  44907. }
  44908. if( mxI==0 ){
  44909. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  44910. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  44911. }
  44912. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  44913. if( rc ){
  44914. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  44915. }
  44916. /* Now that the read-lock has been obtained, check that neither the
  44917. ** value in the aReadMark[] array or the contents of the wal-index
  44918. ** header have changed.
  44919. **
  44920. ** It is necessary to check that the wal-index header did not change
  44921. ** between the time it was read and when the shared-lock was obtained
  44922. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  44923. ** that the log file may have been wrapped by a writer, or that frames
  44924. ** that occur later in the log than pWal->hdr.mxFrame may have been
  44925. ** copied into the database by a checkpointer. If either of these things
  44926. ** happened, then reading the database with the current value of
  44927. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  44928. ** instead.
  44929. **
  44930. ** This does not guarantee that the copy of the wal-index header is up to
  44931. ** date before proceeding. That would not be possible without somehow
  44932. ** blocking writers. It only guarantees that a dangerous checkpoint or
  44933. ** log-wrap (either of which would require an exclusive lock on
  44934. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  44935. */
  44936. walShmBarrier(pWal);
  44937. if( pInfo->aReadMark[mxI]!=mxReadMark
  44938. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  44939. ){
  44940. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  44941. return WAL_RETRY;
  44942. }else{
  44943. assert( mxReadMark<=pWal->hdr.mxFrame );
  44944. pWal->readLock = (i16)mxI;
  44945. }
  44946. }
  44947. return rc;
  44948. }
  44949. /*
  44950. ** Begin a read transaction on the database.
  44951. **
  44952. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  44953. ** it takes a snapshot of the state of the WAL and wal-index for the current
  44954. ** instant in time. The current thread will continue to use this snapshot.
  44955. ** Other threads might append new content to the WAL and wal-index but
  44956. ** that extra content is ignored by the current thread.
  44957. **
  44958. ** If the database contents have changes since the previous read
  44959. ** transaction, then *pChanged is set to 1 before returning. The
  44960. ** Pager layer will use this to know that is cache is stale and
  44961. ** needs to be flushed.
  44962. */
  44963. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  44964. int rc; /* Return code */
  44965. int cnt = 0; /* Number of TryBeginRead attempts */
  44966. do{
  44967. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  44968. }while( rc==WAL_RETRY );
  44969. testcase( (rc&0xff)==SQLITE_BUSY );
  44970. testcase( (rc&0xff)==SQLITE_IOERR );
  44971. testcase( rc==SQLITE_PROTOCOL );
  44972. testcase( rc==SQLITE_OK );
  44973. return rc;
  44974. }
  44975. /*
  44976. ** Finish with a read transaction. All this does is release the
  44977. ** read-lock.
  44978. */
  44979. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  44980. sqlite3WalEndWriteTransaction(pWal);
  44981. if( pWal->readLock>=0 ){
  44982. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  44983. pWal->readLock = -1;
  44984. }
  44985. }
  44986. /*
  44987. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  44988. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  44989. ** to zero.
  44990. **
  44991. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  44992. ** error does occur, the final value of *piRead is undefined.
  44993. */
  44994. SQLITE_PRIVATE int sqlite3WalFindFrame(
  44995. Wal *pWal, /* WAL handle */
  44996. Pgno pgno, /* Database page number to read data for */
  44997. u32 *piRead /* OUT: Frame number (or zero) */
  44998. ){
  44999. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  45000. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  45001. int iHash; /* Used to loop through N hash tables */
  45002. /* This routine is only be called from within a read transaction. */
  45003. assert( pWal->readLock>=0 || pWal->lockError );
  45004. /* If the "last page" field of the wal-index header snapshot is 0, then
  45005. ** no data will be read from the wal under any circumstances. Return early
  45006. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  45007. ** then the WAL is ignored by the reader so return early, as if the
  45008. ** WAL were empty.
  45009. */
  45010. if( iLast==0 || pWal->readLock==0 ){
  45011. *piRead = 0;
  45012. return SQLITE_OK;
  45013. }
  45014. /* Search the hash table or tables for an entry matching page number
  45015. ** pgno. Each iteration of the following for() loop searches one
  45016. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  45017. **
  45018. ** This code might run concurrently to the code in walIndexAppend()
  45019. ** that adds entries to the wal-index (and possibly to this hash
  45020. ** table). This means the value just read from the hash
  45021. ** slot (aHash[iKey]) may have been added before or after the
  45022. ** current read transaction was opened. Values added after the
  45023. ** read transaction was opened may have been written incorrectly -
  45024. ** i.e. these slots may contain garbage data. However, we assume
  45025. ** that any slots written before the current read transaction was
  45026. ** opened remain unmodified.
  45027. **
  45028. ** For the reasons above, the if(...) condition featured in the inner
  45029. ** loop of the following block is more stringent that would be required
  45030. ** if we had exclusive access to the hash-table:
  45031. **
  45032. ** (aPgno[iFrame]==pgno):
  45033. ** This condition filters out normal hash-table collisions.
  45034. **
  45035. ** (iFrame<=iLast):
  45036. ** This condition filters out entries that were added to the hash
  45037. ** table after the current read-transaction had started.
  45038. */
  45039. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  45040. volatile ht_slot *aHash; /* Pointer to hash table */
  45041. volatile u32 *aPgno; /* Pointer to array of page numbers */
  45042. u32 iZero; /* Frame number corresponding to aPgno[0] */
  45043. int iKey; /* Hash slot index */
  45044. int nCollide; /* Number of hash collisions remaining */
  45045. int rc; /* Error code */
  45046. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  45047. if( rc!=SQLITE_OK ){
  45048. return rc;
  45049. }
  45050. nCollide = HASHTABLE_NSLOT;
  45051. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  45052. u32 iFrame = aHash[iKey] + iZero;
  45053. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  45054. /* assert( iFrame>iRead ); -- not true if there is corruption */
  45055. iRead = iFrame;
  45056. }
  45057. if( (nCollide--)==0 ){
  45058. return SQLITE_CORRUPT_BKPT;
  45059. }
  45060. }
  45061. }
  45062. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  45063. /* If expensive assert() statements are available, do a linear search
  45064. ** of the wal-index file content. Make sure the results agree with the
  45065. ** result obtained using the hash indexes above. */
  45066. {
  45067. u32 iRead2 = 0;
  45068. u32 iTest;
  45069. for(iTest=iLast; iTest>0; iTest--){
  45070. if( walFramePgno(pWal, iTest)==pgno ){
  45071. iRead2 = iTest;
  45072. break;
  45073. }
  45074. }
  45075. assert( iRead==iRead2 );
  45076. }
  45077. #endif
  45078. *piRead = iRead;
  45079. return SQLITE_OK;
  45080. }
  45081. /*
  45082. ** Read the contents of frame iRead from the wal file into buffer pOut
  45083. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  45084. ** error code otherwise.
  45085. */
  45086. SQLITE_PRIVATE int sqlite3WalReadFrame(
  45087. Wal *pWal, /* WAL handle */
  45088. u32 iRead, /* Frame to read */
  45089. int nOut, /* Size of buffer pOut in bytes */
  45090. u8 *pOut /* Buffer to write page data to */
  45091. ){
  45092. int sz;
  45093. i64 iOffset;
  45094. sz = pWal->hdr.szPage;
  45095. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  45096. testcase( sz<=32768 );
  45097. testcase( sz>=65536 );
  45098. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  45099. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  45100. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  45101. }
  45102. /*
  45103. ** Return the size of the database in pages (or zero, if unknown).
  45104. */
  45105. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  45106. if( pWal && ALWAYS(pWal->readLock>=0) ){
  45107. return pWal->hdr.nPage;
  45108. }
  45109. return 0;
  45110. }
  45111. /*
  45112. ** This function starts a write transaction on the WAL.
  45113. **
  45114. ** A read transaction must have already been started by a prior call
  45115. ** to sqlite3WalBeginReadTransaction().
  45116. **
  45117. ** If another thread or process has written into the database since
  45118. ** the read transaction was started, then it is not possible for this
  45119. ** thread to write as doing so would cause a fork. So this routine
  45120. ** returns SQLITE_BUSY in that case and no write transaction is started.
  45121. **
  45122. ** There can only be a single writer active at a time.
  45123. */
  45124. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  45125. int rc;
  45126. /* Cannot start a write transaction without first holding a read
  45127. ** transaction. */
  45128. assert( pWal->readLock>=0 );
  45129. if( pWal->readOnly ){
  45130. return SQLITE_READONLY;
  45131. }
  45132. /* Only one writer allowed at a time. Get the write lock. Return
  45133. ** SQLITE_BUSY if unable.
  45134. */
  45135. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  45136. if( rc ){
  45137. return rc;
  45138. }
  45139. pWal->writeLock = 1;
  45140. /* If another connection has written to the database file since the
  45141. ** time the read transaction on this connection was started, then
  45142. ** the write is disallowed.
  45143. */
  45144. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  45145. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  45146. pWal->writeLock = 0;
  45147. rc = SQLITE_BUSY_SNAPSHOT;
  45148. }
  45149. return rc;
  45150. }
  45151. /*
  45152. ** End a write transaction. The commit has already been done. This
  45153. ** routine merely releases the lock.
  45154. */
  45155. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  45156. if( pWal->writeLock ){
  45157. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  45158. pWal->writeLock = 0;
  45159. pWal->truncateOnCommit = 0;
  45160. }
  45161. return SQLITE_OK;
  45162. }
  45163. /*
  45164. ** If any data has been written (but not committed) to the log file, this
  45165. ** function moves the write-pointer back to the start of the transaction.
  45166. **
  45167. ** Additionally, the callback function is invoked for each frame written
  45168. ** to the WAL since the start of the transaction. If the callback returns
  45169. ** other than SQLITE_OK, it is not invoked again and the error code is
  45170. ** returned to the caller.
  45171. **
  45172. ** Otherwise, if the callback function does not return an error, this
  45173. ** function returns SQLITE_OK.
  45174. */
  45175. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  45176. int rc = SQLITE_OK;
  45177. if( ALWAYS(pWal->writeLock) ){
  45178. Pgno iMax = pWal->hdr.mxFrame;
  45179. Pgno iFrame;
  45180. /* Restore the clients cache of the wal-index header to the state it
  45181. ** was in before the client began writing to the database.
  45182. */
  45183. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  45184. for(iFrame=pWal->hdr.mxFrame+1;
  45185. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  45186. iFrame++
  45187. ){
  45188. /* This call cannot fail. Unless the page for which the page number
  45189. ** is passed as the second argument is (a) in the cache and
  45190. ** (b) has an outstanding reference, then xUndo is either a no-op
  45191. ** (if (a) is false) or simply expels the page from the cache (if (b)
  45192. ** is false).
  45193. **
  45194. ** If the upper layer is doing a rollback, it is guaranteed that there
  45195. ** are no outstanding references to any page other than page 1. And
  45196. ** page 1 is never written to the log until the transaction is
  45197. ** committed. As a result, the call to xUndo may not fail.
  45198. */
  45199. assert( walFramePgno(pWal, iFrame)!=1 );
  45200. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  45201. }
  45202. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  45203. }
  45204. assert( rc==SQLITE_OK );
  45205. return rc;
  45206. }
  45207. /*
  45208. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  45209. ** values. This function populates the array with values required to
  45210. ** "rollback" the write position of the WAL handle back to the current
  45211. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  45212. */
  45213. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  45214. assert( pWal->writeLock );
  45215. aWalData[0] = pWal->hdr.mxFrame;
  45216. aWalData[1] = pWal->hdr.aFrameCksum[0];
  45217. aWalData[2] = pWal->hdr.aFrameCksum[1];
  45218. aWalData[3] = pWal->nCkpt;
  45219. }
  45220. /*
  45221. ** Move the write position of the WAL back to the point identified by
  45222. ** the values in the aWalData[] array. aWalData must point to an array
  45223. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  45224. ** by a call to WalSavepoint().
  45225. */
  45226. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  45227. int rc = SQLITE_OK;
  45228. assert( pWal->writeLock );
  45229. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  45230. if( aWalData[3]!=pWal->nCkpt ){
  45231. /* This savepoint was opened immediately after the write-transaction
  45232. ** was started. Right after that, the writer decided to wrap around
  45233. ** to the start of the log. Update the savepoint values to match.
  45234. */
  45235. aWalData[0] = 0;
  45236. aWalData[3] = pWal->nCkpt;
  45237. }
  45238. if( aWalData[0]<pWal->hdr.mxFrame ){
  45239. pWal->hdr.mxFrame = aWalData[0];
  45240. pWal->hdr.aFrameCksum[0] = aWalData[1];
  45241. pWal->hdr.aFrameCksum[1] = aWalData[2];
  45242. walCleanupHash(pWal);
  45243. }
  45244. return rc;
  45245. }
  45246. /*
  45247. ** This function is called just before writing a set of frames to the log
  45248. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  45249. ** to the current log file, it is possible to overwrite the start of the
  45250. ** existing log file with the new frames (i.e. "reset" the log). If so,
  45251. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  45252. ** unchanged.
  45253. **
  45254. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  45255. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  45256. ** if an error occurs.
  45257. */
  45258. static int walRestartLog(Wal *pWal){
  45259. int rc = SQLITE_OK;
  45260. int cnt;
  45261. if( pWal->readLock==0 ){
  45262. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  45263. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  45264. if( pInfo->nBackfill>0 ){
  45265. u32 salt1;
  45266. sqlite3_randomness(4, &salt1);
  45267. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  45268. if( rc==SQLITE_OK ){
  45269. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  45270. ** readers are currently using the WAL), then the transactions
  45271. ** frames will overwrite the start of the existing log. Update the
  45272. ** wal-index header to reflect this.
  45273. **
  45274. ** In theory it would be Ok to update the cache of the header only
  45275. ** at this point. But updating the actual wal-index header is also
  45276. ** safe and means there is no special case for sqlite3WalUndo()
  45277. ** to handle if this transaction is rolled back.
  45278. */
  45279. int i; /* Loop counter */
  45280. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  45281. pWal->nCkpt++;
  45282. pWal->hdr.mxFrame = 0;
  45283. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  45284. aSalt[1] = salt1;
  45285. walIndexWriteHdr(pWal);
  45286. pInfo->nBackfill = 0;
  45287. pInfo->aReadMark[1] = 0;
  45288. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  45289. assert( pInfo->aReadMark[0]==0 );
  45290. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  45291. }else if( rc!=SQLITE_BUSY ){
  45292. return rc;
  45293. }
  45294. }
  45295. walUnlockShared(pWal, WAL_READ_LOCK(0));
  45296. pWal->readLock = -1;
  45297. cnt = 0;
  45298. do{
  45299. int notUsed;
  45300. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  45301. }while( rc==WAL_RETRY );
  45302. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  45303. testcase( (rc&0xff)==SQLITE_IOERR );
  45304. testcase( rc==SQLITE_PROTOCOL );
  45305. testcase( rc==SQLITE_OK );
  45306. }
  45307. return rc;
  45308. }
  45309. /*
  45310. ** Information about the current state of the WAL file and where
  45311. ** the next fsync should occur - passed from sqlite3WalFrames() into
  45312. ** walWriteToLog().
  45313. */
  45314. typedef struct WalWriter {
  45315. Wal *pWal; /* The complete WAL information */
  45316. sqlite3_file *pFd; /* The WAL file to which we write */
  45317. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  45318. int syncFlags; /* Flags for the fsync */
  45319. int szPage; /* Size of one page */
  45320. } WalWriter;
  45321. /*
  45322. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  45323. ** Do a sync when crossing the p->iSyncPoint boundary.
  45324. **
  45325. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  45326. ** first write the part before iSyncPoint, then sync, then write the
  45327. ** rest.
  45328. */
  45329. static int walWriteToLog(
  45330. WalWriter *p, /* WAL to write to */
  45331. void *pContent, /* Content to be written */
  45332. int iAmt, /* Number of bytes to write */
  45333. sqlite3_int64 iOffset /* Start writing at this offset */
  45334. ){
  45335. int rc;
  45336. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  45337. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  45338. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  45339. if( rc ) return rc;
  45340. iOffset += iFirstAmt;
  45341. iAmt -= iFirstAmt;
  45342. pContent = (void*)(iFirstAmt + (char*)pContent);
  45343. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  45344. rc = sqlite3OsSync(p->pFd, p->syncFlags);
  45345. if( iAmt==0 || rc ) return rc;
  45346. }
  45347. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  45348. return rc;
  45349. }
  45350. /*
  45351. ** Write out a single frame of the WAL
  45352. */
  45353. static int walWriteOneFrame(
  45354. WalWriter *p, /* Where to write the frame */
  45355. PgHdr *pPage, /* The page of the frame to be written */
  45356. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  45357. sqlite3_int64 iOffset /* Byte offset at which to write */
  45358. ){
  45359. int rc; /* Result code from subfunctions */
  45360. void *pData; /* Data actually written */
  45361. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  45362. #if defined(SQLITE_HAS_CODEC)
  45363. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  45364. #else
  45365. pData = pPage->pData;
  45366. #endif
  45367. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  45368. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  45369. if( rc ) return rc;
  45370. /* Write the page data */
  45371. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  45372. return rc;
  45373. }
  45374. /*
  45375. ** Write a set of frames to the log. The caller must hold the write-lock
  45376. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  45377. */
  45378. SQLITE_PRIVATE int sqlite3WalFrames(
  45379. Wal *pWal, /* Wal handle to write to */
  45380. int szPage, /* Database page-size in bytes */
  45381. PgHdr *pList, /* List of dirty pages to write */
  45382. Pgno nTruncate, /* Database size after this commit */
  45383. int isCommit, /* True if this is a commit */
  45384. int sync_flags /* Flags to pass to OsSync() (or 0) */
  45385. ){
  45386. int rc; /* Used to catch return codes */
  45387. u32 iFrame; /* Next frame address */
  45388. PgHdr *p; /* Iterator to run through pList with. */
  45389. PgHdr *pLast = 0; /* Last frame in list */
  45390. int nExtra = 0; /* Number of extra copies of last page */
  45391. int szFrame; /* The size of a single frame */
  45392. i64 iOffset; /* Next byte to write in WAL file */
  45393. WalWriter w; /* The writer */
  45394. assert( pList );
  45395. assert( pWal->writeLock );
  45396. /* If this frame set completes a transaction, then nTruncate>0. If
  45397. ** nTruncate==0 then this frame set does not complete the transaction. */
  45398. assert( (isCommit!=0)==(nTruncate!=0) );
  45399. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  45400. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  45401. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  45402. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  45403. }
  45404. #endif
  45405. /* See if it is possible to write these frames into the start of the
  45406. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  45407. */
  45408. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  45409. return rc;
  45410. }
  45411. /* If this is the first frame written into the log, write the WAL
  45412. ** header to the start of the WAL file. See comments at the top of
  45413. ** this source file for a description of the WAL header format.
  45414. */
  45415. iFrame = pWal->hdr.mxFrame;
  45416. if( iFrame==0 ){
  45417. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  45418. u32 aCksum[2]; /* Checksum for wal-header */
  45419. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  45420. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  45421. sqlite3Put4byte(&aWalHdr[8], szPage);
  45422. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  45423. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  45424. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  45425. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  45426. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  45427. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  45428. pWal->szPage = szPage;
  45429. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  45430. pWal->hdr.aFrameCksum[0] = aCksum[0];
  45431. pWal->hdr.aFrameCksum[1] = aCksum[1];
  45432. pWal->truncateOnCommit = 1;
  45433. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  45434. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  45435. if( rc!=SQLITE_OK ){
  45436. return rc;
  45437. }
  45438. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  45439. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  45440. ** an out-of-order write following a WAL restart could result in
  45441. ** database corruption. See the ticket:
  45442. **
  45443. ** http://localhost:591/sqlite/info/ff5be73dee
  45444. */
  45445. if( pWal->syncHeader && sync_flags ){
  45446. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  45447. if( rc ) return rc;
  45448. }
  45449. }
  45450. assert( (int)pWal->szPage==szPage );
  45451. /* Setup information needed to write frames into the WAL */
  45452. w.pWal = pWal;
  45453. w.pFd = pWal->pWalFd;
  45454. w.iSyncPoint = 0;
  45455. w.syncFlags = sync_flags;
  45456. w.szPage = szPage;
  45457. iOffset = walFrameOffset(iFrame+1, szPage);
  45458. szFrame = szPage + WAL_FRAME_HDRSIZE;
  45459. /* Write all frames into the log file exactly once */
  45460. for(p=pList; p; p=p->pDirty){
  45461. int nDbSize; /* 0 normally. Positive == commit flag */
  45462. iFrame++;
  45463. assert( iOffset==walFrameOffset(iFrame, szPage) );
  45464. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  45465. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  45466. if( rc ) return rc;
  45467. pLast = p;
  45468. iOffset += szFrame;
  45469. }
  45470. /* If this is the end of a transaction, then we might need to pad
  45471. ** the transaction and/or sync the WAL file.
  45472. **
  45473. ** Padding and syncing only occur if this set of frames complete a
  45474. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  45475. ** or synchonous==OFF, then no padding or syncing are needed.
  45476. **
  45477. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  45478. ** needed and only the sync is done. If padding is needed, then the
  45479. ** final frame is repeated (with its commit mark) until the next sector
  45480. ** boundary is crossed. Only the part of the WAL prior to the last
  45481. ** sector boundary is synced; the part of the last frame that extends
  45482. ** past the sector boundary is written after the sync.
  45483. */
  45484. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  45485. if( pWal->padToSectorBoundary ){
  45486. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  45487. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  45488. while( iOffset<w.iSyncPoint ){
  45489. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  45490. if( rc ) return rc;
  45491. iOffset += szFrame;
  45492. nExtra++;
  45493. }
  45494. }else{
  45495. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  45496. }
  45497. }
  45498. /* If this frame set completes the first transaction in the WAL and
  45499. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  45500. ** journal size limit, if possible.
  45501. */
  45502. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  45503. i64 sz = pWal->mxWalSize;
  45504. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  45505. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  45506. }
  45507. walLimitSize(pWal, sz);
  45508. pWal->truncateOnCommit = 0;
  45509. }
  45510. /* Append data to the wal-index. It is not necessary to lock the
  45511. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  45512. ** guarantees that there are no other writers, and no data that may
  45513. ** be in use by existing readers is being overwritten.
  45514. */
  45515. iFrame = pWal->hdr.mxFrame;
  45516. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  45517. iFrame++;
  45518. rc = walIndexAppend(pWal, iFrame, p->pgno);
  45519. }
  45520. while( rc==SQLITE_OK && nExtra>0 ){
  45521. iFrame++;
  45522. nExtra--;
  45523. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  45524. }
  45525. if( rc==SQLITE_OK ){
  45526. /* Update the private copy of the header. */
  45527. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  45528. testcase( szPage<=32768 );
  45529. testcase( szPage>=65536 );
  45530. pWal->hdr.mxFrame = iFrame;
  45531. if( isCommit ){
  45532. pWal->hdr.iChange++;
  45533. pWal->hdr.nPage = nTruncate;
  45534. }
  45535. /* If this is a commit, update the wal-index header too. */
  45536. if( isCommit ){
  45537. walIndexWriteHdr(pWal);
  45538. pWal->iCallback = iFrame;
  45539. }
  45540. }
  45541. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  45542. return rc;
  45543. }
  45544. /*
  45545. ** This routine is called to implement sqlite3_wal_checkpoint() and
  45546. ** related interfaces.
  45547. **
  45548. ** Obtain a CHECKPOINT lock and then backfill as much information as
  45549. ** we can from WAL into the database.
  45550. **
  45551. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  45552. ** callback. In this case this function runs a blocking checkpoint.
  45553. */
  45554. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  45555. Wal *pWal, /* Wal connection */
  45556. int eMode, /* PASSIVE, FULL or RESTART */
  45557. int (*xBusy)(void*), /* Function to call when busy */
  45558. void *pBusyArg, /* Context argument for xBusyHandler */
  45559. int sync_flags, /* Flags to sync db file with (or 0) */
  45560. int nBuf, /* Size of temporary buffer */
  45561. u8 *zBuf, /* Temporary buffer to use */
  45562. int *pnLog, /* OUT: Number of frames in WAL */
  45563. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  45564. ){
  45565. int rc; /* Return code */
  45566. int isChanged = 0; /* True if a new wal-index header is loaded */
  45567. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  45568. assert( pWal->ckptLock==0 );
  45569. assert( pWal->writeLock==0 );
  45570. if( pWal->readOnly ) return SQLITE_READONLY;
  45571. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  45572. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  45573. if( rc ){
  45574. /* Usually this is SQLITE_BUSY meaning that another thread or process
  45575. ** is already running a checkpoint, or maybe a recovery. But it might
  45576. ** also be SQLITE_IOERR. */
  45577. return rc;
  45578. }
  45579. pWal->ckptLock = 1;
  45580. /* If this is a blocking-checkpoint, then obtain the write-lock as well
  45581. ** to prevent any writers from running while the checkpoint is underway.
  45582. ** This has to be done before the call to walIndexReadHdr() below.
  45583. **
  45584. ** If the writer lock cannot be obtained, then a passive checkpoint is
  45585. ** run instead. Since the checkpointer is not holding the writer lock,
  45586. ** there is no point in blocking waiting for any readers. Assuming no
  45587. ** other error occurs, this function will return SQLITE_BUSY to the caller.
  45588. */
  45589. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  45590. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  45591. if( rc==SQLITE_OK ){
  45592. pWal->writeLock = 1;
  45593. }else if( rc==SQLITE_BUSY ){
  45594. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  45595. rc = SQLITE_OK;
  45596. }
  45597. }
  45598. /* Read the wal-index header. */
  45599. if( rc==SQLITE_OK ){
  45600. rc = walIndexReadHdr(pWal, &isChanged);
  45601. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  45602. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  45603. }
  45604. }
  45605. /* Copy data from the log to the database file. */
  45606. if( rc==SQLITE_OK ){
  45607. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  45608. rc = SQLITE_CORRUPT_BKPT;
  45609. }else{
  45610. rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
  45611. }
  45612. /* If no error occurred, set the output variables. */
  45613. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  45614. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  45615. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  45616. }
  45617. }
  45618. if( isChanged ){
  45619. /* If a new wal-index header was loaded before the checkpoint was
  45620. ** performed, then the pager-cache associated with pWal is now
  45621. ** out of date. So zero the cached wal-index header to ensure that
  45622. ** next time the pager opens a snapshot on this database it knows that
  45623. ** the cache needs to be reset.
  45624. */
  45625. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  45626. }
  45627. /* Release the locks. */
  45628. sqlite3WalEndWriteTransaction(pWal);
  45629. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  45630. pWal->ckptLock = 0;
  45631. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  45632. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  45633. }
  45634. /* Return the value to pass to a sqlite3_wal_hook callback, the
  45635. ** number of frames in the WAL at the point of the last commit since
  45636. ** sqlite3WalCallback() was called. If no commits have occurred since
  45637. ** the last call, then return 0.
  45638. */
  45639. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  45640. u32 ret = 0;
  45641. if( pWal ){
  45642. ret = pWal->iCallback;
  45643. pWal->iCallback = 0;
  45644. }
  45645. return (int)ret;
  45646. }
  45647. /*
  45648. ** This function is called to change the WAL subsystem into or out
  45649. ** of locking_mode=EXCLUSIVE.
  45650. **
  45651. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  45652. ** into locking_mode=NORMAL. This means that we must acquire a lock
  45653. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  45654. ** or if the acquisition of the lock fails, then return 0. If the
  45655. ** transition out of exclusive-mode is successful, return 1. This
  45656. ** operation must occur while the pager is still holding the exclusive
  45657. ** lock on the main database file.
  45658. **
  45659. ** If op is one, then change from locking_mode=NORMAL into
  45660. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  45661. ** be released. Return 1 if the transition is made and 0 if the
  45662. ** WAL is already in exclusive-locking mode - meaning that this
  45663. ** routine is a no-op. The pager must already hold the exclusive lock
  45664. ** on the main database file before invoking this operation.
  45665. **
  45666. ** If op is negative, then do a dry-run of the op==1 case but do
  45667. ** not actually change anything. The pager uses this to see if it
  45668. ** should acquire the database exclusive lock prior to invoking
  45669. ** the op==1 case.
  45670. */
  45671. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  45672. int rc;
  45673. assert( pWal->writeLock==0 );
  45674. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  45675. /* pWal->readLock is usually set, but might be -1 if there was a
  45676. ** prior error while attempting to acquire are read-lock. This cannot
  45677. ** happen if the connection is actually in exclusive mode (as no xShmLock
  45678. ** locks are taken in this case). Nor should the pager attempt to
  45679. ** upgrade to exclusive-mode following such an error.
  45680. */
  45681. assert( pWal->readLock>=0 || pWal->lockError );
  45682. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  45683. if( op==0 ){
  45684. if( pWal->exclusiveMode ){
  45685. pWal->exclusiveMode = 0;
  45686. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  45687. pWal->exclusiveMode = 1;
  45688. }
  45689. rc = pWal->exclusiveMode==0;
  45690. }else{
  45691. /* Already in locking_mode=NORMAL */
  45692. rc = 0;
  45693. }
  45694. }else if( op>0 ){
  45695. assert( pWal->exclusiveMode==0 );
  45696. assert( pWal->readLock>=0 );
  45697. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  45698. pWal->exclusiveMode = 1;
  45699. rc = 1;
  45700. }else{
  45701. rc = pWal->exclusiveMode==0;
  45702. }
  45703. return rc;
  45704. }
  45705. /*
  45706. ** Return true if the argument is non-NULL and the WAL module is using
  45707. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  45708. ** WAL module is using shared-memory, return false.
  45709. */
  45710. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  45711. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  45712. }
  45713. #ifdef SQLITE_ENABLE_ZIPVFS
  45714. /*
  45715. ** If the argument is not NULL, it points to a Wal object that holds a
  45716. ** read-lock. This function returns the database page-size if it is known,
  45717. ** or zero if it is not (or if pWal is NULL).
  45718. */
  45719. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  45720. assert( pWal==0 || pWal->readLock>=0 );
  45721. return (pWal ? pWal->szPage : 0);
  45722. }
  45723. #endif
  45724. #endif /* #ifndef SQLITE_OMIT_WAL */
  45725. /************** End of wal.c *************************************************/
  45726. /************** Begin file btmutex.c *****************************************/
  45727. /*
  45728. ** 2007 August 27
  45729. **
  45730. ** The author disclaims copyright to this source code. In place of
  45731. ** a legal notice, here is a blessing:
  45732. **
  45733. ** May you do good and not evil.
  45734. ** May you find forgiveness for yourself and forgive others.
  45735. ** May you share freely, never taking more than you give.
  45736. **
  45737. *************************************************************************
  45738. **
  45739. ** This file contains code used to implement mutexes on Btree objects.
  45740. ** This code really belongs in btree.c. But btree.c is getting too
  45741. ** big and we want to break it down some. This packaged seemed like
  45742. ** a good breakout.
  45743. */
  45744. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  45745. /************** Begin file btreeInt.h ****************************************/
  45746. /*
  45747. ** 2004 April 6
  45748. **
  45749. ** The author disclaims copyright to this source code. In place of
  45750. ** a legal notice, here is a blessing:
  45751. **
  45752. ** May you do good and not evil.
  45753. ** May you find forgiveness for yourself and forgive others.
  45754. ** May you share freely, never taking more than you give.
  45755. **
  45756. *************************************************************************
  45757. ** This file implements a external (disk-based) database using BTrees.
  45758. ** For a detailed discussion of BTrees, refer to
  45759. **
  45760. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  45761. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  45762. ** Publishing Company, Reading, Massachusetts.
  45763. **
  45764. ** The basic idea is that each page of the file contains N database
  45765. ** entries and N+1 pointers to subpages.
  45766. **
  45767. ** ----------------------------------------------------------------
  45768. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  45769. ** ----------------------------------------------------------------
  45770. **
  45771. ** All of the keys on the page that Ptr(0) points to have values less
  45772. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  45773. ** values greater than Key(0) and less than Key(1). All of the keys
  45774. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  45775. ** so forth.
  45776. **
  45777. ** Finding a particular key requires reading O(log(M)) pages from the
  45778. ** disk where M is the number of entries in the tree.
  45779. **
  45780. ** In this implementation, a single file can hold one or more separate
  45781. ** BTrees. Each BTree is identified by the index of its root page. The
  45782. ** key and data for any entry are combined to form the "payload". A
  45783. ** fixed amount of payload can be carried directly on the database
  45784. ** page. If the payload is larger than the preset amount then surplus
  45785. ** bytes are stored on overflow pages. The payload for an entry
  45786. ** and the preceding pointer are combined to form a "Cell". Each
  45787. ** page has a small header which contains the Ptr(N) pointer and other
  45788. ** information such as the size of key and data.
  45789. **
  45790. ** FORMAT DETAILS
  45791. **
  45792. ** The file is divided into pages. The first page is called page 1,
  45793. ** the second is page 2, and so forth. A page number of zero indicates
  45794. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  45795. ** Each page can be either a btree page, a freelist page, an overflow
  45796. ** page, or a pointer-map page.
  45797. **
  45798. ** The first page is always a btree page. The first 100 bytes of the first
  45799. ** page contain a special header (the "file header") that describes the file.
  45800. ** The format of the file header is as follows:
  45801. **
  45802. ** OFFSET SIZE DESCRIPTION
  45803. ** 0 16 Header string: "SQLite format 3\000"
  45804. ** 16 2 Page size in bytes. (1 means 65536)
  45805. ** 18 1 File format write version
  45806. ** 19 1 File format read version
  45807. ** 20 1 Bytes of unused space at the end of each page
  45808. ** 21 1 Max embedded payload fraction (must be 64)
  45809. ** 22 1 Min embedded payload fraction (must be 32)
  45810. ** 23 1 Min leaf payload fraction (must be 32)
  45811. ** 24 4 File change counter
  45812. ** 28 4 Reserved for future use
  45813. ** 32 4 First freelist page
  45814. ** 36 4 Number of freelist pages in the file
  45815. ** 40 60 15 4-byte meta values passed to higher layers
  45816. **
  45817. ** 40 4 Schema cookie
  45818. ** 44 4 File format of schema layer
  45819. ** 48 4 Size of page cache
  45820. ** 52 4 Largest root-page (auto/incr_vacuum)
  45821. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  45822. ** 60 4 User version
  45823. ** 64 4 Incremental vacuum mode
  45824. ** 68 4 Application-ID
  45825. ** 72 20 unused
  45826. ** 92 4 The version-valid-for number
  45827. ** 96 4 SQLITE_VERSION_NUMBER
  45828. **
  45829. ** All of the integer values are big-endian (most significant byte first).
  45830. **
  45831. ** The file change counter is incremented when the database is changed
  45832. ** This counter allows other processes to know when the file has changed
  45833. ** and thus when they need to flush their cache.
  45834. **
  45835. ** The max embedded payload fraction is the amount of the total usable
  45836. ** space in a page that can be consumed by a single cell for standard
  45837. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  45838. ** is to limit the maximum cell size so that at least 4 cells will fit
  45839. ** on one page. Thus the default max embedded payload fraction is 64.
  45840. **
  45841. ** If the payload for a cell is larger than the max payload, then extra
  45842. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  45843. ** as many bytes as possible are moved into the overflow pages without letting
  45844. ** the cell size drop below the min embedded payload fraction.
  45845. **
  45846. ** The min leaf payload fraction is like the min embedded payload fraction
  45847. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  45848. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  45849. ** not specified in the header.
  45850. **
  45851. ** Each btree pages is divided into three sections: The header, the
  45852. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  45853. ** file header that occurs before the page header.
  45854. **
  45855. ** |----------------|
  45856. ** | file header | 100 bytes. Page 1 only.
  45857. ** |----------------|
  45858. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  45859. ** |----------------|
  45860. ** | cell pointer | | 2 bytes per cell. Sorted order.
  45861. ** | array | | Grows downward
  45862. ** | | v
  45863. ** |----------------|
  45864. ** | unallocated |
  45865. ** | space |
  45866. ** |----------------| ^ Grows upwards
  45867. ** | cell content | | Arbitrary order interspersed with freeblocks.
  45868. ** | area | | and free space fragments.
  45869. ** |----------------|
  45870. **
  45871. ** The page headers looks like this:
  45872. **
  45873. ** OFFSET SIZE DESCRIPTION
  45874. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  45875. ** 1 2 byte offset to the first freeblock
  45876. ** 3 2 number of cells on this page
  45877. ** 5 2 first byte of the cell content area
  45878. ** 7 1 number of fragmented free bytes
  45879. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  45880. **
  45881. ** The flags define the format of this btree page. The leaf flag means that
  45882. ** this page has no children. The zerodata flag means that this page carries
  45883. ** only keys and no data. The intkey flag means that the key is a integer
  45884. ** which is stored in the key size entry of the cell header rather than in
  45885. ** the payload area.
  45886. **
  45887. ** The cell pointer array begins on the first byte after the page header.
  45888. ** The cell pointer array contains zero or more 2-byte numbers which are
  45889. ** offsets from the beginning of the page to the cell content in the cell
  45890. ** content area. The cell pointers occur in sorted order. The system strives
  45891. ** to keep free space after the last cell pointer so that new cells can
  45892. ** be easily added without having to defragment the page.
  45893. **
  45894. ** Cell content is stored at the very end of the page and grows toward the
  45895. ** beginning of the page.
  45896. **
  45897. ** Unused space within the cell content area is collected into a linked list of
  45898. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  45899. ** to the first freeblock is given in the header. Freeblocks occur in
  45900. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  45901. ** any group of 3 or fewer unused bytes in the cell content area cannot
  45902. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  45903. ** a fragment. The total number of bytes in all fragments is recorded.
  45904. ** in the page header at offset 7.
  45905. **
  45906. ** SIZE DESCRIPTION
  45907. ** 2 Byte offset of the next freeblock
  45908. ** 2 Bytes in this freeblock
  45909. **
  45910. ** Cells are of variable length. Cells are stored in the cell content area at
  45911. ** the end of the page. Pointers to the cells are in the cell pointer array
  45912. ** that immediately follows the page header. Cells is not necessarily
  45913. ** contiguous or in order, but cell pointers are contiguous and in order.
  45914. **
  45915. ** Cell content makes use of variable length integers. A variable
  45916. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  45917. ** byte are used. The integer consists of all bytes that have bit 8 set and
  45918. ** the first byte with bit 8 clear. The most significant byte of the integer
  45919. ** appears first. A variable-length integer may not be more than 9 bytes long.
  45920. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  45921. ** allows a 64-bit integer to be encoded in 9 bytes.
  45922. **
  45923. ** 0x00 becomes 0x00000000
  45924. ** 0x7f becomes 0x0000007f
  45925. ** 0x81 0x00 becomes 0x00000080
  45926. ** 0x82 0x00 becomes 0x00000100
  45927. ** 0x80 0x7f becomes 0x0000007f
  45928. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  45929. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  45930. **
  45931. ** Variable length integers are used for rowids and to hold the number of
  45932. ** bytes of key and data in a btree cell.
  45933. **
  45934. ** The content of a cell looks like this:
  45935. **
  45936. ** SIZE DESCRIPTION
  45937. ** 4 Page number of the left child. Omitted if leaf flag is set.
  45938. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  45939. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  45940. ** * Payload
  45941. ** 4 First page of the overflow chain. Omitted if no overflow
  45942. **
  45943. ** Overflow pages form a linked list. Each page except the last is completely
  45944. ** filled with data (pagesize - 4 bytes). The last page can have as little
  45945. ** as 1 byte of data.
  45946. **
  45947. ** SIZE DESCRIPTION
  45948. ** 4 Page number of next overflow page
  45949. ** * Data
  45950. **
  45951. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  45952. ** file header points to the first in a linked list of trunk page. Each trunk
  45953. ** page points to multiple leaf pages. The content of a leaf page is
  45954. ** unspecified. A trunk page looks like this:
  45955. **
  45956. ** SIZE DESCRIPTION
  45957. ** 4 Page number of next trunk page
  45958. ** 4 Number of leaf pointers on this page
  45959. ** * zero or more pages numbers of leaves
  45960. */
  45961. /* The following value is the maximum cell size assuming a maximum page
  45962. ** size give above.
  45963. */
  45964. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  45965. /* The maximum number of cells on a single page of the database. This
  45966. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  45967. ** plus 2 bytes for the index to the cell in the page header). Such
  45968. ** small cells will be rare, but they are possible.
  45969. */
  45970. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  45971. /* Forward declarations */
  45972. typedef struct MemPage MemPage;
  45973. typedef struct BtLock BtLock;
  45974. /*
  45975. ** This is a magic string that appears at the beginning of every
  45976. ** SQLite database in order to identify the file as a real database.
  45977. **
  45978. ** You can change this value at compile-time by specifying a
  45979. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  45980. ** header must be exactly 16 bytes including the zero-terminator so
  45981. ** the string itself should be 15 characters long. If you change
  45982. ** the header, then your custom library will not be able to read
  45983. ** databases generated by the standard tools and the standard tools
  45984. ** will not be able to read databases created by your custom library.
  45985. */
  45986. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  45987. # define SQLITE_FILE_HEADER "SQLite format 3"
  45988. #endif
  45989. /*
  45990. ** Page type flags. An ORed combination of these flags appear as the
  45991. ** first byte of on-disk image of every BTree page.
  45992. */
  45993. #define PTF_INTKEY 0x01
  45994. #define PTF_ZERODATA 0x02
  45995. #define PTF_LEAFDATA 0x04
  45996. #define PTF_LEAF 0x08
  45997. /*
  45998. ** As each page of the file is loaded into memory, an instance of the following
  45999. ** structure is appended and initialized to zero. This structure stores
  46000. ** information about the page that is decoded from the raw file page.
  46001. **
  46002. ** The pParent field points back to the parent page. This allows us to
  46003. ** walk up the BTree from any leaf to the root. Care must be taken to
  46004. ** unref() the parent page pointer when this page is no longer referenced.
  46005. ** The pageDestructor() routine handles that chore.
  46006. **
  46007. ** Access to all fields of this structure is controlled by the mutex
  46008. ** stored in MemPage.pBt->mutex.
  46009. */
  46010. struct MemPage {
  46011. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  46012. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  46013. u8 intKey; /* True if intkey flag is set */
  46014. u8 leaf; /* True if leaf flag is set */
  46015. u8 hasData; /* True if this page stores data */
  46016. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  46017. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  46018. u8 max1bytePayload; /* min(maxLocal,127) */
  46019. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  46020. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  46021. u16 cellOffset; /* Index in aData of first cell pointer */
  46022. u16 nFree; /* Number of free bytes on the page */
  46023. u16 nCell; /* Number of cells on this page, local and ovfl */
  46024. u16 maskPage; /* Mask for page offset */
  46025. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  46026. ** non-overflow cell */
  46027. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  46028. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  46029. u8 *aData; /* Pointer to disk image of the page data */
  46030. u8 *aDataEnd; /* One byte past the end of usable data */
  46031. u8 *aCellIdx; /* The cell index area */
  46032. DbPage *pDbPage; /* Pager page handle */
  46033. Pgno pgno; /* Page number for this page */
  46034. };
  46035. /*
  46036. ** The in-memory image of a disk page has the auxiliary information appended
  46037. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  46038. ** that extra information.
  46039. */
  46040. #define EXTRA_SIZE sizeof(MemPage)
  46041. /*
  46042. ** A linked list of the following structures is stored at BtShared.pLock.
  46043. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  46044. ** is opened on the table with root page BtShared.iTable. Locks are removed
  46045. ** from this list when a transaction is committed or rolled back, or when
  46046. ** a btree handle is closed.
  46047. */
  46048. struct BtLock {
  46049. Btree *pBtree; /* Btree handle holding this lock */
  46050. Pgno iTable; /* Root page of table */
  46051. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  46052. BtLock *pNext; /* Next in BtShared.pLock list */
  46053. };
  46054. /* Candidate values for BtLock.eLock */
  46055. #define READ_LOCK 1
  46056. #define WRITE_LOCK 2
  46057. /* A Btree handle
  46058. **
  46059. ** A database connection contains a pointer to an instance of
  46060. ** this object for every database file that it has open. This structure
  46061. ** is opaque to the database connection. The database connection cannot
  46062. ** see the internals of this structure and only deals with pointers to
  46063. ** this structure.
  46064. **
  46065. ** For some database files, the same underlying database cache might be
  46066. ** shared between multiple connections. In that case, each connection
  46067. ** has it own instance of this object. But each instance of this object
  46068. ** points to the same BtShared object. The database cache and the
  46069. ** schema associated with the database file are all contained within
  46070. ** the BtShared object.
  46071. **
  46072. ** All fields in this structure are accessed under sqlite3.mutex.
  46073. ** The pBt pointer itself may not be changed while there exists cursors
  46074. ** in the referenced BtShared that point back to this Btree since those
  46075. ** cursors have to go through this Btree to find their BtShared and
  46076. ** they often do so without holding sqlite3.mutex.
  46077. */
  46078. struct Btree {
  46079. sqlite3 *db; /* The database connection holding this btree */
  46080. BtShared *pBt; /* Sharable content of this btree */
  46081. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  46082. u8 sharable; /* True if we can share pBt with another db */
  46083. u8 locked; /* True if db currently has pBt locked */
  46084. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  46085. int nBackup; /* Number of backup operations reading this btree */
  46086. Btree *pNext; /* List of other sharable Btrees from the same db */
  46087. Btree *pPrev; /* Back pointer of the same list */
  46088. #ifndef SQLITE_OMIT_SHARED_CACHE
  46089. BtLock lock; /* Object used to lock page 1 */
  46090. #endif
  46091. };
  46092. /*
  46093. ** Btree.inTrans may take one of the following values.
  46094. **
  46095. ** If the shared-data extension is enabled, there may be multiple users
  46096. ** of the Btree structure. At most one of these may open a write transaction,
  46097. ** but any number may have active read transactions.
  46098. */
  46099. #define TRANS_NONE 0
  46100. #define TRANS_READ 1
  46101. #define TRANS_WRITE 2
  46102. /*
  46103. ** An instance of this object represents a single database file.
  46104. **
  46105. ** A single database file can be in use at the same time by two
  46106. ** or more database connections. When two or more connections are
  46107. ** sharing the same database file, each connection has it own
  46108. ** private Btree object for the file and each of those Btrees points
  46109. ** to this one BtShared object. BtShared.nRef is the number of
  46110. ** connections currently sharing this database file.
  46111. **
  46112. ** Fields in this structure are accessed under the BtShared.mutex
  46113. ** mutex, except for nRef and pNext which are accessed under the
  46114. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  46115. ** may not be modified once it is initially set as long as nRef>0.
  46116. ** The pSchema field may be set once under BtShared.mutex and
  46117. ** thereafter is unchanged as long as nRef>0.
  46118. **
  46119. ** isPending:
  46120. **
  46121. ** If a BtShared client fails to obtain a write-lock on a database
  46122. ** table (because there exists one or more read-locks on the table),
  46123. ** the shared-cache enters 'pending-lock' state and isPending is
  46124. ** set to true.
  46125. **
  46126. ** The shared-cache leaves the 'pending lock' state when either of
  46127. ** the following occur:
  46128. **
  46129. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  46130. ** 2) The number of locks held by other connections drops to zero.
  46131. **
  46132. ** while in the 'pending-lock' state, no connection may start a new
  46133. ** transaction.
  46134. **
  46135. ** This feature is included to help prevent writer-starvation.
  46136. */
  46137. struct BtShared {
  46138. Pager *pPager; /* The page cache */
  46139. sqlite3 *db; /* Database connection currently using this Btree */
  46140. BtCursor *pCursor; /* A list of all open cursors */
  46141. MemPage *pPage1; /* First page of the database */
  46142. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  46143. #ifndef SQLITE_OMIT_AUTOVACUUM
  46144. u8 autoVacuum; /* True if auto-vacuum is enabled */
  46145. u8 incrVacuum; /* True if incr-vacuum is enabled */
  46146. u8 bDoTruncate; /* True to truncate db on commit */
  46147. #endif
  46148. u8 inTransaction; /* Transaction state */
  46149. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  46150. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  46151. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  46152. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  46153. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  46154. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  46155. u32 pageSize; /* Total number of bytes on a page */
  46156. u32 usableSize; /* Number of usable bytes on each page */
  46157. int nTransaction; /* Number of open transactions (read + write) */
  46158. u32 nPage; /* Number of pages in the database */
  46159. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  46160. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  46161. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  46162. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  46163. #ifndef SQLITE_OMIT_SHARED_CACHE
  46164. int nRef; /* Number of references to this structure */
  46165. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  46166. BtLock *pLock; /* List of locks held on this shared-btree struct */
  46167. Btree *pWriter; /* Btree with currently open write transaction */
  46168. #endif
  46169. u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
  46170. };
  46171. /*
  46172. ** Allowed values for BtShared.btsFlags
  46173. */
  46174. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  46175. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  46176. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  46177. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  46178. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  46179. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  46180. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  46181. /*
  46182. ** An instance of the following structure is used to hold information
  46183. ** about a cell. The parseCellPtr() function fills in this structure
  46184. ** based on information extract from the raw disk page.
  46185. */
  46186. typedef struct CellInfo CellInfo;
  46187. struct CellInfo {
  46188. i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
  46189. u8 *pCell; /* Pointer to the start of cell content */
  46190. u32 nData; /* Number of bytes of data */
  46191. u32 nPayload; /* Total amount of payload */
  46192. u16 nHeader; /* Size of the cell content header in bytes */
  46193. u16 nLocal; /* Amount of payload held locally */
  46194. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  46195. u16 nSize; /* Size of the cell content on the main b-tree page */
  46196. };
  46197. /*
  46198. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  46199. ** this will be declared corrupt. This value is calculated based on a
  46200. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  46201. ** root-node and 3 for all other internal nodes.
  46202. **
  46203. ** If a tree that appears to be taller than this is encountered, it is
  46204. ** assumed that the database is corrupt.
  46205. */
  46206. #define BTCURSOR_MAX_DEPTH 20
  46207. /*
  46208. ** A cursor is a pointer to a particular entry within a particular
  46209. ** b-tree within a database file.
  46210. **
  46211. ** The entry is identified by its MemPage and the index in
  46212. ** MemPage.aCell[] of the entry.
  46213. **
  46214. ** A single database file can be shared by two more database connections,
  46215. ** but cursors cannot be shared. Each cursor is associated with a
  46216. ** particular database connection identified BtCursor.pBtree.db.
  46217. **
  46218. ** Fields in this structure are accessed under the BtShared.mutex
  46219. ** found at self->pBt->mutex.
  46220. */
  46221. struct BtCursor {
  46222. Btree *pBtree; /* The Btree to which this cursor belongs */
  46223. BtShared *pBt; /* The BtShared this cursor points to */
  46224. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  46225. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  46226. #ifndef SQLITE_OMIT_INCRBLOB
  46227. Pgno *aOverflow; /* Cache of overflow page locations */
  46228. #endif
  46229. Pgno pgnoRoot; /* The root page of this tree */
  46230. sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
  46231. CellInfo info; /* A parse of the cell we are pointing at */
  46232. i64 nKey; /* Size of pKey, or last integer key */
  46233. void *pKey; /* Saved key that was cursor's last known position */
  46234. int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
  46235. u8 wrFlag; /* True if writable */
  46236. u8 atLast; /* Cursor pointing to the last entry */
  46237. u8 validNKey; /* True if info.nKey is valid */
  46238. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  46239. #ifndef SQLITE_OMIT_INCRBLOB
  46240. u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
  46241. #endif
  46242. u8 hints; /* As configured by CursorSetHints() */
  46243. i16 iPage; /* Index of current page in apPage */
  46244. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  46245. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  46246. };
  46247. /*
  46248. ** Potential values for BtCursor.eState.
  46249. **
  46250. ** CURSOR_INVALID:
  46251. ** Cursor does not point to a valid entry. This can happen (for example)
  46252. ** because the table is empty or because BtreeCursorFirst() has not been
  46253. ** called.
  46254. **
  46255. ** CURSOR_VALID:
  46256. ** Cursor points to a valid entry. getPayload() etc. may be called.
  46257. **
  46258. ** CURSOR_SKIPNEXT:
  46259. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  46260. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  46261. ** operation should be a no-op.
  46262. **
  46263. ** CURSOR_REQUIRESEEK:
  46264. ** The table that this cursor was opened on still exists, but has been
  46265. ** modified since the cursor was last used. The cursor position is saved
  46266. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  46267. ** this state, restoreCursorPosition() can be called to attempt to
  46268. ** seek the cursor to the saved position.
  46269. **
  46270. ** CURSOR_FAULT:
  46271. ** A unrecoverable error (an I/O error or a malloc failure) has occurred
  46272. ** on a different connection that shares the BtShared cache with this
  46273. ** cursor. The error has left the cache in an inconsistent state.
  46274. ** Do nothing else with this cursor. Any attempt to use the cursor
  46275. ** should return the error code stored in BtCursor.skip
  46276. */
  46277. #define CURSOR_INVALID 0
  46278. #define CURSOR_VALID 1
  46279. #define CURSOR_SKIPNEXT 2
  46280. #define CURSOR_REQUIRESEEK 3
  46281. #define CURSOR_FAULT 4
  46282. /*
  46283. ** The database page the PENDING_BYTE occupies. This page is never used.
  46284. */
  46285. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  46286. /*
  46287. ** These macros define the location of the pointer-map entry for a
  46288. ** database page. The first argument to each is the number of usable
  46289. ** bytes on each page of the database (often 1024). The second is the
  46290. ** page number to look up in the pointer map.
  46291. **
  46292. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  46293. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  46294. ** the offset of the requested map entry.
  46295. **
  46296. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  46297. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  46298. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  46299. ** this test.
  46300. */
  46301. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  46302. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  46303. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  46304. /*
  46305. ** The pointer map is a lookup table that identifies the parent page for
  46306. ** each child page in the database file. The parent page is the page that
  46307. ** contains a pointer to the child. Every page in the database contains
  46308. ** 0 or 1 parent pages. (In this context 'database page' refers
  46309. ** to any page that is not part of the pointer map itself.) Each pointer map
  46310. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  46311. ** The PTRMAP_XXX identifiers below are the valid types.
  46312. **
  46313. ** The purpose of the pointer map is to facility moving pages from one
  46314. ** position in the file to another as part of autovacuum. When a page
  46315. ** is moved, the pointer in its parent must be updated to point to the
  46316. ** new location. The pointer map is used to locate the parent page quickly.
  46317. **
  46318. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  46319. ** used in this case.
  46320. **
  46321. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  46322. ** is not used in this case.
  46323. **
  46324. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  46325. ** overflow pages. The page number identifies the page that
  46326. ** contains the cell with a pointer to this overflow page.
  46327. **
  46328. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  46329. ** overflow pages. The page-number identifies the previous
  46330. ** page in the overflow page list.
  46331. **
  46332. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  46333. ** identifies the parent page in the btree.
  46334. */
  46335. #define PTRMAP_ROOTPAGE 1
  46336. #define PTRMAP_FREEPAGE 2
  46337. #define PTRMAP_OVERFLOW1 3
  46338. #define PTRMAP_OVERFLOW2 4
  46339. #define PTRMAP_BTREE 5
  46340. /* A bunch of assert() statements to check the transaction state variables
  46341. ** of handle p (type Btree*) are internally consistent.
  46342. */
  46343. #define btreeIntegrity(p) \
  46344. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  46345. assert( p->pBt->inTransaction>=p->inTrans );
  46346. /*
  46347. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  46348. ** if the database supports auto-vacuum or not. Because it is used
  46349. ** within an expression that is an argument to another macro
  46350. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  46351. ** So, this macro is defined instead.
  46352. */
  46353. #ifndef SQLITE_OMIT_AUTOVACUUM
  46354. #define ISAUTOVACUUM (pBt->autoVacuum)
  46355. #else
  46356. #define ISAUTOVACUUM 0
  46357. #endif
  46358. /*
  46359. ** This structure is passed around through all the sanity checking routines
  46360. ** in order to keep track of some global state information.
  46361. **
  46362. ** The aRef[] array is allocated so that there is 1 bit for each page in
  46363. ** the database. As the integrity-check proceeds, for each page used in
  46364. ** the database the corresponding bit is set. This allows integrity-check to
  46365. ** detect pages that are used twice and orphaned pages (both of which
  46366. ** indicate corruption).
  46367. */
  46368. typedef struct IntegrityCk IntegrityCk;
  46369. struct IntegrityCk {
  46370. BtShared *pBt; /* The tree being checked out */
  46371. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  46372. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  46373. Pgno nPage; /* Number of pages in the database */
  46374. int mxErr; /* Stop accumulating errors when this reaches zero */
  46375. int nErr; /* Number of messages written to zErrMsg so far */
  46376. int mallocFailed; /* A memory allocation error has occurred */
  46377. StrAccum errMsg; /* Accumulate the error message text here */
  46378. };
  46379. /*
  46380. ** Routines to read or write a two- and four-byte big-endian integer values.
  46381. */
  46382. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  46383. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  46384. #define get4byte sqlite3Get4byte
  46385. #define put4byte sqlite3Put4byte
  46386. /************** End of btreeInt.h ********************************************/
  46387. /************** Continuing where we left off in btmutex.c ********************/
  46388. #ifndef SQLITE_OMIT_SHARED_CACHE
  46389. #if SQLITE_THREADSAFE
  46390. /*
  46391. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  46392. ** set BtShared.db to the database handle associated with p and the
  46393. ** p->locked boolean to true.
  46394. */
  46395. static void lockBtreeMutex(Btree *p){
  46396. assert( p->locked==0 );
  46397. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  46398. assert( sqlite3_mutex_held(p->db->mutex) );
  46399. sqlite3_mutex_enter(p->pBt->mutex);
  46400. p->pBt->db = p->db;
  46401. p->locked = 1;
  46402. }
  46403. /*
  46404. ** Release the BtShared mutex associated with B-Tree handle p and
  46405. ** clear the p->locked boolean.
  46406. */
  46407. static void unlockBtreeMutex(Btree *p){
  46408. BtShared *pBt = p->pBt;
  46409. assert( p->locked==1 );
  46410. assert( sqlite3_mutex_held(pBt->mutex) );
  46411. assert( sqlite3_mutex_held(p->db->mutex) );
  46412. assert( p->db==pBt->db );
  46413. sqlite3_mutex_leave(pBt->mutex);
  46414. p->locked = 0;
  46415. }
  46416. /*
  46417. ** Enter a mutex on the given BTree object.
  46418. **
  46419. ** If the object is not sharable, then no mutex is ever required
  46420. ** and this routine is a no-op. The underlying mutex is non-recursive.
  46421. ** But we keep a reference count in Btree.wantToLock so the behavior
  46422. ** of this interface is recursive.
  46423. **
  46424. ** To avoid deadlocks, multiple Btrees are locked in the same order
  46425. ** by all database connections. The p->pNext is a list of other
  46426. ** Btrees belonging to the same database connection as the p Btree
  46427. ** which need to be locked after p. If we cannot get a lock on
  46428. ** p, then first unlock all of the others on p->pNext, then wait
  46429. ** for the lock to become available on p, then relock all of the
  46430. ** subsequent Btrees that desire a lock.
  46431. */
  46432. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  46433. Btree *pLater;
  46434. /* Some basic sanity checking on the Btree. The list of Btrees
  46435. ** connected by pNext and pPrev should be in sorted order by
  46436. ** Btree.pBt value. All elements of the list should belong to
  46437. ** the same connection. Only shared Btrees are on the list. */
  46438. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  46439. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  46440. assert( p->pNext==0 || p->pNext->db==p->db );
  46441. assert( p->pPrev==0 || p->pPrev->db==p->db );
  46442. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  46443. /* Check for locking consistency */
  46444. assert( !p->locked || p->wantToLock>0 );
  46445. assert( p->sharable || p->wantToLock==0 );
  46446. /* We should already hold a lock on the database connection */
  46447. assert( sqlite3_mutex_held(p->db->mutex) );
  46448. /* Unless the database is sharable and unlocked, then BtShared.db
  46449. ** should already be set correctly. */
  46450. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  46451. if( !p->sharable ) return;
  46452. p->wantToLock++;
  46453. if( p->locked ) return;
  46454. /* In most cases, we should be able to acquire the lock we
  46455. ** want without having to go throught the ascending lock
  46456. ** procedure that follows. Just be sure not to block.
  46457. */
  46458. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  46459. p->pBt->db = p->db;
  46460. p->locked = 1;
  46461. return;
  46462. }
  46463. /* To avoid deadlock, first release all locks with a larger
  46464. ** BtShared address. Then acquire our lock. Then reacquire
  46465. ** the other BtShared locks that we used to hold in ascending
  46466. ** order.
  46467. */
  46468. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  46469. assert( pLater->sharable );
  46470. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  46471. assert( !pLater->locked || pLater->wantToLock>0 );
  46472. if( pLater->locked ){
  46473. unlockBtreeMutex(pLater);
  46474. }
  46475. }
  46476. lockBtreeMutex(p);
  46477. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  46478. if( pLater->wantToLock ){
  46479. lockBtreeMutex(pLater);
  46480. }
  46481. }
  46482. }
  46483. /*
  46484. ** Exit the recursive mutex on a Btree.
  46485. */
  46486. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  46487. if( p->sharable ){
  46488. assert( p->wantToLock>0 );
  46489. p->wantToLock--;
  46490. if( p->wantToLock==0 ){
  46491. unlockBtreeMutex(p);
  46492. }
  46493. }
  46494. }
  46495. #ifndef NDEBUG
  46496. /*
  46497. ** Return true if the BtShared mutex is held on the btree, or if the
  46498. ** B-Tree is not marked as sharable.
  46499. **
  46500. ** This routine is used only from within assert() statements.
  46501. */
  46502. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  46503. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  46504. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  46505. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  46506. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  46507. return (p->sharable==0 || p->locked);
  46508. }
  46509. #endif
  46510. #ifndef SQLITE_OMIT_INCRBLOB
  46511. /*
  46512. ** Enter and leave a mutex on a Btree given a cursor owned by that
  46513. ** Btree. These entry points are used by incremental I/O and can be
  46514. ** omitted if that module is not used.
  46515. */
  46516. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  46517. sqlite3BtreeEnter(pCur->pBtree);
  46518. }
  46519. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  46520. sqlite3BtreeLeave(pCur->pBtree);
  46521. }
  46522. #endif /* SQLITE_OMIT_INCRBLOB */
  46523. /*
  46524. ** Enter the mutex on every Btree associated with a database
  46525. ** connection. This is needed (for example) prior to parsing
  46526. ** a statement since we will be comparing table and column names
  46527. ** against all schemas and we do not want those schemas being
  46528. ** reset out from under us.
  46529. **
  46530. ** There is a corresponding leave-all procedures.
  46531. **
  46532. ** Enter the mutexes in accending order by BtShared pointer address
  46533. ** to avoid the possibility of deadlock when two threads with
  46534. ** two or more btrees in common both try to lock all their btrees
  46535. ** at the same instant.
  46536. */
  46537. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  46538. int i;
  46539. Btree *p;
  46540. assert( sqlite3_mutex_held(db->mutex) );
  46541. for(i=0; i<db->nDb; i++){
  46542. p = db->aDb[i].pBt;
  46543. if( p ) sqlite3BtreeEnter(p);
  46544. }
  46545. }
  46546. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  46547. int i;
  46548. Btree *p;
  46549. assert( sqlite3_mutex_held(db->mutex) );
  46550. for(i=0; i<db->nDb; i++){
  46551. p = db->aDb[i].pBt;
  46552. if( p ) sqlite3BtreeLeave(p);
  46553. }
  46554. }
  46555. /*
  46556. ** Return true if a particular Btree requires a lock. Return FALSE if
  46557. ** no lock is ever required since it is not sharable.
  46558. */
  46559. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  46560. return p->sharable;
  46561. }
  46562. #ifndef NDEBUG
  46563. /*
  46564. ** Return true if the current thread holds the database connection
  46565. ** mutex and all required BtShared mutexes.
  46566. **
  46567. ** This routine is used inside assert() statements only.
  46568. */
  46569. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  46570. int i;
  46571. if( !sqlite3_mutex_held(db->mutex) ){
  46572. return 0;
  46573. }
  46574. for(i=0; i<db->nDb; i++){
  46575. Btree *p;
  46576. p = db->aDb[i].pBt;
  46577. if( p && p->sharable &&
  46578. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  46579. return 0;
  46580. }
  46581. }
  46582. return 1;
  46583. }
  46584. #endif /* NDEBUG */
  46585. #ifndef NDEBUG
  46586. /*
  46587. ** Return true if the correct mutexes are held for accessing the
  46588. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  46589. ** access are:
  46590. **
  46591. ** (1) The mutex on db
  46592. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  46593. **
  46594. ** If pSchema is not NULL, then iDb is computed from pSchema and
  46595. ** db using sqlite3SchemaToIndex().
  46596. */
  46597. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  46598. Btree *p;
  46599. assert( db!=0 );
  46600. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  46601. assert( iDb>=0 && iDb<db->nDb );
  46602. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  46603. if( iDb==1 ) return 1;
  46604. p = db->aDb[iDb].pBt;
  46605. assert( p!=0 );
  46606. return p->sharable==0 || p->locked==1;
  46607. }
  46608. #endif /* NDEBUG */
  46609. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  46610. /*
  46611. ** The following are special cases for mutex enter routines for use
  46612. ** in single threaded applications that use shared cache. Except for
  46613. ** these two routines, all mutex operations are no-ops in that case and
  46614. ** are null #defines in btree.h.
  46615. **
  46616. ** If shared cache is disabled, then all btree mutex routines, including
  46617. ** the ones below, are no-ops and are null #defines in btree.h.
  46618. */
  46619. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  46620. p->pBt->db = p->db;
  46621. }
  46622. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  46623. int i;
  46624. for(i=0; i<db->nDb; i++){
  46625. Btree *p = db->aDb[i].pBt;
  46626. if( p ){
  46627. p->pBt->db = p->db;
  46628. }
  46629. }
  46630. }
  46631. #endif /* if SQLITE_THREADSAFE */
  46632. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  46633. /************** End of btmutex.c *********************************************/
  46634. /************** Begin file btree.c *******************************************/
  46635. /*
  46636. ** 2004 April 6
  46637. **
  46638. ** The author disclaims copyright to this source code. In place of
  46639. ** a legal notice, here is a blessing:
  46640. **
  46641. ** May you do good and not evil.
  46642. ** May you find forgiveness for yourself and forgive others.
  46643. ** May you share freely, never taking more than you give.
  46644. **
  46645. *************************************************************************
  46646. ** This file implements a external (disk-based) database using BTrees.
  46647. ** See the header comment on "btreeInt.h" for additional information.
  46648. ** Including a description of file format and an overview of operation.
  46649. */
  46650. /*
  46651. ** The header string that appears at the beginning of every
  46652. ** SQLite database.
  46653. */
  46654. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  46655. /*
  46656. ** Set this global variable to 1 to enable tracing using the TRACE
  46657. ** macro.
  46658. */
  46659. #if 0
  46660. int sqlite3BtreeTrace=1; /* True to enable tracing */
  46661. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  46662. #else
  46663. # define TRACE(X)
  46664. #endif
  46665. /*
  46666. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  46667. ** But if the value is zero, make it 65536.
  46668. **
  46669. ** This routine is used to extract the "offset to cell content area" value
  46670. ** from the header of a btree page. If the page size is 65536 and the page
  46671. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  46672. ** This routine makes the necessary adjustment to 65536.
  46673. */
  46674. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  46675. /*
  46676. ** Values passed as the 5th argument to allocateBtreePage()
  46677. */
  46678. #define BTALLOC_ANY 0 /* Allocate any page */
  46679. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  46680. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  46681. /*
  46682. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  46683. ** defined, or 0 if it is. For example:
  46684. **
  46685. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  46686. */
  46687. #ifndef SQLITE_OMIT_AUTOVACUUM
  46688. #define IfNotOmitAV(expr) (expr)
  46689. #else
  46690. #define IfNotOmitAV(expr) 0
  46691. #endif
  46692. #ifndef SQLITE_OMIT_SHARED_CACHE
  46693. /*
  46694. ** A list of BtShared objects that are eligible for participation
  46695. ** in shared cache. This variable has file scope during normal builds,
  46696. ** but the test harness needs to access it so we make it global for
  46697. ** test builds.
  46698. **
  46699. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  46700. */
  46701. #ifdef SQLITE_TEST
  46702. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  46703. #else
  46704. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  46705. #endif
  46706. #endif /* SQLITE_OMIT_SHARED_CACHE */
  46707. #ifndef SQLITE_OMIT_SHARED_CACHE
  46708. /*
  46709. ** Enable or disable the shared pager and schema features.
  46710. **
  46711. ** This routine has no effect on existing database connections.
  46712. ** The shared cache setting effects only future calls to
  46713. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  46714. */
  46715. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  46716. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  46717. return SQLITE_OK;
  46718. }
  46719. #endif
  46720. #ifdef SQLITE_OMIT_SHARED_CACHE
  46721. /*
  46722. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  46723. ** and clearAllSharedCacheTableLocks()
  46724. ** manipulate entries in the BtShared.pLock linked list used to store
  46725. ** shared-cache table level locks. If the library is compiled with the
  46726. ** shared-cache feature disabled, then there is only ever one user
  46727. ** of each BtShared structure and so this locking is not necessary.
  46728. ** So define the lock related functions as no-ops.
  46729. */
  46730. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  46731. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  46732. #define clearAllSharedCacheTableLocks(a)
  46733. #define downgradeAllSharedCacheTableLocks(a)
  46734. #define hasSharedCacheTableLock(a,b,c,d) 1
  46735. #define hasReadConflicts(a, b) 0
  46736. #endif
  46737. #ifndef SQLITE_OMIT_SHARED_CACHE
  46738. #ifdef SQLITE_DEBUG
  46739. /*
  46740. **** This function is only used as part of an assert() statement. ***
  46741. **
  46742. ** Check to see if pBtree holds the required locks to read or write to the
  46743. ** table with root page iRoot. Return 1 if it does and 0 if not.
  46744. **
  46745. ** For example, when writing to a table with root-page iRoot via
  46746. ** Btree connection pBtree:
  46747. **
  46748. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  46749. **
  46750. ** When writing to an index that resides in a sharable database, the
  46751. ** caller should have first obtained a lock specifying the root page of
  46752. ** the corresponding table. This makes things a bit more complicated,
  46753. ** as this module treats each table as a separate structure. To determine
  46754. ** the table corresponding to the index being written, this
  46755. ** function has to search through the database schema.
  46756. **
  46757. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  46758. ** hold a write-lock on the schema table (root page 1). This is also
  46759. ** acceptable.
  46760. */
  46761. static int hasSharedCacheTableLock(
  46762. Btree *pBtree, /* Handle that must hold lock */
  46763. Pgno iRoot, /* Root page of b-tree */
  46764. int isIndex, /* True if iRoot is the root of an index b-tree */
  46765. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  46766. ){
  46767. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  46768. Pgno iTab = 0;
  46769. BtLock *pLock;
  46770. /* If this database is not shareable, or if the client is reading
  46771. ** and has the read-uncommitted flag set, then no lock is required.
  46772. ** Return true immediately.
  46773. */
  46774. if( (pBtree->sharable==0)
  46775. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  46776. ){
  46777. return 1;
  46778. }
  46779. /* If the client is reading or writing an index and the schema is
  46780. ** not loaded, then it is too difficult to actually check to see if
  46781. ** the correct locks are held. So do not bother - just return true.
  46782. ** This case does not come up very often anyhow.
  46783. */
  46784. if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
  46785. return 1;
  46786. }
  46787. /* Figure out the root-page that the lock should be held on. For table
  46788. ** b-trees, this is just the root page of the b-tree being read or
  46789. ** written. For index b-trees, it is the root page of the associated
  46790. ** table. */
  46791. if( isIndex ){
  46792. HashElem *p;
  46793. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  46794. Index *pIdx = (Index *)sqliteHashData(p);
  46795. if( pIdx->tnum==(int)iRoot ){
  46796. iTab = pIdx->pTable->tnum;
  46797. }
  46798. }
  46799. }else{
  46800. iTab = iRoot;
  46801. }
  46802. /* Search for the required lock. Either a write-lock on root-page iTab, a
  46803. ** write-lock on the schema table, or (if the client is reading) a
  46804. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  46805. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  46806. if( pLock->pBtree==pBtree
  46807. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  46808. && pLock->eLock>=eLockType
  46809. ){
  46810. return 1;
  46811. }
  46812. }
  46813. /* Failed to find the required lock. */
  46814. return 0;
  46815. }
  46816. #endif /* SQLITE_DEBUG */
  46817. #ifdef SQLITE_DEBUG
  46818. /*
  46819. **** This function may be used as part of assert() statements only. ****
  46820. **
  46821. ** Return true if it would be illegal for pBtree to write into the
  46822. ** table or index rooted at iRoot because other shared connections are
  46823. ** simultaneously reading that same table or index.
  46824. **
  46825. ** It is illegal for pBtree to write if some other Btree object that
  46826. ** shares the same BtShared object is currently reading or writing
  46827. ** the iRoot table. Except, if the other Btree object has the
  46828. ** read-uncommitted flag set, then it is OK for the other object to
  46829. ** have a read cursor.
  46830. **
  46831. ** For example, before writing to any part of the table or index
  46832. ** rooted at page iRoot, one should call:
  46833. **
  46834. ** assert( !hasReadConflicts(pBtree, iRoot) );
  46835. */
  46836. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  46837. BtCursor *p;
  46838. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  46839. if( p->pgnoRoot==iRoot
  46840. && p->pBtree!=pBtree
  46841. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  46842. ){
  46843. return 1;
  46844. }
  46845. }
  46846. return 0;
  46847. }
  46848. #endif /* #ifdef SQLITE_DEBUG */
  46849. /*
  46850. ** Query to see if Btree handle p may obtain a lock of type eLock
  46851. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  46852. ** SQLITE_OK if the lock may be obtained (by calling
  46853. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  46854. */
  46855. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  46856. BtShared *pBt = p->pBt;
  46857. BtLock *pIter;
  46858. assert( sqlite3BtreeHoldsMutex(p) );
  46859. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  46860. assert( p->db!=0 );
  46861. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  46862. /* If requesting a write-lock, then the Btree must have an open write
  46863. ** transaction on this file. And, obviously, for this to be so there
  46864. ** must be an open write transaction on the file itself.
  46865. */
  46866. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  46867. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  46868. /* This routine is a no-op if the shared-cache is not enabled */
  46869. if( !p->sharable ){
  46870. return SQLITE_OK;
  46871. }
  46872. /* If some other connection is holding an exclusive lock, the
  46873. ** requested lock may not be obtained.
  46874. */
  46875. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  46876. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  46877. return SQLITE_LOCKED_SHAREDCACHE;
  46878. }
  46879. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  46880. /* The condition (pIter->eLock!=eLock) in the following if(...)
  46881. ** statement is a simplification of:
  46882. **
  46883. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  46884. **
  46885. ** since we know that if eLock==WRITE_LOCK, then no other connection
  46886. ** may hold a WRITE_LOCK on any table in this file (since there can
  46887. ** only be a single writer).
  46888. */
  46889. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  46890. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  46891. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  46892. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  46893. if( eLock==WRITE_LOCK ){
  46894. assert( p==pBt->pWriter );
  46895. pBt->btsFlags |= BTS_PENDING;
  46896. }
  46897. return SQLITE_LOCKED_SHAREDCACHE;
  46898. }
  46899. }
  46900. return SQLITE_OK;
  46901. }
  46902. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  46903. #ifndef SQLITE_OMIT_SHARED_CACHE
  46904. /*
  46905. ** Add a lock on the table with root-page iTable to the shared-btree used
  46906. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  46907. ** WRITE_LOCK.
  46908. **
  46909. ** This function assumes the following:
  46910. **
  46911. ** (a) The specified Btree object p is connected to a sharable
  46912. ** database (one with the BtShared.sharable flag set), and
  46913. **
  46914. ** (b) No other Btree objects hold a lock that conflicts
  46915. ** with the requested lock (i.e. querySharedCacheTableLock() has
  46916. ** already been called and returned SQLITE_OK).
  46917. **
  46918. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  46919. ** is returned if a malloc attempt fails.
  46920. */
  46921. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  46922. BtShared *pBt = p->pBt;
  46923. BtLock *pLock = 0;
  46924. BtLock *pIter;
  46925. assert( sqlite3BtreeHoldsMutex(p) );
  46926. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  46927. assert( p->db!=0 );
  46928. /* A connection with the read-uncommitted flag set will never try to
  46929. ** obtain a read-lock using this function. The only read-lock obtained
  46930. ** by a connection in read-uncommitted mode is on the sqlite_master
  46931. ** table, and that lock is obtained in BtreeBeginTrans(). */
  46932. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  46933. /* This function should only be called on a sharable b-tree after it
  46934. ** has been determined that no other b-tree holds a conflicting lock. */
  46935. assert( p->sharable );
  46936. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  46937. /* First search the list for an existing lock on this table. */
  46938. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  46939. if( pIter->iTable==iTable && pIter->pBtree==p ){
  46940. pLock = pIter;
  46941. break;
  46942. }
  46943. }
  46944. /* If the above search did not find a BtLock struct associating Btree p
  46945. ** with table iTable, allocate one and link it into the list.
  46946. */
  46947. if( !pLock ){
  46948. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  46949. if( !pLock ){
  46950. return SQLITE_NOMEM;
  46951. }
  46952. pLock->iTable = iTable;
  46953. pLock->pBtree = p;
  46954. pLock->pNext = pBt->pLock;
  46955. pBt->pLock = pLock;
  46956. }
  46957. /* Set the BtLock.eLock variable to the maximum of the current lock
  46958. ** and the requested lock. This means if a write-lock was already held
  46959. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  46960. */
  46961. assert( WRITE_LOCK>READ_LOCK );
  46962. if( eLock>pLock->eLock ){
  46963. pLock->eLock = eLock;
  46964. }
  46965. return SQLITE_OK;
  46966. }
  46967. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  46968. #ifndef SQLITE_OMIT_SHARED_CACHE
  46969. /*
  46970. ** Release all the table locks (locks obtained via calls to
  46971. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  46972. **
  46973. ** This function assumes that Btree p has an open read or write
  46974. ** transaction. If it does not, then the BTS_PENDING flag
  46975. ** may be incorrectly cleared.
  46976. */
  46977. static void clearAllSharedCacheTableLocks(Btree *p){
  46978. BtShared *pBt = p->pBt;
  46979. BtLock **ppIter = &pBt->pLock;
  46980. assert( sqlite3BtreeHoldsMutex(p) );
  46981. assert( p->sharable || 0==*ppIter );
  46982. assert( p->inTrans>0 );
  46983. while( *ppIter ){
  46984. BtLock *pLock = *ppIter;
  46985. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  46986. assert( pLock->pBtree->inTrans>=pLock->eLock );
  46987. if( pLock->pBtree==p ){
  46988. *ppIter = pLock->pNext;
  46989. assert( pLock->iTable!=1 || pLock==&p->lock );
  46990. if( pLock->iTable!=1 ){
  46991. sqlite3_free(pLock);
  46992. }
  46993. }else{
  46994. ppIter = &pLock->pNext;
  46995. }
  46996. }
  46997. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  46998. if( pBt->pWriter==p ){
  46999. pBt->pWriter = 0;
  47000. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  47001. }else if( pBt->nTransaction==2 ){
  47002. /* This function is called when Btree p is concluding its
  47003. ** transaction. If there currently exists a writer, and p is not
  47004. ** that writer, then the number of locks held by connections other
  47005. ** than the writer must be about to drop to zero. In this case
  47006. ** set the BTS_PENDING flag to 0.
  47007. **
  47008. ** If there is not currently a writer, then BTS_PENDING must
  47009. ** be zero already. So this next line is harmless in that case.
  47010. */
  47011. pBt->btsFlags &= ~BTS_PENDING;
  47012. }
  47013. }
  47014. /*
  47015. ** This function changes all write-locks held by Btree p into read-locks.
  47016. */
  47017. static void downgradeAllSharedCacheTableLocks(Btree *p){
  47018. BtShared *pBt = p->pBt;
  47019. if( pBt->pWriter==p ){
  47020. BtLock *pLock;
  47021. pBt->pWriter = 0;
  47022. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  47023. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  47024. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  47025. pLock->eLock = READ_LOCK;
  47026. }
  47027. }
  47028. }
  47029. #endif /* SQLITE_OMIT_SHARED_CACHE */
  47030. static void releasePage(MemPage *pPage); /* Forward reference */
  47031. /*
  47032. ***** This routine is used inside of assert() only ****
  47033. **
  47034. ** Verify that the cursor holds the mutex on its BtShared
  47035. */
  47036. #ifdef SQLITE_DEBUG
  47037. static int cursorHoldsMutex(BtCursor *p){
  47038. return sqlite3_mutex_held(p->pBt->mutex);
  47039. }
  47040. #endif
  47041. #ifndef SQLITE_OMIT_INCRBLOB
  47042. /*
  47043. ** Invalidate the overflow page-list cache for cursor pCur, if any.
  47044. */
  47045. static void invalidateOverflowCache(BtCursor *pCur){
  47046. assert( cursorHoldsMutex(pCur) );
  47047. sqlite3_free(pCur->aOverflow);
  47048. pCur->aOverflow = 0;
  47049. }
  47050. /*
  47051. ** Invalidate the overflow page-list cache for all cursors opened
  47052. ** on the shared btree structure pBt.
  47053. */
  47054. static void invalidateAllOverflowCache(BtShared *pBt){
  47055. BtCursor *p;
  47056. assert( sqlite3_mutex_held(pBt->mutex) );
  47057. for(p=pBt->pCursor; p; p=p->pNext){
  47058. invalidateOverflowCache(p);
  47059. }
  47060. }
  47061. /*
  47062. ** This function is called before modifying the contents of a table
  47063. ** to invalidate any incrblob cursors that are open on the
  47064. ** row or one of the rows being modified.
  47065. **
  47066. ** If argument isClearTable is true, then the entire contents of the
  47067. ** table is about to be deleted. In this case invalidate all incrblob
  47068. ** cursors open on any row within the table with root-page pgnoRoot.
  47069. **
  47070. ** Otherwise, if argument isClearTable is false, then the row with
  47071. ** rowid iRow is being replaced or deleted. In this case invalidate
  47072. ** only those incrblob cursors open on that specific row.
  47073. */
  47074. static void invalidateIncrblobCursors(
  47075. Btree *pBtree, /* The database file to check */
  47076. i64 iRow, /* The rowid that might be changing */
  47077. int isClearTable /* True if all rows are being deleted */
  47078. ){
  47079. BtCursor *p;
  47080. BtShared *pBt = pBtree->pBt;
  47081. assert( sqlite3BtreeHoldsMutex(pBtree) );
  47082. for(p=pBt->pCursor; p; p=p->pNext){
  47083. if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
  47084. p->eState = CURSOR_INVALID;
  47085. }
  47086. }
  47087. }
  47088. #else
  47089. /* Stub functions when INCRBLOB is omitted */
  47090. #define invalidateOverflowCache(x)
  47091. #define invalidateAllOverflowCache(x)
  47092. #define invalidateIncrblobCursors(x,y,z)
  47093. #endif /* SQLITE_OMIT_INCRBLOB */
  47094. /*
  47095. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  47096. ** when a page that previously contained data becomes a free-list leaf
  47097. ** page.
  47098. **
  47099. ** The BtShared.pHasContent bitvec exists to work around an obscure
  47100. ** bug caused by the interaction of two useful IO optimizations surrounding
  47101. ** free-list leaf pages:
  47102. **
  47103. ** 1) When all data is deleted from a page and the page becomes
  47104. ** a free-list leaf page, the page is not written to the database
  47105. ** (as free-list leaf pages contain no meaningful data). Sometimes
  47106. ** such a page is not even journalled (as it will not be modified,
  47107. ** why bother journalling it?).
  47108. **
  47109. ** 2) When a free-list leaf page is reused, its content is not read
  47110. ** from the database or written to the journal file (why should it
  47111. ** be, if it is not at all meaningful?).
  47112. **
  47113. ** By themselves, these optimizations work fine and provide a handy
  47114. ** performance boost to bulk delete or insert operations. However, if
  47115. ** a page is moved to the free-list and then reused within the same
  47116. ** transaction, a problem comes up. If the page is not journalled when
  47117. ** it is moved to the free-list and it is also not journalled when it
  47118. ** is extracted from the free-list and reused, then the original data
  47119. ** may be lost. In the event of a rollback, it may not be possible
  47120. ** to restore the database to its original configuration.
  47121. **
  47122. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  47123. ** moved to become a free-list leaf page, the corresponding bit is
  47124. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  47125. ** optimization 2 above is omitted if the corresponding bit is already
  47126. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  47127. ** at the end of every transaction.
  47128. */
  47129. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  47130. int rc = SQLITE_OK;
  47131. if( !pBt->pHasContent ){
  47132. assert( pgno<=pBt->nPage );
  47133. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  47134. if( !pBt->pHasContent ){
  47135. rc = SQLITE_NOMEM;
  47136. }
  47137. }
  47138. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  47139. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  47140. }
  47141. return rc;
  47142. }
  47143. /*
  47144. ** Query the BtShared.pHasContent vector.
  47145. **
  47146. ** This function is called when a free-list leaf page is removed from the
  47147. ** free-list for reuse. It returns false if it is safe to retrieve the
  47148. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  47149. */
  47150. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  47151. Bitvec *p = pBt->pHasContent;
  47152. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  47153. }
  47154. /*
  47155. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  47156. ** invoked at the conclusion of each write-transaction.
  47157. */
  47158. static void btreeClearHasContent(BtShared *pBt){
  47159. sqlite3BitvecDestroy(pBt->pHasContent);
  47160. pBt->pHasContent = 0;
  47161. }
  47162. /*
  47163. ** Release all of the apPage[] pages for a cursor.
  47164. */
  47165. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  47166. int i;
  47167. for(i=0; i<=pCur->iPage; i++){
  47168. releasePage(pCur->apPage[i]);
  47169. pCur->apPage[i] = 0;
  47170. }
  47171. pCur->iPage = -1;
  47172. }
  47173. /*
  47174. ** Save the current cursor position in the variables BtCursor.nKey
  47175. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  47176. **
  47177. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  47178. ** prior to calling this routine.
  47179. */
  47180. static int saveCursorPosition(BtCursor *pCur){
  47181. int rc;
  47182. assert( CURSOR_VALID==pCur->eState );
  47183. assert( 0==pCur->pKey );
  47184. assert( cursorHoldsMutex(pCur) );
  47185. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  47186. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  47187. /* If this is an intKey table, then the above call to BtreeKeySize()
  47188. ** stores the integer key in pCur->nKey. In this case this value is
  47189. ** all that is required. Otherwise, if pCur is not open on an intKey
  47190. ** table, then malloc space for and store the pCur->nKey bytes of key
  47191. ** data.
  47192. */
  47193. if( 0==pCur->apPage[0]->intKey ){
  47194. void *pKey = sqlite3Malloc( (int)pCur->nKey );
  47195. if( pKey ){
  47196. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  47197. if( rc==SQLITE_OK ){
  47198. pCur->pKey = pKey;
  47199. }else{
  47200. sqlite3_free(pKey);
  47201. }
  47202. }else{
  47203. rc = SQLITE_NOMEM;
  47204. }
  47205. }
  47206. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  47207. if( rc==SQLITE_OK ){
  47208. btreeReleaseAllCursorPages(pCur);
  47209. pCur->eState = CURSOR_REQUIRESEEK;
  47210. }
  47211. invalidateOverflowCache(pCur);
  47212. return rc;
  47213. }
  47214. /*
  47215. ** Save the positions of all cursors (except pExcept) that are open on
  47216. ** the table with root-page iRoot. Usually, this is called just before cursor
  47217. ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
  47218. */
  47219. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  47220. BtCursor *p;
  47221. assert( sqlite3_mutex_held(pBt->mutex) );
  47222. assert( pExcept==0 || pExcept->pBt==pBt );
  47223. for(p=pBt->pCursor; p; p=p->pNext){
  47224. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  47225. if( p->eState==CURSOR_VALID ){
  47226. int rc = saveCursorPosition(p);
  47227. if( SQLITE_OK!=rc ){
  47228. return rc;
  47229. }
  47230. }else{
  47231. testcase( p->iPage>0 );
  47232. btreeReleaseAllCursorPages(p);
  47233. }
  47234. }
  47235. }
  47236. return SQLITE_OK;
  47237. }
  47238. /*
  47239. ** Clear the current cursor position.
  47240. */
  47241. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  47242. assert( cursorHoldsMutex(pCur) );
  47243. sqlite3_free(pCur->pKey);
  47244. pCur->pKey = 0;
  47245. pCur->eState = CURSOR_INVALID;
  47246. }
  47247. /*
  47248. ** In this version of BtreeMoveto, pKey is a packed index record
  47249. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  47250. ** record and then call BtreeMovetoUnpacked() to do the work.
  47251. */
  47252. static int btreeMoveto(
  47253. BtCursor *pCur, /* Cursor open on the btree to be searched */
  47254. const void *pKey, /* Packed key if the btree is an index */
  47255. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  47256. int bias, /* Bias search to the high end */
  47257. int *pRes /* Write search results here */
  47258. ){
  47259. int rc; /* Status code */
  47260. UnpackedRecord *pIdxKey; /* Unpacked index key */
  47261. char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
  47262. char *pFree = 0;
  47263. if( pKey ){
  47264. assert( nKey==(i64)(int)nKey );
  47265. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  47266. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  47267. );
  47268. if( pIdxKey==0 ) return SQLITE_NOMEM;
  47269. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  47270. }else{
  47271. pIdxKey = 0;
  47272. }
  47273. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  47274. if( pFree ){
  47275. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  47276. }
  47277. return rc;
  47278. }
  47279. /*
  47280. ** Restore the cursor to the position it was in (or as close to as possible)
  47281. ** when saveCursorPosition() was called. Note that this call deletes the
  47282. ** saved position info stored by saveCursorPosition(), so there can be
  47283. ** at most one effective restoreCursorPosition() call after each
  47284. ** saveCursorPosition().
  47285. */
  47286. static int btreeRestoreCursorPosition(BtCursor *pCur){
  47287. int rc;
  47288. assert( cursorHoldsMutex(pCur) );
  47289. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  47290. if( pCur->eState==CURSOR_FAULT ){
  47291. return pCur->skipNext;
  47292. }
  47293. pCur->eState = CURSOR_INVALID;
  47294. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
  47295. if( rc==SQLITE_OK ){
  47296. sqlite3_free(pCur->pKey);
  47297. pCur->pKey = 0;
  47298. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  47299. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  47300. pCur->eState = CURSOR_SKIPNEXT;
  47301. }
  47302. }
  47303. return rc;
  47304. }
  47305. #define restoreCursorPosition(p) \
  47306. (p->eState>=CURSOR_REQUIRESEEK ? \
  47307. btreeRestoreCursorPosition(p) : \
  47308. SQLITE_OK)
  47309. /*
  47310. ** Determine whether or not a cursor has moved from the position it
  47311. ** was last placed at. Cursors can move when the row they are pointing
  47312. ** at is deleted out from under them.
  47313. **
  47314. ** This routine returns an error code if something goes wrong. The
  47315. ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
  47316. */
  47317. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
  47318. int rc;
  47319. rc = restoreCursorPosition(pCur);
  47320. if( rc ){
  47321. *pHasMoved = 1;
  47322. return rc;
  47323. }
  47324. if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
  47325. *pHasMoved = 1;
  47326. }else{
  47327. *pHasMoved = 0;
  47328. }
  47329. return SQLITE_OK;
  47330. }
  47331. #ifndef SQLITE_OMIT_AUTOVACUUM
  47332. /*
  47333. ** Given a page number of a regular database page, return the page
  47334. ** number for the pointer-map page that contains the entry for the
  47335. ** input page number.
  47336. **
  47337. ** Return 0 (not a valid page) for pgno==1 since there is
  47338. ** no pointer map associated with page 1. The integrity_check logic
  47339. ** requires that ptrmapPageno(*,1)!=1.
  47340. */
  47341. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  47342. int nPagesPerMapPage;
  47343. Pgno iPtrMap, ret;
  47344. assert( sqlite3_mutex_held(pBt->mutex) );
  47345. if( pgno<2 ) return 0;
  47346. nPagesPerMapPage = (pBt->usableSize/5)+1;
  47347. iPtrMap = (pgno-2)/nPagesPerMapPage;
  47348. ret = (iPtrMap*nPagesPerMapPage) + 2;
  47349. if( ret==PENDING_BYTE_PAGE(pBt) ){
  47350. ret++;
  47351. }
  47352. return ret;
  47353. }
  47354. /*
  47355. ** Write an entry into the pointer map.
  47356. **
  47357. ** This routine updates the pointer map entry for page number 'key'
  47358. ** so that it maps to type 'eType' and parent page number 'pgno'.
  47359. **
  47360. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  47361. ** a no-op. If an error occurs, the appropriate error code is written
  47362. ** into *pRC.
  47363. */
  47364. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  47365. DbPage *pDbPage; /* The pointer map page */
  47366. u8 *pPtrmap; /* The pointer map data */
  47367. Pgno iPtrmap; /* The pointer map page number */
  47368. int offset; /* Offset in pointer map page */
  47369. int rc; /* Return code from subfunctions */
  47370. if( *pRC ) return;
  47371. assert( sqlite3_mutex_held(pBt->mutex) );
  47372. /* The master-journal page number must never be used as a pointer map page */
  47373. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  47374. assert( pBt->autoVacuum );
  47375. if( key==0 ){
  47376. *pRC = SQLITE_CORRUPT_BKPT;
  47377. return;
  47378. }
  47379. iPtrmap = PTRMAP_PAGENO(pBt, key);
  47380. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  47381. if( rc!=SQLITE_OK ){
  47382. *pRC = rc;
  47383. return;
  47384. }
  47385. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  47386. if( offset<0 ){
  47387. *pRC = SQLITE_CORRUPT_BKPT;
  47388. goto ptrmap_exit;
  47389. }
  47390. assert( offset <= (int)pBt->usableSize-5 );
  47391. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  47392. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  47393. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  47394. *pRC= rc = sqlite3PagerWrite(pDbPage);
  47395. if( rc==SQLITE_OK ){
  47396. pPtrmap[offset] = eType;
  47397. put4byte(&pPtrmap[offset+1], parent);
  47398. }
  47399. }
  47400. ptrmap_exit:
  47401. sqlite3PagerUnref(pDbPage);
  47402. }
  47403. /*
  47404. ** Read an entry from the pointer map.
  47405. **
  47406. ** This routine retrieves the pointer map entry for page 'key', writing
  47407. ** the type and parent page number to *pEType and *pPgno respectively.
  47408. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  47409. */
  47410. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  47411. DbPage *pDbPage; /* The pointer map page */
  47412. int iPtrmap; /* Pointer map page index */
  47413. u8 *pPtrmap; /* Pointer map page data */
  47414. int offset; /* Offset of entry in pointer map */
  47415. int rc;
  47416. assert( sqlite3_mutex_held(pBt->mutex) );
  47417. iPtrmap = PTRMAP_PAGENO(pBt, key);
  47418. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  47419. if( rc!=0 ){
  47420. return rc;
  47421. }
  47422. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  47423. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  47424. if( offset<0 ){
  47425. sqlite3PagerUnref(pDbPage);
  47426. return SQLITE_CORRUPT_BKPT;
  47427. }
  47428. assert( offset <= (int)pBt->usableSize-5 );
  47429. assert( pEType!=0 );
  47430. *pEType = pPtrmap[offset];
  47431. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  47432. sqlite3PagerUnref(pDbPage);
  47433. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  47434. return SQLITE_OK;
  47435. }
  47436. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  47437. #define ptrmapPut(w,x,y,z,rc)
  47438. #define ptrmapGet(w,x,y,z) SQLITE_OK
  47439. #define ptrmapPutOvflPtr(x, y, rc)
  47440. #endif
  47441. /*
  47442. ** Given a btree page and a cell index (0 means the first cell on
  47443. ** the page, 1 means the second cell, and so forth) return a pointer
  47444. ** to the cell content.
  47445. **
  47446. ** This routine works only for pages that do not contain overflow cells.
  47447. */
  47448. #define findCell(P,I) \
  47449. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
  47450. #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
  47451. /*
  47452. ** This a more complex version of findCell() that works for
  47453. ** pages that do contain overflow cells.
  47454. */
  47455. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  47456. int i;
  47457. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47458. for(i=pPage->nOverflow-1; i>=0; i--){
  47459. int k;
  47460. k = pPage->aiOvfl[i];
  47461. if( k<=iCell ){
  47462. if( k==iCell ){
  47463. return pPage->apOvfl[i];
  47464. }
  47465. iCell--;
  47466. }
  47467. }
  47468. return findCell(pPage, iCell);
  47469. }
  47470. /*
  47471. ** Parse a cell content block and fill in the CellInfo structure. There
  47472. ** are two versions of this function. btreeParseCell() takes a
  47473. ** cell index as the second argument and btreeParseCellPtr()
  47474. ** takes a pointer to the body of the cell as its second argument.
  47475. **
  47476. ** Within this file, the parseCell() macro can be called instead of
  47477. ** btreeParseCellPtr(). Using some compilers, this will be faster.
  47478. */
  47479. static void btreeParseCellPtr(
  47480. MemPage *pPage, /* Page containing the cell */
  47481. u8 *pCell, /* Pointer to the cell text. */
  47482. CellInfo *pInfo /* Fill in this structure */
  47483. ){
  47484. u16 n; /* Number bytes in cell content header */
  47485. u32 nPayload; /* Number of bytes of cell payload */
  47486. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47487. pInfo->pCell = pCell;
  47488. assert( pPage->leaf==0 || pPage->leaf==1 );
  47489. n = pPage->childPtrSize;
  47490. assert( n==4-4*pPage->leaf );
  47491. if( pPage->intKey ){
  47492. if( pPage->hasData ){
  47493. assert( n==0 );
  47494. n = getVarint32(pCell, nPayload);
  47495. }else{
  47496. nPayload = 0;
  47497. }
  47498. n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
  47499. pInfo->nData = nPayload;
  47500. }else{
  47501. pInfo->nData = 0;
  47502. n += getVarint32(&pCell[n], nPayload);
  47503. pInfo->nKey = nPayload;
  47504. }
  47505. pInfo->nPayload = nPayload;
  47506. pInfo->nHeader = n;
  47507. testcase( nPayload==pPage->maxLocal );
  47508. testcase( nPayload==pPage->maxLocal+1 );
  47509. if( likely(nPayload<=pPage->maxLocal) ){
  47510. /* This is the (easy) common case where the entire payload fits
  47511. ** on the local page. No overflow is required.
  47512. */
  47513. if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
  47514. pInfo->nLocal = (u16)nPayload;
  47515. pInfo->iOverflow = 0;
  47516. }else{
  47517. /* If the payload will not fit completely on the local page, we have
  47518. ** to decide how much to store locally and how much to spill onto
  47519. ** overflow pages. The strategy is to minimize the amount of unused
  47520. ** space on overflow pages while keeping the amount of local storage
  47521. ** in between minLocal and maxLocal.
  47522. **
  47523. ** Warning: changing the way overflow payload is distributed in any
  47524. ** way will result in an incompatible file format.
  47525. */
  47526. int minLocal; /* Minimum amount of payload held locally */
  47527. int maxLocal; /* Maximum amount of payload held locally */
  47528. int surplus; /* Overflow payload available for local storage */
  47529. minLocal = pPage->minLocal;
  47530. maxLocal = pPage->maxLocal;
  47531. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  47532. testcase( surplus==maxLocal );
  47533. testcase( surplus==maxLocal+1 );
  47534. if( surplus <= maxLocal ){
  47535. pInfo->nLocal = (u16)surplus;
  47536. }else{
  47537. pInfo->nLocal = (u16)minLocal;
  47538. }
  47539. pInfo->iOverflow = (u16)(pInfo->nLocal + n);
  47540. pInfo->nSize = pInfo->iOverflow + 4;
  47541. }
  47542. }
  47543. #define parseCell(pPage, iCell, pInfo) \
  47544. btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
  47545. static void btreeParseCell(
  47546. MemPage *pPage, /* Page containing the cell */
  47547. int iCell, /* The cell index. First cell is 0 */
  47548. CellInfo *pInfo /* Fill in this structure */
  47549. ){
  47550. parseCell(pPage, iCell, pInfo);
  47551. }
  47552. /*
  47553. ** Compute the total number of bytes that a Cell needs in the cell
  47554. ** data area of the btree-page. The return number includes the cell
  47555. ** data header and the local payload, but not any overflow page or
  47556. ** the space used by the cell pointer.
  47557. */
  47558. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  47559. u8 *pIter = &pCell[pPage->childPtrSize];
  47560. u32 nSize;
  47561. #ifdef SQLITE_DEBUG
  47562. /* The value returned by this function should always be the same as
  47563. ** the (CellInfo.nSize) value found by doing a full parse of the
  47564. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  47565. ** this function verifies that this invariant is not violated. */
  47566. CellInfo debuginfo;
  47567. btreeParseCellPtr(pPage, pCell, &debuginfo);
  47568. #endif
  47569. if( pPage->intKey ){
  47570. u8 *pEnd;
  47571. if( pPage->hasData ){
  47572. pIter += getVarint32(pIter, nSize);
  47573. }else{
  47574. nSize = 0;
  47575. }
  47576. /* pIter now points at the 64-bit integer key value, a variable length
  47577. ** integer. The following block moves pIter to point at the first byte
  47578. ** past the end of the key value. */
  47579. pEnd = &pIter[9];
  47580. while( (*pIter++)&0x80 && pIter<pEnd );
  47581. }else{
  47582. pIter += getVarint32(pIter, nSize);
  47583. }
  47584. testcase( nSize==pPage->maxLocal );
  47585. testcase( nSize==pPage->maxLocal+1 );
  47586. if( nSize>pPage->maxLocal ){
  47587. int minLocal = pPage->minLocal;
  47588. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  47589. testcase( nSize==pPage->maxLocal );
  47590. testcase( nSize==pPage->maxLocal+1 );
  47591. if( nSize>pPage->maxLocal ){
  47592. nSize = minLocal;
  47593. }
  47594. nSize += 4;
  47595. }
  47596. nSize += (u32)(pIter - pCell);
  47597. /* The minimum size of any cell is 4 bytes. */
  47598. if( nSize<4 ){
  47599. nSize = 4;
  47600. }
  47601. assert( nSize==debuginfo.nSize );
  47602. return (u16)nSize;
  47603. }
  47604. #ifdef SQLITE_DEBUG
  47605. /* This variation on cellSizePtr() is used inside of assert() statements
  47606. ** only. */
  47607. static u16 cellSize(MemPage *pPage, int iCell){
  47608. return cellSizePtr(pPage, findCell(pPage, iCell));
  47609. }
  47610. #endif
  47611. #ifndef SQLITE_OMIT_AUTOVACUUM
  47612. /*
  47613. ** If the cell pCell, part of page pPage contains a pointer
  47614. ** to an overflow page, insert an entry into the pointer-map
  47615. ** for the overflow page.
  47616. */
  47617. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  47618. CellInfo info;
  47619. if( *pRC ) return;
  47620. assert( pCell!=0 );
  47621. btreeParseCellPtr(pPage, pCell, &info);
  47622. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  47623. if( info.iOverflow ){
  47624. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  47625. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  47626. }
  47627. }
  47628. #endif
  47629. /*
  47630. ** Defragment the page given. All Cells are moved to the
  47631. ** end of the page and all free space is collected into one
  47632. ** big FreeBlk that occurs in between the header and cell
  47633. ** pointer array and the cell content area.
  47634. */
  47635. static int defragmentPage(MemPage *pPage){
  47636. int i; /* Loop counter */
  47637. int pc; /* Address of a i-th cell */
  47638. int hdr; /* Offset to the page header */
  47639. int size; /* Size of a cell */
  47640. int usableSize; /* Number of usable bytes on a page */
  47641. int cellOffset; /* Offset to the cell pointer array */
  47642. int cbrk; /* Offset to the cell content area */
  47643. int nCell; /* Number of cells on the page */
  47644. unsigned char *data; /* The page data */
  47645. unsigned char *temp; /* Temp area for cell content */
  47646. int iCellFirst; /* First allowable cell index */
  47647. int iCellLast; /* Last possible cell index */
  47648. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47649. assert( pPage->pBt!=0 );
  47650. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  47651. assert( pPage->nOverflow==0 );
  47652. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47653. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  47654. data = pPage->aData;
  47655. hdr = pPage->hdrOffset;
  47656. cellOffset = pPage->cellOffset;
  47657. nCell = pPage->nCell;
  47658. assert( nCell==get2byte(&data[hdr+3]) );
  47659. usableSize = pPage->pBt->usableSize;
  47660. cbrk = get2byte(&data[hdr+5]);
  47661. memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  47662. cbrk = usableSize;
  47663. iCellFirst = cellOffset + 2*nCell;
  47664. iCellLast = usableSize - 4;
  47665. for(i=0; i<nCell; i++){
  47666. u8 *pAddr; /* The i-th cell pointer */
  47667. pAddr = &data[cellOffset + i*2];
  47668. pc = get2byte(pAddr);
  47669. testcase( pc==iCellFirst );
  47670. testcase( pc==iCellLast );
  47671. #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  47672. /* These conditions have already been verified in btreeInitPage()
  47673. ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
  47674. */
  47675. if( pc<iCellFirst || pc>iCellLast ){
  47676. return SQLITE_CORRUPT_BKPT;
  47677. }
  47678. #endif
  47679. assert( pc>=iCellFirst && pc<=iCellLast );
  47680. size = cellSizePtr(pPage, &temp[pc]);
  47681. cbrk -= size;
  47682. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  47683. if( cbrk<iCellFirst ){
  47684. return SQLITE_CORRUPT_BKPT;
  47685. }
  47686. #else
  47687. if( cbrk<iCellFirst || pc+size>usableSize ){
  47688. return SQLITE_CORRUPT_BKPT;
  47689. }
  47690. #endif
  47691. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  47692. testcase( cbrk+size==usableSize );
  47693. testcase( pc+size==usableSize );
  47694. memcpy(&data[cbrk], &temp[pc], size);
  47695. put2byte(pAddr, cbrk);
  47696. }
  47697. assert( cbrk>=iCellFirst );
  47698. put2byte(&data[hdr+5], cbrk);
  47699. data[hdr+1] = 0;
  47700. data[hdr+2] = 0;
  47701. data[hdr+7] = 0;
  47702. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  47703. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47704. if( cbrk-iCellFirst!=pPage->nFree ){
  47705. return SQLITE_CORRUPT_BKPT;
  47706. }
  47707. return SQLITE_OK;
  47708. }
  47709. /*
  47710. ** Allocate nByte bytes of space from within the B-Tree page passed
  47711. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  47712. ** of the first byte of allocated space. Return either SQLITE_OK or
  47713. ** an error code (usually SQLITE_CORRUPT).
  47714. **
  47715. ** The caller guarantees that there is sufficient space to make the
  47716. ** allocation. This routine might need to defragment in order to bring
  47717. ** all the space together, however. This routine will avoid using
  47718. ** the first two bytes past the cell pointer area since presumably this
  47719. ** allocation is being made in order to insert a new cell, so we will
  47720. ** also end up needing a new cell pointer.
  47721. */
  47722. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  47723. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  47724. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  47725. int nFrag; /* Number of fragmented bytes on pPage */
  47726. int top; /* First byte of cell content area */
  47727. int gap; /* First byte of gap between cell pointers and cell content */
  47728. int rc; /* Integer return code */
  47729. int usableSize; /* Usable size of the page */
  47730. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47731. assert( pPage->pBt );
  47732. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47733. assert( nByte>=0 ); /* Minimum cell size is 4 */
  47734. assert( pPage->nFree>=nByte );
  47735. assert( pPage->nOverflow==0 );
  47736. usableSize = pPage->pBt->usableSize;
  47737. assert( nByte < usableSize-8 );
  47738. nFrag = data[hdr+7];
  47739. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  47740. gap = pPage->cellOffset + 2*pPage->nCell;
  47741. top = get2byteNotZero(&data[hdr+5]);
  47742. if( gap>top ) return SQLITE_CORRUPT_BKPT;
  47743. testcase( gap+2==top );
  47744. testcase( gap+1==top );
  47745. testcase( gap==top );
  47746. if( nFrag>=60 ){
  47747. /* Always defragment highly fragmented pages */
  47748. rc = defragmentPage(pPage);
  47749. if( rc ) return rc;
  47750. top = get2byteNotZero(&data[hdr+5]);
  47751. }else if( gap+2<=top ){
  47752. /* Search the freelist looking for a free slot big enough to satisfy
  47753. ** the request. The allocation is made from the first free slot in
  47754. ** the list that is large enough to accommodate it.
  47755. */
  47756. int pc, addr;
  47757. for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
  47758. int size; /* Size of the free slot */
  47759. if( pc>usableSize-4 || pc<addr+4 ){
  47760. return SQLITE_CORRUPT_BKPT;
  47761. }
  47762. size = get2byte(&data[pc+2]);
  47763. if( size>=nByte ){
  47764. int x = size - nByte;
  47765. testcase( x==4 );
  47766. testcase( x==3 );
  47767. if( x<4 ){
  47768. /* Remove the slot from the free-list. Update the number of
  47769. ** fragmented bytes within the page. */
  47770. memcpy(&data[addr], &data[pc], 2);
  47771. data[hdr+7] = (u8)(nFrag + x);
  47772. }else if( size+pc > usableSize ){
  47773. return SQLITE_CORRUPT_BKPT;
  47774. }else{
  47775. /* The slot remains on the free-list. Reduce its size to account
  47776. ** for the portion used by the new allocation. */
  47777. put2byte(&data[pc+2], x);
  47778. }
  47779. *pIdx = pc + x;
  47780. return SQLITE_OK;
  47781. }
  47782. }
  47783. }
  47784. /* Check to make sure there is enough space in the gap to satisfy
  47785. ** the allocation. If not, defragment.
  47786. */
  47787. testcase( gap+2+nByte==top );
  47788. if( gap+2+nByte>top ){
  47789. rc = defragmentPage(pPage);
  47790. if( rc ) return rc;
  47791. top = get2byteNotZero(&data[hdr+5]);
  47792. assert( gap+nByte<=top );
  47793. }
  47794. /* Allocate memory from the gap in between the cell pointer array
  47795. ** and the cell content area. The btreeInitPage() call has already
  47796. ** validated the freelist. Given that the freelist is valid, there
  47797. ** is no way that the allocation can extend off the end of the page.
  47798. ** The assert() below verifies the previous sentence.
  47799. */
  47800. top -= nByte;
  47801. put2byte(&data[hdr+5], top);
  47802. assert( top+nByte <= (int)pPage->pBt->usableSize );
  47803. *pIdx = top;
  47804. return SQLITE_OK;
  47805. }
  47806. /*
  47807. ** Return a section of the pPage->aData to the freelist.
  47808. ** The first byte of the new free block is pPage->aDisk[start]
  47809. ** and the size of the block is "size" bytes.
  47810. **
  47811. ** Most of the effort here is involved in coalesing adjacent
  47812. ** free blocks into a single big free block.
  47813. */
  47814. static int freeSpace(MemPage *pPage, int start, int size){
  47815. int addr, pbegin, hdr;
  47816. int iLast; /* Largest possible freeblock offset */
  47817. unsigned char *data = pPage->aData;
  47818. assert( pPage->pBt!=0 );
  47819. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47820. assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
  47821. assert( (start + size) <= (int)pPage->pBt->usableSize );
  47822. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47823. assert( size>=0 ); /* Minimum cell size is 4 */
  47824. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  47825. /* Overwrite deleted information with zeros when the secure_delete
  47826. ** option is enabled */
  47827. memset(&data[start], 0, size);
  47828. }
  47829. /* Add the space back into the linked list of freeblocks. Note that
  47830. ** even though the freeblock list was checked by btreeInitPage(),
  47831. ** btreeInitPage() did not detect overlapping cells or
  47832. ** freeblocks that overlapped cells. Nor does it detect when the
  47833. ** cell content area exceeds the value in the page header. If these
  47834. ** situations arise, then subsequent insert operations might corrupt
  47835. ** the freelist. So we do need to check for corruption while scanning
  47836. ** the freelist.
  47837. */
  47838. hdr = pPage->hdrOffset;
  47839. addr = hdr + 1;
  47840. iLast = pPage->pBt->usableSize - 4;
  47841. assert( start<=iLast );
  47842. while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
  47843. if( pbegin<addr+4 ){
  47844. return SQLITE_CORRUPT_BKPT;
  47845. }
  47846. addr = pbegin;
  47847. }
  47848. if( pbegin>iLast ){
  47849. return SQLITE_CORRUPT_BKPT;
  47850. }
  47851. assert( pbegin>addr || pbegin==0 );
  47852. put2byte(&data[addr], start);
  47853. put2byte(&data[start], pbegin);
  47854. put2byte(&data[start+2], size);
  47855. pPage->nFree = pPage->nFree + (u16)size;
  47856. /* Coalesce adjacent free blocks */
  47857. addr = hdr + 1;
  47858. while( (pbegin = get2byte(&data[addr]))>0 ){
  47859. int pnext, psize, x;
  47860. assert( pbegin>addr );
  47861. assert( pbegin <= (int)pPage->pBt->usableSize-4 );
  47862. pnext = get2byte(&data[pbegin]);
  47863. psize = get2byte(&data[pbegin+2]);
  47864. if( pbegin + psize + 3 >= pnext && pnext>0 ){
  47865. int frag = pnext - (pbegin+psize);
  47866. if( (frag<0) || (frag>(int)data[hdr+7]) ){
  47867. return SQLITE_CORRUPT_BKPT;
  47868. }
  47869. data[hdr+7] -= (u8)frag;
  47870. x = get2byte(&data[pnext]);
  47871. put2byte(&data[pbegin], x);
  47872. x = pnext + get2byte(&data[pnext+2]) - pbegin;
  47873. put2byte(&data[pbegin+2], x);
  47874. }else{
  47875. addr = pbegin;
  47876. }
  47877. }
  47878. /* If the cell content area begins with a freeblock, remove it. */
  47879. if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
  47880. int top;
  47881. pbegin = get2byte(&data[hdr+1]);
  47882. memcpy(&data[hdr+1], &data[pbegin], 2);
  47883. top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
  47884. put2byte(&data[hdr+5], top);
  47885. }
  47886. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47887. return SQLITE_OK;
  47888. }
  47889. /*
  47890. ** Decode the flags byte (the first byte of the header) for a page
  47891. ** and initialize fields of the MemPage structure accordingly.
  47892. **
  47893. ** Only the following combinations are supported. Anything different
  47894. ** indicates a corrupt database files:
  47895. **
  47896. ** PTF_ZERODATA
  47897. ** PTF_ZERODATA | PTF_LEAF
  47898. ** PTF_LEAFDATA | PTF_INTKEY
  47899. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  47900. */
  47901. static int decodeFlags(MemPage *pPage, int flagByte){
  47902. BtShared *pBt; /* A copy of pPage->pBt */
  47903. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  47904. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47905. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  47906. flagByte &= ~PTF_LEAF;
  47907. pPage->childPtrSize = 4-4*pPage->leaf;
  47908. pBt = pPage->pBt;
  47909. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  47910. pPage->intKey = 1;
  47911. pPage->hasData = pPage->leaf;
  47912. pPage->maxLocal = pBt->maxLeaf;
  47913. pPage->minLocal = pBt->minLeaf;
  47914. }else if( flagByte==PTF_ZERODATA ){
  47915. pPage->intKey = 0;
  47916. pPage->hasData = 0;
  47917. pPage->maxLocal = pBt->maxLocal;
  47918. pPage->minLocal = pBt->minLocal;
  47919. }else{
  47920. return SQLITE_CORRUPT_BKPT;
  47921. }
  47922. pPage->max1bytePayload = pBt->max1bytePayload;
  47923. return SQLITE_OK;
  47924. }
  47925. /*
  47926. ** Initialize the auxiliary information for a disk block.
  47927. **
  47928. ** Return SQLITE_OK on success. If we see that the page does
  47929. ** not contain a well-formed database page, then return
  47930. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  47931. ** guarantee that the page is well-formed. It only shows that
  47932. ** we failed to detect any corruption.
  47933. */
  47934. static int btreeInitPage(MemPage *pPage){
  47935. assert( pPage->pBt!=0 );
  47936. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47937. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  47938. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  47939. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  47940. if( !pPage->isInit ){
  47941. u16 pc; /* Address of a freeblock within pPage->aData[] */
  47942. u8 hdr; /* Offset to beginning of page header */
  47943. u8 *data; /* Equal to pPage->aData */
  47944. BtShared *pBt; /* The main btree structure */
  47945. int usableSize; /* Amount of usable space on each page */
  47946. u16 cellOffset; /* Offset from start of page to first cell pointer */
  47947. int nFree; /* Number of unused bytes on the page */
  47948. int top; /* First byte of the cell content area */
  47949. int iCellFirst; /* First allowable cell or freeblock offset */
  47950. int iCellLast; /* Last possible cell or freeblock offset */
  47951. pBt = pPage->pBt;
  47952. hdr = pPage->hdrOffset;
  47953. data = pPage->aData;
  47954. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  47955. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  47956. pPage->maskPage = (u16)(pBt->pageSize - 1);
  47957. pPage->nOverflow = 0;
  47958. usableSize = pBt->usableSize;
  47959. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  47960. pPage->aDataEnd = &data[usableSize];
  47961. pPage->aCellIdx = &data[cellOffset];
  47962. top = get2byteNotZero(&data[hdr+5]);
  47963. pPage->nCell = get2byte(&data[hdr+3]);
  47964. if( pPage->nCell>MX_CELL(pBt) ){
  47965. /* To many cells for a single page. The page must be corrupt */
  47966. return SQLITE_CORRUPT_BKPT;
  47967. }
  47968. testcase( pPage->nCell==MX_CELL(pBt) );
  47969. /* A malformed database page might cause us to read past the end
  47970. ** of page when parsing a cell.
  47971. **
  47972. ** The following block of code checks early to see if a cell extends
  47973. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  47974. ** returned if it does.
  47975. */
  47976. iCellFirst = cellOffset + 2*pPage->nCell;
  47977. iCellLast = usableSize - 4;
  47978. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  47979. {
  47980. int i; /* Index into the cell pointer array */
  47981. int sz; /* Size of a cell */
  47982. if( !pPage->leaf ) iCellLast--;
  47983. for(i=0; i<pPage->nCell; i++){
  47984. pc = get2byte(&data[cellOffset+i*2]);
  47985. testcase( pc==iCellFirst );
  47986. testcase( pc==iCellLast );
  47987. if( pc<iCellFirst || pc>iCellLast ){
  47988. return SQLITE_CORRUPT_BKPT;
  47989. }
  47990. sz = cellSizePtr(pPage, &data[pc]);
  47991. testcase( pc+sz==usableSize );
  47992. if( pc+sz>usableSize ){
  47993. return SQLITE_CORRUPT_BKPT;
  47994. }
  47995. }
  47996. if( !pPage->leaf ) iCellLast++;
  47997. }
  47998. #endif
  47999. /* Compute the total free space on the page */
  48000. pc = get2byte(&data[hdr+1]);
  48001. nFree = data[hdr+7] + top;
  48002. while( pc>0 ){
  48003. u16 next, size;
  48004. if( pc<iCellFirst || pc>iCellLast ){
  48005. /* Start of free block is off the page */
  48006. return SQLITE_CORRUPT_BKPT;
  48007. }
  48008. next = get2byte(&data[pc]);
  48009. size = get2byte(&data[pc+2]);
  48010. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  48011. /* Free blocks must be in ascending order. And the last byte of
  48012. ** the free-block must lie on the database page. */
  48013. return SQLITE_CORRUPT_BKPT;
  48014. }
  48015. nFree = nFree + size;
  48016. pc = next;
  48017. }
  48018. /* At this point, nFree contains the sum of the offset to the start
  48019. ** of the cell-content area plus the number of free bytes within
  48020. ** the cell-content area. If this is greater than the usable-size
  48021. ** of the page, then the page must be corrupted. This check also
  48022. ** serves to verify that the offset to the start of the cell-content
  48023. ** area, according to the page header, lies within the page.
  48024. */
  48025. if( nFree>usableSize ){
  48026. return SQLITE_CORRUPT_BKPT;
  48027. }
  48028. pPage->nFree = (u16)(nFree - iCellFirst);
  48029. pPage->isInit = 1;
  48030. }
  48031. return SQLITE_OK;
  48032. }
  48033. /*
  48034. ** Set up a raw page so that it looks like a database page holding
  48035. ** no entries.
  48036. */
  48037. static void zeroPage(MemPage *pPage, int flags){
  48038. unsigned char *data = pPage->aData;
  48039. BtShared *pBt = pPage->pBt;
  48040. u8 hdr = pPage->hdrOffset;
  48041. u16 first;
  48042. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  48043. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  48044. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  48045. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  48046. assert( sqlite3_mutex_held(pBt->mutex) );
  48047. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  48048. memset(&data[hdr], 0, pBt->usableSize - hdr);
  48049. }
  48050. data[hdr] = (char)flags;
  48051. first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
  48052. memset(&data[hdr+1], 0, 4);
  48053. data[hdr+7] = 0;
  48054. put2byte(&data[hdr+5], pBt->usableSize);
  48055. pPage->nFree = (u16)(pBt->usableSize - first);
  48056. decodeFlags(pPage, flags);
  48057. pPage->hdrOffset = hdr;
  48058. pPage->cellOffset = first;
  48059. pPage->aDataEnd = &data[pBt->usableSize];
  48060. pPage->aCellIdx = &data[first];
  48061. pPage->nOverflow = 0;
  48062. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  48063. pPage->maskPage = (u16)(pBt->pageSize - 1);
  48064. pPage->nCell = 0;
  48065. pPage->isInit = 1;
  48066. }
  48067. /*
  48068. ** Convert a DbPage obtained from the pager into a MemPage used by
  48069. ** the btree layer.
  48070. */
  48071. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  48072. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  48073. pPage->aData = sqlite3PagerGetData(pDbPage);
  48074. pPage->pDbPage = pDbPage;
  48075. pPage->pBt = pBt;
  48076. pPage->pgno = pgno;
  48077. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  48078. return pPage;
  48079. }
  48080. /*
  48081. ** Get a page from the pager. Initialize the MemPage.pBt and
  48082. ** MemPage.aData elements if needed.
  48083. **
  48084. ** If the noContent flag is set, it means that we do not care about
  48085. ** the content of the page at this time. So do not go to the disk
  48086. ** to fetch the content. Just fill in the content with zeros for now.
  48087. ** If in the future we call sqlite3PagerWrite() on this page, that
  48088. ** means we have started to be concerned about content and the disk
  48089. ** read should occur at that point.
  48090. */
  48091. static int btreeGetPage(
  48092. BtShared *pBt, /* The btree */
  48093. Pgno pgno, /* Number of the page to fetch */
  48094. MemPage **ppPage, /* Return the page in this parameter */
  48095. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  48096. ){
  48097. int rc;
  48098. DbPage *pDbPage;
  48099. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  48100. assert( sqlite3_mutex_held(pBt->mutex) );
  48101. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  48102. if( rc ) return rc;
  48103. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  48104. return SQLITE_OK;
  48105. }
  48106. /*
  48107. ** Retrieve a page from the pager cache. If the requested page is not
  48108. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  48109. ** MemPage.aData elements if needed.
  48110. */
  48111. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  48112. DbPage *pDbPage;
  48113. assert( sqlite3_mutex_held(pBt->mutex) );
  48114. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  48115. if( pDbPage ){
  48116. return btreePageFromDbPage(pDbPage, pgno, pBt);
  48117. }
  48118. return 0;
  48119. }
  48120. /*
  48121. ** Return the size of the database file in pages. If there is any kind of
  48122. ** error, return ((unsigned int)-1).
  48123. */
  48124. static Pgno btreePagecount(BtShared *pBt){
  48125. return pBt->nPage;
  48126. }
  48127. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  48128. assert( sqlite3BtreeHoldsMutex(p) );
  48129. assert( ((p->pBt->nPage)&0x8000000)==0 );
  48130. return (int)btreePagecount(p->pBt);
  48131. }
  48132. /*
  48133. ** Get a page from the pager and initialize it. This routine is just a
  48134. ** convenience wrapper around separate calls to btreeGetPage() and
  48135. ** btreeInitPage().
  48136. **
  48137. ** If an error occurs, then the value *ppPage is set to is undefined. It
  48138. ** may remain unchanged, or it may be set to an invalid value.
  48139. */
  48140. static int getAndInitPage(
  48141. BtShared *pBt, /* The database file */
  48142. Pgno pgno, /* Number of the page to get */
  48143. MemPage **ppPage, /* Write the page pointer here */
  48144. int bReadonly /* PAGER_GET_READONLY or 0 */
  48145. ){
  48146. int rc;
  48147. assert( sqlite3_mutex_held(pBt->mutex) );
  48148. assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
  48149. if( pgno>btreePagecount(pBt) ){
  48150. rc = SQLITE_CORRUPT_BKPT;
  48151. }else{
  48152. rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
  48153. if( rc==SQLITE_OK ){
  48154. rc = btreeInitPage(*ppPage);
  48155. if( rc!=SQLITE_OK ){
  48156. releasePage(*ppPage);
  48157. }
  48158. }
  48159. }
  48160. testcase( pgno==0 );
  48161. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  48162. return rc;
  48163. }
  48164. /*
  48165. ** Release a MemPage. This should be called once for each prior
  48166. ** call to btreeGetPage.
  48167. */
  48168. static void releasePage(MemPage *pPage){
  48169. if( pPage ){
  48170. assert( pPage->aData );
  48171. assert( pPage->pBt );
  48172. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  48173. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  48174. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  48175. sqlite3PagerUnref(pPage->pDbPage);
  48176. }
  48177. }
  48178. /*
  48179. ** During a rollback, when the pager reloads information into the cache
  48180. ** so that the cache is restored to its original state at the start of
  48181. ** the transaction, for each page restored this routine is called.
  48182. **
  48183. ** This routine needs to reset the extra data section at the end of the
  48184. ** page to agree with the restored data.
  48185. */
  48186. static void pageReinit(DbPage *pData){
  48187. MemPage *pPage;
  48188. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  48189. assert( sqlite3PagerPageRefcount(pData)>0 );
  48190. if( pPage->isInit ){
  48191. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  48192. pPage->isInit = 0;
  48193. if( sqlite3PagerPageRefcount(pData)>1 ){
  48194. /* pPage might not be a btree page; it might be an overflow page
  48195. ** or ptrmap page or a free page. In those cases, the following
  48196. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  48197. ** But no harm is done by this. And it is very important that
  48198. ** btreeInitPage() be called on every btree page so we make
  48199. ** the call for every page that comes in for re-initing. */
  48200. btreeInitPage(pPage);
  48201. }
  48202. }
  48203. }
  48204. /*
  48205. ** Invoke the busy handler for a btree.
  48206. */
  48207. static int btreeInvokeBusyHandler(void *pArg){
  48208. BtShared *pBt = (BtShared*)pArg;
  48209. assert( pBt->db );
  48210. assert( sqlite3_mutex_held(pBt->db->mutex) );
  48211. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  48212. }
  48213. /*
  48214. ** Open a database file.
  48215. **
  48216. ** zFilename is the name of the database file. If zFilename is NULL
  48217. ** then an ephemeral database is created. The ephemeral database might
  48218. ** be exclusively in memory, or it might use a disk-based memory cache.
  48219. ** Either way, the ephemeral database will be automatically deleted
  48220. ** when sqlite3BtreeClose() is called.
  48221. **
  48222. ** If zFilename is ":memory:" then an in-memory database is created
  48223. ** that is automatically destroyed when it is closed.
  48224. **
  48225. ** The "flags" parameter is a bitmask that might contain bits like
  48226. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  48227. **
  48228. ** If the database is already opened in the same database connection
  48229. ** and we are in shared cache mode, then the open will fail with an
  48230. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  48231. ** objects in the same database connection since doing so will lead
  48232. ** to problems with locking.
  48233. */
  48234. SQLITE_PRIVATE int sqlite3BtreeOpen(
  48235. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  48236. const char *zFilename, /* Name of the file containing the BTree database */
  48237. sqlite3 *db, /* Associated database handle */
  48238. Btree **ppBtree, /* Pointer to new Btree object written here */
  48239. int flags, /* Options */
  48240. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  48241. ){
  48242. BtShared *pBt = 0; /* Shared part of btree structure */
  48243. Btree *p; /* Handle to return */
  48244. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  48245. int rc = SQLITE_OK; /* Result code from this function */
  48246. u8 nReserve; /* Byte of unused space on each page */
  48247. unsigned char zDbHeader[100]; /* Database header content */
  48248. /* True if opening an ephemeral, temporary database */
  48249. const int isTempDb = zFilename==0 || zFilename[0]==0;
  48250. /* Set the variable isMemdb to true for an in-memory database, or
  48251. ** false for a file-based database.
  48252. */
  48253. #ifdef SQLITE_OMIT_MEMORYDB
  48254. const int isMemdb = 0;
  48255. #else
  48256. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  48257. || (isTempDb && sqlite3TempInMemory(db))
  48258. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  48259. #endif
  48260. assert( db!=0 );
  48261. assert( pVfs!=0 );
  48262. assert( sqlite3_mutex_held(db->mutex) );
  48263. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  48264. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  48265. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  48266. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  48267. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  48268. if( isMemdb ){
  48269. flags |= BTREE_MEMORY;
  48270. }
  48271. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  48272. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  48273. }
  48274. p = sqlite3MallocZero(sizeof(Btree));
  48275. if( !p ){
  48276. return SQLITE_NOMEM;
  48277. }
  48278. p->inTrans = TRANS_NONE;
  48279. p->db = db;
  48280. #ifndef SQLITE_OMIT_SHARED_CACHE
  48281. p->lock.pBtree = p;
  48282. p->lock.iTable = 1;
  48283. #endif
  48284. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  48285. /*
  48286. ** If this Btree is a candidate for shared cache, try to find an
  48287. ** existing BtShared object that we can share with
  48288. */
  48289. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  48290. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  48291. int nFullPathname = pVfs->mxPathname+1;
  48292. char *zFullPathname = sqlite3Malloc(nFullPathname);
  48293. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  48294. p->sharable = 1;
  48295. if( !zFullPathname ){
  48296. sqlite3_free(p);
  48297. return SQLITE_NOMEM;
  48298. }
  48299. if( isMemdb ){
  48300. memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
  48301. }else{
  48302. rc = sqlite3OsFullPathname(pVfs, zFilename,
  48303. nFullPathname, zFullPathname);
  48304. if( rc ){
  48305. sqlite3_free(zFullPathname);
  48306. sqlite3_free(p);
  48307. return rc;
  48308. }
  48309. }
  48310. #if SQLITE_THREADSAFE
  48311. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  48312. sqlite3_mutex_enter(mutexOpen);
  48313. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  48314. sqlite3_mutex_enter(mutexShared);
  48315. #endif
  48316. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  48317. assert( pBt->nRef>0 );
  48318. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  48319. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  48320. int iDb;
  48321. for(iDb=db->nDb-1; iDb>=0; iDb--){
  48322. Btree *pExisting = db->aDb[iDb].pBt;
  48323. if( pExisting && pExisting->pBt==pBt ){
  48324. sqlite3_mutex_leave(mutexShared);
  48325. sqlite3_mutex_leave(mutexOpen);
  48326. sqlite3_free(zFullPathname);
  48327. sqlite3_free(p);
  48328. return SQLITE_CONSTRAINT;
  48329. }
  48330. }
  48331. p->pBt = pBt;
  48332. pBt->nRef++;
  48333. break;
  48334. }
  48335. }
  48336. sqlite3_mutex_leave(mutexShared);
  48337. sqlite3_free(zFullPathname);
  48338. }
  48339. #ifdef SQLITE_DEBUG
  48340. else{
  48341. /* In debug mode, we mark all persistent databases as sharable
  48342. ** even when they are not. This exercises the locking code and
  48343. ** gives more opportunity for asserts(sqlite3_mutex_held())
  48344. ** statements to find locking problems.
  48345. */
  48346. p->sharable = 1;
  48347. }
  48348. #endif
  48349. }
  48350. #endif
  48351. if( pBt==0 ){
  48352. /*
  48353. ** The following asserts make sure that structures used by the btree are
  48354. ** the right size. This is to guard against size changes that result
  48355. ** when compiling on a different architecture.
  48356. */
  48357. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  48358. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  48359. assert( sizeof(u32)==4 );
  48360. assert( sizeof(u16)==2 );
  48361. assert( sizeof(Pgno)==4 );
  48362. pBt = sqlite3MallocZero( sizeof(*pBt) );
  48363. if( pBt==0 ){
  48364. rc = SQLITE_NOMEM;
  48365. goto btree_open_out;
  48366. }
  48367. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  48368. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  48369. if( rc==SQLITE_OK ){
  48370. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  48371. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  48372. }
  48373. if( rc!=SQLITE_OK ){
  48374. goto btree_open_out;
  48375. }
  48376. pBt->openFlags = (u8)flags;
  48377. pBt->db = db;
  48378. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  48379. p->pBt = pBt;
  48380. pBt->pCursor = 0;
  48381. pBt->pPage1 = 0;
  48382. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  48383. #ifdef SQLITE_SECURE_DELETE
  48384. pBt->btsFlags |= BTS_SECURE_DELETE;
  48385. #endif
  48386. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  48387. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  48388. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  48389. pBt->pageSize = 0;
  48390. #ifndef SQLITE_OMIT_AUTOVACUUM
  48391. /* If the magic name ":memory:" will create an in-memory database, then
  48392. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  48393. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  48394. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  48395. ** regular file-name. In this case the auto-vacuum applies as per normal.
  48396. */
  48397. if( zFilename && !isMemdb ){
  48398. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  48399. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  48400. }
  48401. #endif
  48402. nReserve = 0;
  48403. }else{
  48404. nReserve = zDbHeader[20];
  48405. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  48406. #ifndef SQLITE_OMIT_AUTOVACUUM
  48407. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  48408. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  48409. #endif
  48410. }
  48411. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  48412. if( rc ) goto btree_open_out;
  48413. pBt->usableSize = pBt->pageSize - nReserve;
  48414. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  48415. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  48416. /* Add the new BtShared object to the linked list sharable BtShareds.
  48417. */
  48418. if( p->sharable ){
  48419. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  48420. pBt->nRef = 1;
  48421. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  48422. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  48423. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  48424. if( pBt->mutex==0 ){
  48425. rc = SQLITE_NOMEM;
  48426. db->mallocFailed = 0;
  48427. goto btree_open_out;
  48428. }
  48429. }
  48430. sqlite3_mutex_enter(mutexShared);
  48431. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  48432. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  48433. sqlite3_mutex_leave(mutexShared);
  48434. }
  48435. #endif
  48436. }
  48437. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  48438. /* If the new Btree uses a sharable pBtShared, then link the new
  48439. ** Btree into the list of all sharable Btrees for the same connection.
  48440. ** The list is kept in ascending order by pBt address.
  48441. */
  48442. if( p->sharable ){
  48443. int i;
  48444. Btree *pSib;
  48445. for(i=0; i<db->nDb; i++){
  48446. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  48447. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  48448. if( p->pBt<pSib->pBt ){
  48449. p->pNext = pSib;
  48450. p->pPrev = 0;
  48451. pSib->pPrev = p;
  48452. }else{
  48453. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  48454. pSib = pSib->pNext;
  48455. }
  48456. p->pNext = pSib->pNext;
  48457. p->pPrev = pSib;
  48458. if( p->pNext ){
  48459. p->pNext->pPrev = p;
  48460. }
  48461. pSib->pNext = p;
  48462. }
  48463. break;
  48464. }
  48465. }
  48466. }
  48467. #endif
  48468. *ppBtree = p;
  48469. btree_open_out:
  48470. if( rc!=SQLITE_OK ){
  48471. if( pBt && pBt->pPager ){
  48472. sqlite3PagerClose(pBt->pPager);
  48473. }
  48474. sqlite3_free(pBt);
  48475. sqlite3_free(p);
  48476. *ppBtree = 0;
  48477. }else{
  48478. /* If the B-Tree was successfully opened, set the pager-cache size to the
  48479. ** default value. Except, when opening on an existing shared pager-cache,
  48480. ** do not change the pager-cache size.
  48481. */
  48482. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  48483. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  48484. }
  48485. }
  48486. if( mutexOpen ){
  48487. assert( sqlite3_mutex_held(mutexOpen) );
  48488. sqlite3_mutex_leave(mutexOpen);
  48489. }
  48490. return rc;
  48491. }
  48492. /*
  48493. ** Decrement the BtShared.nRef counter. When it reaches zero,
  48494. ** remove the BtShared structure from the sharing list. Return
  48495. ** true if the BtShared.nRef counter reaches zero and return
  48496. ** false if it is still positive.
  48497. */
  48498. static int removeFromSharingList(BtShared *pBt){
  48499. #ifndef SQLITE_OMIT_SHARED_CACHE
  48500. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  48501. BtShared *pList;
  48502. int removed = 0;
  48503. assert( sqlite3_mutex_notheld(pBt->mutex) );
  48504. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  48505. sqlite3_mutex_enter(pMaster);
  48506. pBt->nRef--;
  48507. if( pBt->nRef<=0 ){
  48508. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  48509. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  48510. }else{
  48511. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  48512. while( ALWAYS(pList) && pList->pNext!=pBt ){
  48513. pList=pList->pNext;
  48514. }
  48515. if( ALWAYS(pList) ){
  48516. pList->pNext = pBt->pNext;
  48517. }
  48518. }
  48519. if( SQLITE_THREADSAFE ){
  48520. sqlite3_mutex_free(pBt->mutex);
  48521. }
  48522. removed = 1;
  48523. }
  48524. sqlite3_mutex_leave(pMaster);
  48525. return removed;
  48526. #else
  48527. return 1;
  48528. #endif
  48529. }
  48530. /*
  48531. ** Make sure pBt->pTmpSpace points to an allocation of
  48532. ** MX_CELL_SIZE(pBt) bytes.
  48533. */
  48534. static void allocateTempSpace(BtShared *pBt){
  48535. if( !pBt->pTmpSpace ){
  48536. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  48537. /* One of the uses of pBt->pTmpSpace is to format cells before
  48538. ** inserting them into a leaf page (function fillInCell()). If
  48539. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  48540. ** by the various routines that manipulate binary cells. Which
  48541. ** can mean that fillInCell() only initializes the first 2 or 3
  48542. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  48543. ** it into a database page. This is not actually a problem, but it
  48544. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  48545. ** data is passed to system call write(). So to avoid this error,
  48546. ** zero the first 4 bytes of temp space here. */
  48547. if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4);
  48548. }
  48549. }
  48550. /*
  48551. ** Free the pBt->pTmpSpace allocation
  48552. */
  48553. static void freeTempSpace(BtShared *pBt){
  48554. sqlite3PageFree( pBt->pTmpSpace);
  48555. pBt->pTmpSpace = 0;
  48556. }
  48557. /*
  48558. ** Close an open database and invalidate all cursors.
  48559. */
  48560. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  48561. BtShared *pBt = p->pBt;
  48562. BtCursor *pCur;
  48563. /* Close all cursors opened via this handle. */
  48564. assert( sqlite3_mutex_held(p->db->mutex) );
  48565. sqlite3BtreeEnter(p);
  48566. pCur = pBt->pCursor;
  48567. while( pCur ){
  48568. BtCursor *pTmp = pCur;
  48569. pCur = pCur->pNext;
  48570. if( pTmp->pBtree==p ){
  48571. sqlite3BtreeCloseCursor(pTmp);
  48572. }
  48573. }
  48574. /* Rollback any active transaction and free the handle structure.
  48575. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  48576. ** this handle.
  48577. */
  48578. sqlite3BtreeRollback(p, SQLITE_OK);
  48579. sqlite3BtreeLeave(p);
  48580. /* If there are still other outstanding references to the shared-btree
  48581. ** structure, return now. The remainder of this procedure cleans
  48582. ** up the shared-btree.
  48583. */
  48584. assert( p->wantToLock==0 && p->locked==0 );
  48585. if( !p->sharable || removeFromSharingList(pBt) ){
  48586. /* The pBt is no longer on the sharing list, so we can access
  48587. ** it without having to hold the mutex.
  48588. **
  48589. ** Clean out and delete the BtShared object.
  48590. */
  48591. assert( !pBt->pCursor );
  48592. sqlite3PagerClose(pBt->pPager);
  48593. if( pBt->xFreeSchema && pBt->pSchema ){
  48594. pBt->xFreeSchema(pBt->pSchema);
  48595. }
  48596. sqlite3DbFree(0, pBt->pSchema);
  48597. freeTempSpace(pBt);
  48598. sqlite3_free(pBt);
  48599. }
  48600. #ifndef SQLITE_OMIT_SHARED_CACHE
  48601. assert( p->wantToLock==0 );
  48602. assert( p->locked==0 );
  48603. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  48604. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  48605. #endif
  48606. sqlite3_free(p);
  48607. return SQLITE_OK;
  48608. }
  48609. /*
  48610. ** Change the limit on the number of pages allowed in the cache.
  48611. **
  48612. ** The maximum number of cache pages is set to the absolute
  48613. ** value of mxPage. If mxPage is negative, the pager will
  48614. ** operate asynchronously - it will not stop to do fsync()s
  48615. ** to insure data is written to the disk surface before
  48616. ** continuing. Transactions still work if synchronous is off,
  48617. ** and the database cannot be corrupted if this program
  48618. ** crashes. But if the operating system crashes or there is
  48619. ** an abrupt power failure when synchronous is off, the database
  48620. ** could be left in an inconsistent and unrecoverable state.
  48621. ** Synchronous is on by default so database corruption is not
  48622. ** normally a worry.
  48623. */
  48624. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  48625. BtShared *pBt = p->pBt;
  48626. assert( sqlite3_mutex_held(p->db->mutex) );
  48627. sqlite3BtreeEnter(p);
  48628. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  48629. sqlite3BtreeLeave(p);
  48630. return SQLITE_OK;
  48631. }
  48632. /*
  48633. ** Change the limit on the amount of the database file that may be
  48634. ** memory mapped.
  48635. */
  48636. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  48637. BtShared *pBt = p->pBt;
  48638. assert( sqlite3_mutex_held(p->db->mutex) );
  48639. sqlite3BtreeEnter(p);
  48640. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  48641. sqlite3BtreeLeave(p);
  48642. return SQLITE_OK;
  48643. }
  48644. /*
  48645. ** Change the way data is synced to disk in order to increase or decrease
  48646. ** how well the database resists damage due to OS crashes and power
  48647. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  48648. ** there is a high probability of damage) Level 2 is the default. There
  48649. ** is a very low but non-zero probability of damage. Level 3 reduces the
  48650. ** probability of damage to near zero but with a write performance reduction.
  48651. */
  48652. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  48653. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  48654. Btree *p, /* The btree to set the safety level on */
  48655. unsigned pgFlags /* Various PAGER_* flags */
  48656. ){
  48657. BtShared *pBt = p->pBt;
  48658. assert( sqlite3_mutex_held(p->db->mutex) );
  48659. sqlite3BtreeEnter(p);
  48660. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  48661. sqlite3BtreeLeave(p);
  48662. return SQLITE_OK;
  48663. }
  48664. #endif
  48665. /*
  48666. ** Return TRUE if the given btree is set to safety level 1. In other
  48667. ** words, return TRUE if no sync() occurs on the disk files.
  48668. */
  48669. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  48670. BtShared *pBt = p->pBt;
  48671. int rc;
  48672. assert( sqlite3_mutex_held(p->db->mutex) );
  48673. sqlite3BtreeEnter(p);
  48674. assert( pBt && pBt->pPager );
  48675. rc = sqlite3PagerNosync(pBt->pPager);
  48676. sqlite3BtreeLeave(p);
  48677. return rc;
  48678. }
  48679. /*
  48680. ** Change the default pages size and the number of reserved bytes per page.
  48681. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  48682. ** without changing anything.
  48683. **
  48684. ** The page size must be a power of 2 between 512 and 65536. If the page
  48685. ** size supplied does not meet this constraint then the page size is not
  48686. ** changed.
  48687. **
  48688. ** Page sizes are constrained to be a power of two so that the region
  48689. ** of the database file used for locking (beginning at PENDING_BYTE,
  48690. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  48691. ** at the beginning of a page.
  48692. **
  48693. ** If parameter nReserve is less than zero, then the number of reserved
  48694. ** bytes per page is left unchanged.
  48695. **
  48696. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  48697. ** and autovacuum mode can no longer be changed.
  48698. */
  48699. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  48700. int rc = SQLITE_OK;
  48701. BtShared *pBt = p->pBt;
  48702. assert( nReserve>=-1 && nReserve<=255 );
  48703. sqlite3BtreeEnter(p);
  48704. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  48705. sqlite3BtreeLeave(p);
  48706. return SQLITE_READONLY;
  48707. }
  48708. if( nReserve<0 ){
  48709. nReserve = pBt->pageSize - pBt->usableSize;
  48710. }
  48711. assert( nReserve>=0 && nReserve<=255 );
  48712. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  48713. ((pageSize-1)&pageSize)==0 ){
  48714. assert( (pageSize & 7)==0 );
  48715. assert( !pBt->pPage1 && !pBt->pCursor );
  48716. pBt->pageSize = (u32)pageSize;
  48717. freeTempSpace(pBt);
  48718. }
  48719. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  48720. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  48721. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  48722. sqlite3BtreeLeave(p);
  48723. return rc;
  48724. }
  48725. /*
  48726. ** Return the currently defined page size
  48727. */
  48728. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  48729. return p->pBt->pageSize;
  48730. }
  48731. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  48732. /*
  48733. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  48734. ** may only be called if it is guaranteed that the b-tree mutex is already
  48735. ** held.
  48736. **
  48737. ** This is useful in one special case in the backup API code where it is
  48738. ** known that the shared b-tree mutex is held, but the mutex on the
  48739. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  48740. ** were to be called, it might collide with some other operation on the
  48741. ** database handle that owns *p, causing undefined behavior.
  48742. */
  48743. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  48744. assert( sqlite3_mutex_held(p->pBt->mutex) );
  48745. return p->pBt->pageSize - p->pBt->usableSize;
  48746. }
  48747. #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
  48748. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  48749. /*
  48750. ** Return the number of bytes of space at the end of every page that
  48751. ** are intentually left unused. This is the "reserved" space that is
  48752. ** sometimes used by extensions.
  48753. */
  48754. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  48755. int n;
  48756. sqlite3BtreeEnter(p);
  48757. n = p->pBt->pageSize - p->pBt->usableSize;
  48758. sqlite3BtreeLeave(p);
  48759. return n;
  48760. }
  48761. /*
  48762. ** Set the maximum page count for a database if mxPage is positive.
  48763. ** No changes are made if mxPage is 0 or negative.
  48764. ** Regardless of the value of mxPage, return the maximum page count.
  48765. */
  48766. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  48767. int n;
  48768. sqlite3BtreeEnter(p);
  48769. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  48770. sqlite3BtreeLeave(p);
  48771. return n;
  48772. }
  48773. /*
  48774. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  48775. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  48776. ** setting after the change.
  48777. */
  48778. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  48779. int b;
  48780. if( p==0 ) return 0;
  48781. sqlite3BtreeEnter(p);
  48782. if( newFlag>=0 ){
  48783. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  48784. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  48785. }
  48786. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  48787. sqlite3BtreeLeave(p);
  48788. return b;
  48789. }
  48790. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  48791. /*
  48792. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  48793. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  48794. ** is disabled. The default value for the auto-vacuum property is
  48795. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  48796. */
  48797. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  48798. #ifdef SQLITE_OMIT_AUTOVACUUM
  48799. return SQLITE_READONLY;
  48800. #else
  48801. BtShared *pBt = p->pBt;
  48802. int rc = SQLITE_OK;
  48803. u8 av = (u8)autoVacuum;
  48804. sqlite3BtreeEnter(p);
  48805. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  48806. rc = SQLITE_READONLY;
  48807. }else{
  48808. pBt->autoVacuum = av ?1:0;
  48809. pBt->incrVacuum = av==2 ?1:0;
  48810. }
  48811. sqlite3BtreeLeave(p);
  48812. return rc;
  48813. #endif
  48814. }
  48815. /*
  48816. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  48817. ** enabled 1 is returned. Otherwise 0.
  48818. */
  48819. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  48820. #ifdef SQLITE_OMIT_AUTOVACUUM
  48821. return BTREE_AUTOVACUUM_NONE;
  48822. #else
  48823. int rc;
  48824. sqlite3BtreeEnter(p);
  48825. rc = (
  48826. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  48827. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  48828. BTREE_AUTOVACUUM_INCR
  48829. );
  48830. sqlite3BtreeLeave(p);
  48831. return rc;
  48832. #endif
  48833. }
  48834. /*
  48835. ** Get a reference to pPage1 of the database file. This will
  48836. ** also acquire a readlock on that file.
  48837. **
  48838. ** SQLITE_OK is returned on success. If the file is not a
  48839. ** well-formed database file, then SQLITE_CORRUPT is returned.
  48840. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  48841. ** is returned if we run out of memory.
  48842. */
  48843. static int lockBtree(BtShared *pBt){
  48844. int rc; /* Result code from subfunctions */
  48845. MemPage *pPage1; /* Page 1 of the database file */
  48846. int nPage; /* Number of pages in the database */
  48847. int nPageFile = 0; /* Number of pages in the database file */
  48848. int nPageHeader; /* Number of pages in the database according to hdr */
  48849. assert( sqlite3_mutex_held(pBt->mutex) );
  48850. assert( pBt->pPage1==0 );
  48851. rc = sqlite3PagerSharedLock(pBt->pPager);
  48852. if( rc!=SQLITE_OK ) return rc;
  48853. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  48854. if( rc!=SQLITE_OK ) return rc;
  48855. /* Do some checking to help insure the file we opened really is
  48856. ** a valid database file.
  48857. */
  48858. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  48859. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  48860. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  48861. nPage = nPageFile;
  48862. }
  48863. if( nPage>0 ){
  48864. u32 pageSize;
  48865. u32 usableSize;
  48866. u8 *page1 = pPage1->aData;
  48867. rc = SQLITE_NOTADB;
  48868. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  48869. goto page1_init_failed;
  48870. }
  48871. #ifdef SQLITE_OMIT_WAL
  48872. if( page1[18]>1 ){
  48873. pBt->btsFlags |= BTS_READ_ONLY;
  48874. }
  48875. if( page1[19]>1 ){
  48876. goto page1_init_failed;
  48877. }
  48878. #else
  48879. if( page1[18]>2 ){
  48880. pBt->btsFlags |= BTS_READ_ONLY;
  48881. }
  48882. if( page1[19]>2 ){
  48883. goto page1_init_failed;
  48884. }
  48885. /* If the write version is set to 2, this database should be accessed
  48886. ** in WAL mode. If the log is not already open, open it now. Then
  48887. ** return SQLITE_OK and return without populating BtShared.pPage1.
  48888. ** The caller detects this and calls this function again. This is
  48889. ** required as the version of page 1 currently in the page1 buffer
  48890. ** may not be the latest version - there may be a newer one in the log
  48891. ** file.
  48892. */
  48893. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  48894. int isOpen = 0;
  48895. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  48896. if( rc!=SQLITE_OK ){
  48897. goto page1_init_failed;
  48898. }else if( isOpen==0 ){
  48899. releasePage(pPage1);
  48900. return SQLITE_OK;
  48901. }
  48902. rc = SQLITE_NOTADB;
  48903. }
  48904. #endif
  48905. /* The maximum embedded fraction must be exactly 25%. And the minimum
  48906. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  48907. ** The original design allowed these amounts to vary, but as of
  48908. ** version 3.6.0, we require them to be fixed.
  48909. */
  48910. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  48911. goto page1_init_failed;
  48912. }
  48913. pageSize = (page1[16]<<8) | (page1[17]<<16);
  48914. if( ((pageSize-1)&pageSize)!=0
  48915. || pageSize>SQLITE_MAX_PAGE_SIZE
  48916. || pageSize<=256
  48917. ){
  48918. goto page1_init_failed;
  48919. }
  48920. assert( (pageSize & 7)==0 );
  48921. usableSize = pageSize - page1[20];
  48922. if( (u32)pageSize!=pBt->pageSize ){
  48923. /* After reading the first page of the database assuming a page size
  48924. ** of BtShared.pageSize, we have discovered that the page-size is
  48925. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  48926. ** zero and return SQLITE_OK. The caller will call this function
  48927. ** again with the correct page-size.
  48928. */
  48929. releasePage(pPage1);
  48930. pBt->usableSize = usableSize;
  48931. pBt->pageSize = pageSize;
  48932. freeTempSpace(pBt);
  48933. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  48934. pageSize-usableSize);
  48935. return rc;
  48936. }
  48937. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  48938. rc = SQLITE_CORRUPT_BKPT;
  48939. goto page1_init_failed;
  48940. }
  48941. if( usableSize<480 ){
  48942. goto page1_init_failed;
  48943. }
  48944. pBt->pageSize = pageSize;
  48945. pBt->usableSize = usableSize;
  48946. #ifndef SQLITE_OMIT_AUTOVACUUM
  48947. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  48948. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  48949. #endif
  48950. }
  48951. /* maxLocal is the maximum amount of payload to store locally for
  48952. ** a cell. Make sure it is small enough so that at least minFanout
  48953. ** cells can will fit on one page. We assume a 10-byte page header.
  48954. ** Besides the payload, the cell must store:
  48955. ** 2-byte pointer to the cell
  48956. ** 4-byte child pointer
  48957. ** 9-byte nKey value
  48958. ** 4-byte nData value
  48959. ** 4-byte overflow page pointer
  48960. ** So a cell consists of a 2-byte pointer, a header which is as much as
  48961. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  48962. ** page pointer.
  48963. */
  48964. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  48965. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  48966. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  48967. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  48968. if( pBt->maxLocal>127 ){
  48969. pBt->max1bytePayload = 127;
  48970. }else{
  48971. pBt->max1bytePayload = (u8)pBt->maxLocal;
  48972. }
  48973. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  48974. pBt->pPage1 = pPage1;
  48975. pBt->nPage = nPage;
  48976. return SQLITE_OK;
  48977. page1_init_failed:
  48978. releasePage(pPage1);
  48979. pBt->pPage1 = 0;
  48980. return rc;
  48981. }
  48982. #ifndef NDEBUG
  48983. /*
  48984. ** Return the number of cursors open on pBt. This is for use
  48985. ** in assert() expressions, so it is only compiled if NDEBUG is not
  48986. ** defined.
  48987. **
  48988. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  48989. ** false then all cursors are counted.
  48990. **
  48991. ** For the purposes of this routine, a cursor is any cursor that
  48992. ** is capable of reading or writing to the databse. Cursors that
  48993. ** have been tripped into the CURSOR_FAULT state are not counted.
  48994. */
  48995. static int countValidCursors(BtShared *pBt, int wrOnly){
  48996. BtCursor *pCur;
  48997. int r = 0;
  48998. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  48999. if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++;
  49000. }
  49001. return r;
  49002. }
  49003. #endif
  49004. /*
  49005. ** If there are no outstanding cursors and we are not in the middle
  49006. ** of a transaction but there is a read lock on the database, then
  49007. ** this routine unrefs the first page of the database file which
  49008. ** has the effect of releasing the read lock.
  49009. **
  49010. ** If there is a transaction in progress, this routine is a no-op.
  49011. */
  49012. static void unlockBtreeIfUnused(BtShared *pBt){
  49013. assert( sqlite3_mutex_held(pBt->mutex) );
  49014. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  49015. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  49016. assert( pBt->pPage1->aData );
  49017. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  49018. assert( pBt->pPage1->aData );
  49019. releasePage(pBt->pPage1);
  49020. pBt->pPage1 = 0;
  49021. }
  49022. }
  49023. /*
  49024. ** If pBt points to an empty file then convert that empty file
  49025. ** into a new empty database by initializing the first page of
  49026. ** the database.
  49027. */
  49028. static int newDatabase(BtShared *pBt){
  49029. MemPage *pP1;
  49030. unsigned char *data;
  49031. int rc;
  49032. assert( sqlite3_mutex_held(pBt->mutex) );
  49033. if( pBt->nPage>0 ){
  49034. return SQLITE_OK;
  49035. }
  49036. pP1 = pBt->pPage1;
  49037. assert( pP1!=0 );
  49038. data = pP1->aData;
  49039. rc = sqlite3PagerWrite(pP1->pDbPage);
  49040. if( rc ) return rc;
  49041. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  49042. assert( sizeof(zMagicHeader)==16 );
  49043. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  49044. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  49045. data[18] = 1;
  49046. data[19] = 1;
  49047. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  49048. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  49049. data[21] = 64;
  49050. data[22] = 32;
  49051. data[23] = 32;
  49052. memset(&data[24], 0, 100-24);
  49053. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  49054. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  49055. #ifndef SQLITE_OMIT_AUTOVACUUM
  49056. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  49057. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  49058. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  49059. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  49060. #endif
  49061. pBt->nPage = 1;
  49062. data[31] = 1;
  49063. return SQLITE_OK;
  49064. }
  49065. /*
  49066. ** Initialize the first page of the database file (creating a database
  49067. ** consisting of a single page and no schema objects). Return SQLITE_OK
  49068. ** if successful, or an SQLite error code otherwise.
  49069. */
  49070. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  49071. int rc;
  49072. sqlite3BtreeEnter(p);
  49073. p->pBt->nPage = 0;
  49074. rc = newDatabase(p->pBt);
  49075. sqlite3BtreeLeave(p);
  49076. return rc;
  49077. }
  49078. /*
  49079. ** Attempt to start a new transaction. A write-transaction
  49080. ** is started if the second argument is nonzero, otherwise a read-
  49081. ** transaction. If the second argument is 2 or more and exclusive
  49082. ** transaction is started, meaning that no other process is allowed
  49083. ** to access the database. A preexisting transaction may not be
  49084. ** upgraded to exclusive by calling this routine a second time - the
  49085. ** exclusivity flag only works for a new transaction.
  49086. **
  49087. ** A write-transaction must be started before attempting any
  49088. ** changes to the database. None of the following routines
  49089. ** will work unless a transaction is started first:
  49090. **
  49091. ** sqlite3BtreeCreateTable()
  49092. ** sqlite3BtreeCreateIndex()
  49093. ** sqlite3BtreeClearTable()
  49094. ** sqlite3BtreeDropTable()
  49095. ** sqlite3BtreeInsert()
  49096. ** sqlite3BtreeDelete()
  49097. ** sqlite3BtreeUpdateMeta()
  49098. **
  49099. ** If an initial attempt to acquire the lock fails because of lock contention
  49100. ** and the database was previously unlocked, then invoke the busy handler
  49101. ** if there is one. But if there was previously a read-lock, do not
  49102. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  49103. ** returned when there is already a read-lock in order to avoid a deadlock.
  49104. **
  49105. ** Suppose there are two processes A and B. A has a read lock and B has
  49106. ** a reserved lock. B tries to promote to exclusive but is blocked because
  49107. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  49108. ** One or the other of the two processes must give way or there can be
  49109. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  49110. ** when A already has a read lock, we encourage A to give up and let B
  49111. ** proceed.
  49112. */
  49113. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  49114. sqlite3 *pBlock = 0;
  49115. BtShared *pBt = p->pBt;
  49116. int rc = SQLITE_OK;
  49117. sqlite3BtreeEnter(p);
  49118. btreeIntegrity(p);
  49119. /* If the btree is already in a write-transaction, or it
  49120. ** is already in a read-transaction and a read-transaction
  49121. ** is requested, this is a no-op.
  49122. */
  49123. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  49124. goto trans_begun;
  49125. }
  49126. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  49127. /* Write transactions are not possible on a read-only database */
  49128. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  49129. rc = SQLITE_READONLY;
  49130. goto trans_begun;
  49131. }
  49132. #ifndef SQLITE_OMIT_SHARED_CACHE
  49133. /* If another database handle has already opened a write transaction
  49134. ** on this shared-btree structure and a second write transaction is
  49135. ** requested, return SQLITE_LOCKED.
  49136. */
  49137. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  49138. || (pBt->btsFlags & BTS_PENDING)!=0
  49139. ){
  49140. pBlock = pBt->pWriter->db;
  49141. }else if( wrflag>1 ){
  49142. BtLock *pIter;
  49143. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  49144. if( pIter->pBtree!=p ){
  49145. pBlock = pIter->pBtree->db;
  49146. break;
  49147. }
  49148. }
  49149. }
  49150. if( pBlock ){
  49151. sqlite3ConnectionBlocked(p->db, pBlock);
  49152. rc = SQLITE_LOCKED_SHAREDCACHE;
  49153. goto trans_begun;
  49154. }
  49155. #endif
  49156. /* Any read-only or read-write transaction implies a read-lock on
  49157. ** page 1. So if some other shared-cache client already has a write-lock
  49158. ** on page 1, the transaction cannot be opened. */
  49159. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  49160. if( SQLITE_OK!=rc ) goto trans_begun;
  49161. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  49162. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  49163. do {
  49164. /* Call lockBtree() until either pBt->pPage1 is populated or
  49165. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  49166. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  49167. ** reading page 1 it discovers that the page-size of the database
  49168. ** file is not pBt->pageSize. In this case lockBtree() will update
  49169. ** pBt->pageSize to the page-size of the file on disk.
  49170. */
  49171. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  49172. if( rc==SQLITE_OK && wrflag ){
  49173. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  49174. rc = SQLITE_READONLY;
  49175. }else{
  49176. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  49177. if( rc==SQLITE_OK ){
  49178. rc = newDatabase(pBt);
  49179. }
  49180. }
  49181. }
  49182. if( rc!=SQLITE_OK ){
  49183. unlockBtreeIfUnused(pBt);
  49184. }
  49185. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  49186. btreeInvokeBusyHandler(pBt) );
  49187. if( rc==SQLITE_OK ){
  49188. if( p->inTrans==TRANS_NONE ){
  49189. pBt->nTransaction++;
  49190. #ifndef SQLITE_OMIT_SHARED_CACHE
  49191. if( p->sharable ){
  49192. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  49193. p->lock.eLock = READ_LOCK;
  49194. p->lock.pNext = pBt->pLock;
  49195. pBt->pLock = &p->lock;
  49196. }
  49197. #endif
  49198. }
  49199. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  49200. if( p->inTrans>pBt->inTransaction ){
  49201. pBt->inTransaction = p->inTrans;
  49202. }
  49203. if( wrflag ){
  49204. MemPage *pPage1 = pBt->pPage1;
  49205. #ifndef SQLITE_OMIT_SHARED_CACHE
  49206. assert( !pBt->pWriter );
  49207. pBt->pWriter = p;
  49208. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  49209. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  49210. #endif
  49211. /* If the db-size header field is incorrect (as it may be if an old
  49212. ** client has been writing the database file), update it now. Doing
  49213. ** this sooner rather than later means the database size can safely
  49214. ** re-read the database size from page 1 if a savepoint or transaction
  49215. ** rollback occurs within the transaction.
  49216. */
  49217. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  49218. rc = sqlite3PagerWrite(pPage1->pDbPage);
  49219. if( rc==SQLITE_OK ){
  49220. put4byte(&pPage1->aData[28], pBt->nPage);
  49221. }
  49222. }
  49223. }
  49224. }
  49225. trans_begun:
  49226. if( rc==SQLITE_OK && wrflag ){
  49227. /* This call makes sure that the pager has the correct number of
  49228. ** open savepoints. If the second parameter is greater than 0 and
  49229. ** the sub-journal is not already open, then it will be opened here.
  49230. */
  49231. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  49232. }
  49233. btreeIntegrity(p);
  49234. sqlite3BtreeLeave(p);
  49235. return rc;
  49236. }
  49237. #ifndef SQLITE_OMIT_AUTOVACUUM
  49238. /*
  49239. ** Set the pointer-map entries for all children of page pPage. Also, if
  49240. ** pPage contains cells that point to overflow pages, set the pointer
  49241. ** map entries for the overflow pages as well.
  49242. */
  49243. static int setChildPtrmaps(MemPage *pPage){
  49244. int i; /* Counter variable */
  49245. int nCell; /* Number of cells in page pPage */
  49246. int rc; /* Return code */
  49247. BtShared *pBt = pPage->pBt;
  49248. u8 isInitOrig = pPage->isInit;
  49249. Pgno pgno = pPage->pgno;
  49250. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49251. rc = btreeInitPage(pPage);
  49252. if( rc!=SQLITE_OK ){
  49253. goto set_child_ptrmaps_out;
  49254. }
  49255. nCell = pPage->nCell;
  49256. for(i=0; i<nCell; i++){
  49257. u8 *pCell = findCell(pPage, i);
  49258. ptrmapPutOvflPtr(pPage, pCell, &rc);
  49259. if( !pPage->leaf ){
  49260. Pgno childPgno = get4byte(pCell);
  49261. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  49262. }
  49263. }
  49264. if( !pPage->leaf ){
  49265. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  49266. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  49267. }
  49268. set_child_ptrmaps_out:
  49269. pPage->isInit = isInitOrig;
  49270. return rc;
  49271. }
  49272. /*
  49273. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  49274. ** that it points to iTo. Parameter eType describes the type of pointer to
  49275. ** be modified, as follows:
  49276. **
  49277. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  49278. ** page of pPage.
  49279. **
  49280. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  49281. ** page pointed to by one of the cells on pPage.
  49282. **
  49283. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  49284. ** overflow page in the list.
  49285. */
  49286. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  49287. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49288. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  49289. if( eType==PTRMAP_OVERFLOW2 ){
  49290. /* The pointer is always the first 4 bytes of the page in this case. */
  49291. if( get4byte(pPage->aData)!=iFrom ){
  49292. return SQLITE_CORRUPT_BKPT;
  49293. }
  49294. put4byte(pPage->aData, iTo);
  49295. }else{
  49296. u8 isInitOrig = pPage->isInit;
  49297. int i;
  49298. int nCell;
  49299. btreeInitPage(pPage);
  49300. nCell = pPage->nCell;
  49301. for(i=0; i<nCell; i++){
  49302. u8 *pCell = findCell(pPage, i);
  49303. if( eType==PTRMAP_OVERFLOW1 ){
  49304. CellInfo info;
  49305. btreeParseCellPtr(pPage, pCell, &info);
  49306. if( info.iOverflow
  49307. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  49308. && iFrom==get4byte(&pCell[info.iOverflow])
  49309. ){
  49310. put4byte(&pCell[info.iOverflow], iTo);
  49311. break;
  49312. }
  49313. }else{
  49314. if( get4byte(pCell)==iFrom ){
  49315. put4byte(pCell, iTo);
  49316. break;
  49317. }
  49318. }
  49319. }
  49320. if( i==nCell ){
  49321. if( eType!=PTRMAP_BTREE ||
  49322. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  49323. return SQLITE_CORRUPT_BKPT;
  49324. }
  49325. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  49326. }
  49327. pPage->isInit = isInitOrig;
  49328. }
  49329. return SQLITE_OK;
  49330. }
  49331. /*
  49332. ** Move the open database page pDbPage to location iFreePage in the
  49333. ** database. The pDbPage reference remains valid.
  49334. **
  49335. ** The isCommit flag indicates that there is no need to remember that
  49336. ** the journal needs to be sync()ed before database page pDbPage->pgno
  49337. ** can be written to. The caller has already promised not to write to that
  49338. ** page.
  49339. */
  49340. static int relocatePage(
  49341. BtShared *pBt, /* Btree */
  49342. MemPage *pDbPage, /* Open page to move */
  49343. u8 eType, /* Pointer map 'type' entry for pDbPage */
  49344. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  49345. Pgno iFreePage, /* The location to move pDbPage to */
  49346. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  49347. ){
  49348. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  49349. Pgno iDbPage = pDbPage->pgno;
  49350. Pager *pPager = pBt->pPager;
  49351. int rc;
  49352. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  49353. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  49354. assert( sqlite3_mutex_held(pBt->mutex) );
  49355. assert( pDbPage->pBt==pBt );
  49356. /* Move page iDbPage from its current location to page number iFreePage */
  49357. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  49358. iDbPage, iFreePage, iPtrPage, eType));
  49359. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  49360. if( rc!=SQLITE_OK ){
  49361. return rc;
  49362. }
  49363. pDbPage->pgno = iFreePage;
  49364. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  49365. ** that point to overflow pages. The pointer map entries for all these
  49366. ** pages need to be changed.
  49367. **
  49368. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  49369. ** pointer to a subsequent overflow page. If this is the case, then
  49370. ** the pointer map needs to be updated for the subsequent overflow page.
  49371. */
  49372. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  49373. rc = setChildPtrmaps(pDbPage);
  49374. if( rc!=SQLITE_OK ){
  49375. return rc;
  49376. }
  49377. }else{
  49378. Pgno nextOvfl = get4byte(pDbPage->aData);
  49379. if( nextOvfl!=0 ){
  49380. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  49381. if( rc!=SQLITE_OK ){
  49382. return rc;
  49383. }
  49384. }
  49385. }
  49386. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  49387. ** that it points at iFreePage. Also fix the pointer map entry for
  49388. ** iPtrPage.
  49389. */
  49390. if( eType!=PTRMAP_ROOTPAGE ){
  49391. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  49392. if( rc!=SQLITE_OK ){
  49393. return rc;
  49394. }
  49395. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  49396. if( rc!=SQLITE_OK ){
  49397. releasePage(pPtrPage);
  49398. return rc;
  49399. }
  49400. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  49401. releasePage(pPtrPage);
  49402. if( rc==SQLITE_OK ){
  49403. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  49404. }
  49405. }
  49406. return rc;
  49407. }
  49408. /* Forward declaration required by incrVacuumStep(). */
  49409. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  49410. /*
  49411. ** Perform a single step of an incremental-vacuum. If successful, return
  49412. ** SQLITE_OK. If there is no work to do (and therefore no point in
  49413. ** calling this function again), return SQLITE_DONE. Or, if an error
  49414. ** occurs, return some other error code.
  49415. **
  49416. ** More specificly, this function attempts to re-organize the database so
  49417. ** that the last page of the file currently in use is no longer in use.
  49418. **
  49419. ** Parameter nFin is the number of pages that this database would contain
  49420. ** were this function called until it returns SQLITE_DONE.
  49421. **
  49422. ** If the bCommit parameter is non-zero, this function assumes that the
  49423. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  49424. ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
  49425. ** operation, or false for an incremental vacuum.
  49426. */
  49427. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  49428. Pgno nFreeList; /* Number of pages still on the free-list */
  49429. int rc;
  49430. assert( sqlite3_mutex_held(pBt->mutex) );
  49431. assert( iLastPg>nFin );
  49432. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  49433. u8 eType;
  49434. Pgno iPtrPage;
  49435. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  49436. if( nFreeList==0 ){
  49437. return SQLITE_DONE;
  49438. }
  49439. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  49440. if( rc!=SQLITE_OK ){
  49441. return rc;
  49442. }
  49443. if( eType==PTRMAP_ROOTPAGE ){
  49444. return SQLITE_CORRUPT_BKPT;
  49445. }
  49446. if( eType==PTRMAP_FREEPAGE ){
  49447. if( bCommit==0 ){
  49448. /* Remove the page from the files free-list. This is not required
  49449. ** if bCommit is non-zero. In that case, the free-list will be
  49450. ** truncated to zero after this function returns, so it doesn't
  49451. ** matter if it still contains some garbage entries.
  49452. */
  49453. Pgno iFreePg;
  49454. MemPage *pFreePg;
  49455. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  49456. if( rc!=SQLITE_OK ){
  49457. return rc;
  49458. }
  49459. assert( iFreePg==iLastPg );
  49460. releasePage(pFreePg);
  49461. }
  49462. } else {
  49463. Pgno iFreePg; /* Index of free page to move pLastPg to */
  49464. MemPage *pLastPg;
  49465. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  49466. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  49467. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  49468. if( rc!=SQLITE_OK ){
  49469. return rc;
  49470. }
  49471. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  49472. ** is swapped with the first free page pulled off the free list.
  49473. **
  49474. ** On the other hand, if bCommit is greater than zero, then keep
  49475. ** looping until a free-page located within the first nFin pages
  49476. ** of the file is found.
  49477. */
  49478. if( bCommit==0 ){
  49479. eMode = BTALLOC_LE;
  49480. iNear = nFin;
  49481. }
  49482. do {
  49483. MemPage *pFreePg;
  49484. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  49485. if( rc!=SQLITE_OK ){
  49486. releasePage(pLastPg);
  49487. return rc;
  49488. }
  49489. releasePage(pFreePg);
  49490. }while( bCommit && iFreePg>nFin );
  49491. assert( iFreePg<iLastPg );
  49492. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  49493. releasePage(pLastPg);
  49494. if( rc!=SQLITE_OK ){
  49495. return rc;
  49496. }
  49497. }
  49498. }
  49499. if( bCommit==0 ){
  49500. do {
  49501. iLastPg--;
  49502. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  49503. pBt->bDoTruncate = 1;
  49504. pBt->nPage = iLastPg;
  49505. }
  49506. return SQLITE_OK;
  49507. }
  49508. /*
  49509. ** The database opened by the first argument is an auto-vacuum database
  49510. ** nOrig pages in size containing nFree free pages. Return the expected
  49511. ** size of the database in pages following an auto-vacuum operation.
  49512. */
  49513. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  49514. int nEntry; /* Number of entries on one ptrmap page */
  49515. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  49516. Pgno nFin; /* Return value */
  49517. nEntry = pBt->usableSize/5;
  49518. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  49519. nFin = nOrig - nFree - nPtrmap;
  49520. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  49521. nFin--;
  49522. }
  49523. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  49524. nFin--;
  49525. }
  49526. return nFin;
  49527. }
  49528. /*
  49529. ** A write-transaction must be opened before calling this function.
  49530. ** It performs a single unit of work towards an incremental vacuum.
  49531. **
  49532. ** If the incremental vacuum is finished after this function has run,
  49533. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  49534. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  49535. */
  49536. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  49537. int rc;
  49538. BtShared *pBt = p->pBt;
  49539. sqlite3BtreeEnter(p);
  49540. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  49541. if( !pBt->autoVacuum ){
  49542. rc = SQLITE_DONE;
  49543. }else{
  49544. Pgno nOrig = btreePagecount(pBt);
  49545. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  49546. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  49547. if( nOrig<nFin ){
  49548. rc = SQLITE_CORRUPT_BKPT;
  49549. }else if( nFree>0 ){
  49550. rc = saveAllCursors(pBt, 0, 0);
  49551. if( rc==SQLITE_OK ){
  49552. invalidateAllOverflowCache(pBt);
  49553. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  49554. }
  49555. if( rc==SQLITE_OK ){
  49556. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  49557. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  49558. }
  49559. }else{
  49560. rc = SQLITE_DONE;
  49561. }
  49562. }
  49563. sqlite3BtreeLeave(p);
  49564. return rc;
  49565. }
  49566. /*
  49567. ** This routine is called prior to sqlite3PagerCommit when a transaction
  49568. ** is committed for an auto-vacuum database.
  49569. **
  49570. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  49571. ** the database file should be truncated to during the commit process.
  49572. ** i.e. the database has been reorganized so that only the first *pnTrunc
  49573. ** pages are in use.
  49574. */
  49575. static int autoVacuumCommit(BtShared *pBt){
  49576. int rc = SQLITE_OK;
  49577. Pager *pPager = pBt->pPager;
  49578. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  49579. assert( sqlite3_mutex_held(pBt->mutex) );
  49580. invalidateAllOverflowCache(pBt);
  49581. assert(pBt->autoVacuum);
  49582. if( !pBt->incrVacuum ){
  49583. Pgno nFin; /* Number of pages in database after autovacuuming */
  49584. Pgno nFree; /* Number of pages on the freelist initially */
  49585. Pgno iFree; /* The next page to be freed */
  49586. Pgno nOrig; /* Database size before freeing */
  49587. nOrig = btreePagecount(pBt);
  49588. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  49589. /* It is not possible to create a database for which the final page
  49590. ** is either a pointer-map page or the pending-byte page. If one
  49591. ** is encountered, this indicates corruption.
  49592. */
  49593. return SQLITE_CORRUPT_BKPT;
  49594. }
  49595. nFree = get4byte(&pBt->pPage1->aData[36]);
  49596. nFin = finalDbSize(pBt, nOrig, nFree);
  49597. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  49598. if( nFin<nOrig ){
  49599. rc = saveAllCursors(pBt, 0, 0);
  49600. }
  49601. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  49602. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  49603. }
  49604. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  49605. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  49606. put4byte(&pBt->pPage1->aData[32], 0);
  49607. put4byte(&pBt->pPage1->aData[36], 0);
  49608. put4byte(&pBt->pPage1->aData[28], nFin);
  49609. pBt->bDoTruncate = 1;
  49610. pBt->nPage = nFin;
  49611. }
  49612. if( rc!=SQLITE_OK ){
  49613. sqlite3PagerRollback(pPager);
  49614. }
  49615. }
  49616. assert( nRef>=sqlite3PagerRefcount(pPager) );
  49617. return rc;
  49618. }
  49619. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  49620. # define setChildPtrmaps(x) SQLITE_OK
  49621. #endif
  49622. /*
  49623. ** This routine does the first phase of a two-phase commit. This routine
  49624. ** causes a rollback journal to be created (if it does not already exist)
  49625. ** and populated with enough information so that if a power loss occurs
  49626. ** the database can be restored to its original state by playing back
  49627. ** the journal. Then the contents of the journal are flushed out to
  49628. ** the disk. After the journal is safely on oxide, the changes to the
  49629. ** database are written into the database file and flushed to oxide.
  49630. ** At the end of this call, the rollback journal still exists on the
  49631. ** disk and we are still holding all locks, so the transaction has not
  49632. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  49633. ** commit process.
  49634. **
  49635. ** This call is a no-op if no write-transaction is currently active on pBt.
  49636. **
  49637. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  49638. ** the name of a master journal file that should be written into the
  49639. ** individual journal file, or is NULL, indicating no master journal file
  49640. ** (single database transaction).
  49641. **
  49642. ** When this is called, the master journal should already have been
  49643. ** created, populated with this journal pointer and synced to disk.
  49644. **
  49645. ** Once this is routine has returned, the only thing required to commit
  49646. ** the write-transaction for this database file is to delete the journal.
  49647. */
  49648. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  49649. int rc = SQLITE_OK;
  49650. if( p->inTrans==TRANS_WRITE ){
  49651. BtShared *pBt = p->pBt;
  49652. sqlite3BtreeEnter(p);
  49653. #ifndef SQLITE_OMIT_AUTOVACUUM
  49654. if( pBt->autoVacuum ){
  49655. rc = autoVacuumCommit(pBt);
  49656. if( rc!=SQLITE_OK ){
  49657. sqlite3BtreeLeave(p);
  49658. return rc;
  49659. }
  49660. }
  49661. if( pBt->bDoTruncate ){
  49662. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  49663. }
  49664. #endif
  49665. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  49666. sqlite3BtreeLeave(p);
  49667. }
  49668. return rc;
  49669. }
  49670. /*
  49671. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  49672. ** at the conclusion of a transaction.
  49673. */
  49674. static void btreeEndTransaction(Btree *p){
  49675. BtShared *pBt = p->pBt;
  49676. sqlite3 *db = p->db;
  49677. assert( sqlite3BtreeHoldsMutex(p) );
  49678. #ifndef SQLITE_OMIT_AUTOVACUUM
  49679. pBt->bDoTruncate = 0;
  49680. #endif
  49681. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  49682. /* If there are other active statements that belong to this database
  49683. ** handle, downgrade to a read-only transaction. The other statements
  49684. ** may still be reading from the database. */
  49685. downgradeAllSharedCacheTableLocks(p);
  49686. p->inTrans = TRANS_READ;
  49687. }else{
  49688. /* If the handle had any kind of transaction open, decrement the
  49689. ** transaction count of the shared btree. If the transaction count
  49690. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  49691. ** call below will unlock the pager. */
  49692. if( p->inTrans!=TRANS_NONE ){
  49693. clearAllSharedCacheTableLocks(p);
  49694. pBt->nTransaction--;
  49695. if( 0==pBt->nTransaction ){
  49696. pBt->inTransaction = TRANS_NONE;
  49697. }
  49698. }
  49699. /* Set the current transaction state to TRANS_NONE and unlock the
  49700. ** pager if this call closed the only read or write transaction. */
  49701. p->inTrans = TRANS_NONE;
  49702. unlockBtreeIfUnused(pBt);
  49703. }
  49704. btreeIntegrity(p);
  49705. }
  49706. /*
  49707. ** Commit the transaction currently in progress.
  49708. **
  49709. ** This routine implements the second phase of a 2-phase commit. The
  49710. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  49711. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  49712. ** routine did all the work of writing information out to disk and flushing the
  49713. ** contents so that they are written onto the disk platter. All this
  49714. ** routine has to do is delete or truncate or zero the header in the
  49715. ** the rollback journal (which causes the transaction to commit) and
  49716. ** drop locks.
  49717. **
  49718. ** Normally, if an error occurs while the pager layer is attempting to
  49719. ** finalize the underlying journal file, this function returns an error and
  49720. ** the upper layer will attempt a rollback. However, if the second argument
  49721. ** is non-zero then this b-tree transaction is part of a multi-file
  49722. ** transaction. In this case, the transaction has already been committed
  49723. ** (by deleting a master journal file) and the caller will ignore this
  49724. ** functions return code. So, even if an error occurs in the pager layer,
  49725. ** reset the b-tree objects internal state to indicate that the write
  49726. ** transaction has been closed. This is quite safe, as the pager will have
  49727. ** transitioned to the error state.
  49728. **
  49729. ** This will release the write lock on the database file. If there
  49730. ** are no active cursors, it also releases the read lock.
  49731. */
  49732. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  49733. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  49734. sqlite3BtreeEnter(p);
  49735. btreeIntegrity(p);
  49736. /* If the handle has a write-transaction open, commit the shared-btrees
  49737. ** transaction and set the shared state to TRANS_READ.
  49738. */
  49739. if( p->inTrans==TRANS_WRITE ){
  49740. int rc;
  49741. BtShared *pBt = p->pBt;
  49742. assert( pBt->inTransaction==TRANS_WRITE );
  49743. assert( pBt->nTransaction>0 );
  49744. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  49745. if( rc!=SQLITE_OK && bCleanup==0 ){
  49746. sqlite3BtreeLeave(p);
  49747. return rc;
  49748. }
  49749. pBt->inTransaction = TRANS_READ;
  49750. btreeClearHasContent(pBt);
  49751. }
  49752. btreeEndTransaction(p);
  49753. sqlite3BtreeLeave(p);
  49754. return SQLITE_OK;
  49755. }
  49756. /*
  49757. ** Do both phases of a commit.
  49758. */
  49759. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  49760. int rc;
  49761. sqlite3BtreeEnter(p);
  49762. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  49763. if( rc==SQLITE_OK ){
  49764. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  49765. }
  49766. sqlite3BtreeLeave(p);
  49767. return rc;
  49768. }
  49769. /*
  49770. ** This routine sets the state to CURSOR_FAULT and the error
  49771. ** code to errCode for every cursor on BtShared that pBtree
  49772. ** references.
  49773. **
  49774. ** Every cursor is tripped, including cursors that belong
  49775. ** to other database connections that happen to be sharing
  49776. ** the cache with pBtree.
  49777. **
  49778. ** This routine gets called when a rollback occurs.
  49779. ** All cursors using the same cache must be tripped
  49780. ** to prevent them from trying to use the btree after
  49781. ** the rollback. The rollback may have deleted tables
  49782. ** or moved root pages, so it is not sufficient to
  49783. ** save the state of the cursor. The cursor must be
  49784. ** invalidated.
  49785. */
  49786. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  49787. BtCursor *p;
  49788. if( pBtree==0 ) return;
  49789. sqlite3BtreeEnter(pBtree);
  49790. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  49791. int i;
  49792. sqlite3BtreeClearCursor(p);
  49793. p->eState = CURSOR_FAULT;
  49794. p->skipNext = errCode;
  49795. for(i=0; i<=p->iPage; i++){
  49796. releasePage(p->apPage[i]);
  49797. p->apPage[i] = 0;
  49798. }
  49799. }
  49800. sqlite3BtreeLeave(pBtree);
  49801. }
  49802. /*
  49803. ** Rollback the transaction in progress. All cursors will be
  49804. ** invalided by this operation. Any attempt to use a cursor
  49805. ** that was open at the beginning of this operation will result
  49806. ** in an error.
  49807. **
  49808. ** This will release the write lock on the database file. If there
  49809. ** are no active cursors, it also releases the read lock.
  49810. */
  49811. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
  49812. int rc;
  49813. BtShared *pBt = p->pBt;
  49814. MemPage *pPage1;
  49815. sqlite3BtreeEnter(p);
  49816. if( tripCode==SQLITE_OK ){
  49817. rc = tripCode = saveAllCursors(pBt, 0, 0);
  49818. }else{
  49819. rc = SQLITE_OK;
  49820. }
  49821. if( tripCode ){
  49822. sqlite3BtreeTripAllCursors(p, tripCode);
  49823. }
  49824. btreeIntegrity(p);
  49825. if( p->inTrans==TRANS_WRITE ){
  49826. int rc2;
  49827. assert( TRANS_WRITE==pBt->inTransaction );
  49828. rc2 = sqlite3PagerRollback(pBt->pPager);
  49829. if( rc2!=SQLITE_OK ){
  49830. rc = rc2;
  49831. }
  49832. /* The rollback may have destroyed the pPage1->aData value. So
  49833. ** call btreeGetPage() on page 1 again to make
  49834. ** sure pPage1->aData is set correctly. */
  49835. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  49836. int nPage = get4byte(28+(u8*)pPage1->aData);
  49837. testcase( nPage==0 );
  49838. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  49839. testcase( pBt->nPage!=nPage );
  49840. pBt->nPage = nPage;
  49841. releasePage(pPage1);
  49842. }
  49843. assert( countValidCursors(pBt, 1)==0 );
  49844. pBt->inTransaction = TRANS_READ;
  49845. btreeClearHasContent(pBt);
  49846. }
  49847. btreeEndTransaction(p);
  49848. sqlite3BtreeLeave(p);
  49849. return rc;
  49850. }
  49851. /*
  49852. ** Start a statement subtransaction. The subtransaction can can be rolled
  49853. ** back independently of the main transaction. You must start a transaction
  49854. ** before starting a subtransaction. The subtransaction is ended automatically
  49855. ** if the main transaction commits or rolls back.
  49856. **
  49857. ** Statement subtransactions are used around individual SQL statements
  49858. ** that are contained within a BEGIN...COMMIT block. If a constraint
  49859. ** error occurs within the statement, the effect of that one statement
  49860. ** can be rolled back without having to rollback the entire transaction.
  49861. **
  49862. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  49863. ** value passed as the second parameter is the total number of savepoints,
  49864. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  49865. ** are no active savepoints and no other statement-transactions open,
  49866. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  49867. ** using the sqlite3BtreeSavepoint() function.
  49868. */
  49869. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  49870. int rc;
  49871. BtShared *pBt = p->pBt;
  49872. sqlite3BtreeEnter(p);
  49873. assert( p->inTrans==TRANS_WRITE );
  49874. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  49875. assert( iStatement>0 );
  49876. assert( iStatement>p->db->nSavepoint );
  49877. assert( pBt->inTransaction==TRANS_WRITE );
  49878. /* At the pager level, a statement transaction is a savepoint with
  49879. ** an index greater than all savepoints created explicitly using
  49880. ** SQL statements. It is illegal to open, release or rollback any
  49881. ** such savepoints while the statement transaction savepoint is active.
  49882. */
  49883. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  49884. sqlite3BtreeLeave(p);
  49885. return rc;
  49886. }
  49887. /*
  49888. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  49889. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  49890. ** savepoint identified by parameter iSavepoint, depending on the value
  49891. ** of op.
  49892. **
  49893. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  49894. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  49895. ** contents of the entire transaction are rolled back. This is different
  49896. ** from a normal transaction rollback, as no locks are released and the
  49897. ** transaction remains open.
  49898. */
  49899. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  49900. int rc = SQLITE_OK;
  49901. if( p && p->inTrans==TRANS_WRITE ){
  49902. BtShared *pBt = p->pBt;
  49903. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  49904. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  49905. sqlite3BtreeEnter(p);
  49906. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  49907. if( rc==SQLITE_OK ){
  49908. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  49909. pBt->nPage = 0;
  49910. }
  49911. rc = newDatabase(pBt);
  49912. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  49913. /* The database size was written into the offset 28 of the header
  49914. ** when the transaction started, so we know that the value at offset
  49915. ** 28 is nonzero. */
  49916. assert( pBt->nPage>0 );
  49917. }
  49918. sqlite3BtreeLeave(p);
  49919. }
  49920. return rc;
  49921. }
  49922. /*
  49923. ** Create a new cursor for the BTree whose root is on the page
  49924. ** iTable. If a read-only cursor is requested, it is assumed that
  49925. ** the caller already has at least a read-only transaction open
  49926. ** on the database already. If a write-cursor is requested, then
  49927. ** the caller is assumed to have an open write transaction.
  49928. **
  49929. ** If wrFlag==0, then the cursor can only be used for reading.
  49930. ** If wrFlag==1, then the cursor can be used for reading or for
  49931. ** writing if other conditions for writing are also met. These
  49932. ** are the conditions that must be met in order for writing to
  49933. ** be allowed:
  49934. **
  49935. ** 1: The cursor must have been opened with wrFlag==1
  49936. **
  49937. ** 2: Other database connections that share the same pager cache
  49938. ** but which are not in the READ_UNCOMMITTED state may not have
  49939. ** cursors open with wrFlag==0 on the same table. Otherwise
  49940. ** the changes made by this write cursor would be visible to
  49941. ** the read cursors in the other database connection.
  49942. **
  49943. ** 3: The database must be writable (not on read-only media)
  49944. **
  49945. ** 4: There must be an active transaction.
  49946. **
  49947. ** No checking is done to make sure that page iTable really is the
  49948. ** root page of a b-tree. If it is not, then the cursor acquired
  49949. ** will not work correctly.
  49950. **
  49951. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  49952. ** on pCur to initialize the memory space prior to invoking this routine.
  49953. */
  49954. static int btreeCursor(
  49955. Btree *p, /* The btree */
  49956. int iTable, /* Root page of table to open */
  49957. int wrFlag, /* 1 to write. 0 read-only */
  49958. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  49959. BtCursor *pCur /* Space for new cursor */
  49960. ){
  49961. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  49962. assert( sqlite3BtreeHoldsMutex(p) );
  49963. assert( wrFlag==0 || wrFlag==1 );
  49964. /* The following assert statements verify that if this is a sharable
  49965. ** b-tree database, the connection is holding the required table locks,
  49966. ** and that no other connection has any open cursor that conflicts with
  49967. ** this lock. */
  49968. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  49969. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  49970. /* Assert that the caller has opened the required transaction. */
  49971. assert( p->inTrans>TRANS_NONE );
  49972. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  49973. assert( pBt->pPage1 && pBt->pPage1->aData );
  49974. if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
  49975. return SQLITE_READONLY;
  49976. }
  49977. if( iTable==1 && btreePagecount(pBt)==0 ){
  49978. assert( wrFlag==0 );
  49979. iTable = 0;
  49980. }
  49981. /* Now that no other errors can occur, finish filling in the BtCursor
  49982. ** variables and link the cursor into the BtShared list. */
  49983. pCur->pgnoRoot = (Pgno)iTable;
  49984. pCur->iPage = -1;
  49985. pCur->pKeyInfo = pKeyInfo;
  49986. pCur->pBtree = p;
  49987. pCur->pBt = pBt;
  49988. pCur->wrFlag = (u8)wrFlag;
  49989. pCur->pNext = pBt->pCursor;
  49990. if( pCur->pNext ){
  49991. pCur->pNext->pPrev = pCur;
  49992. }
  49993. pBt->pCursor = pCur;
  49994. pCur->eState = CURSOR_INVALID;
  49995. pCur->cachedRowid = 0;
  49996. return SQLITE_OK;
  49997. }
  49998. SQLITE_PRIVATE int sqlite3BtreeCursor(
  49999. Btree *p, /* The btree */
  50000. int iTable, /* Root page of table to open */
  50001. int wrFlag, /* 1 to write. 0 read-only */
  50002. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  50003. BtCursor *pCur /* Write new cursor here */
  50004. ){
  50005. int rc;
  50006. sqlite3BtreeEnter(p);
  50007. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  50008. sqlite3BtreeLeave(p);
  50009. return rc;
  50010. }
  50011. /*
  50012. ** Return the size of a BtCursor object in bytes.
  50013. **
  50014. ** This interfaces is needed so that users of cursors can preallocate
  50015. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  50016. ** to users so they cannot do the sizeof() themselves - they must call
  50017. ** this routine.
  50018. */
  50019. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  50020. return ROUND8(sizeof(BtCursor));
  50021. }
  50022. /*
  50023. ** Initialize memory that will be converted into a BtCursor object.
  50024. **
  50025. ** The simple approach here would be to memset() the entire object
  50026. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  50027. ** do not need to be zeroed and they are large, so we can save a lot
  50028. ** of run-time by skipping the initialization of those elements.
  50029. */
  50030. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  50031. memset(p, 0, offsetof(BtCursor, iPage));
  50032. }
  50033. /*
  50034. ** Set the cached rowid value of every cursor in the same database file
  50035. ** as pCur and having the same root page number as pCur. The value is
  50036. ** set to iRowid.
  50037. **
  50038. ** Only positive rowid values are considered valid for this cache.
  50039. ** The cache is initialized to zero, indicating an invalid cache.
  50040. ** A btree will work fine with zero or negative rowids. We just cannot
  50041. ** cache zero or negative rowids, which means tables that use zero or
  50042. ** negative rowids might run a little slower. But in practice, zero
  50043. ** or negative rowids are very uncommon so this should not be a problem.
  50044. */
  50045. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
  50046. BtCursor *p;
  50047. for(p=pCur->pBt->pCursor; p; p=p->pNext){
  50048. if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
  50049. }
  50050. assert( pCur->cachedRowid==iRowid );
  50051. }
  50052. /*
  50053. ** Return the cached rowid for the given cursor. A negative or zero
  50054. ** return value indicates that the rowid cache is invalid and should be
  50055. ** ignored. If the rowid cache has never before been set, then a
  50056. ** zero is returned.
  50057. */
  50058. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
  50059. return pCur->cachedRowid;
  50060. }
  50061. /*
  50062. ** Close a cursor. The read lock on the database file is released
  50063. ** when the last cursor is closed.
  50064. */
  50065. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  50066. Btree *pBtree = pCur->pBtree;
  50067. if( pBtree ){
  50068. int i;
  50069. BtShared *pBt = pCur->pBt;
  50070. sqlite3BtreeEnter(pBtree);
  50071. sqlite3BtreeClearCursor(pCur);
  50072. if( pCur->pPrev ){
  50073. pCur->pPrev->pNext = pCur->pNext;
  50074. }else{
  50075. pBt->pCursor = pCur->pNext;
  50076. }
  50077. if( pCur->pNext ){
  50078. pCur->pNext->pPrev = pCur->pPrev;
  50079. }
  50080. for(i=0; i<=pCur->iPage; i++){
  50081. releasePage(pCur->apPage[i]);
  50082. }
  50083. unlockBtreeIfUnused(pBt);
  50084. invalidateOverflowCache(pCur);
  50085. /* sqlite3_free(pCur); */
  50086. sqlite3BtreeLeave(pBtree);
  50087. }
  50088. return SQLITE_OK;
  50089. }
  50090. /*
  50091. ** Make sure the BtCursor* given in the argument has a valid
  50092. ** BtCursor.info structure. If it is not already valid, call
  50093. ** btreeParseCell() to fill it in.
  50094. **
  50095. ** BtCursor.info is a cache of the information in the current cell.
  50096. ** Using this cache reduces the number of calls to btreeParseCell().
  50097. **
  50098. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  50099. ** compiler to crash when getCellInfo() is implemented as a macro.
  50100. ** But there is a measureable speed advantage to using the macro on gcc
  50101. ** (when less compiler optimizations like -Os or -O0 are used and the
  50102. ** compiler is not doing agressive inlining.) So we use a real function
  50103. ** for MSVC and a macro for everything else. Ticket #2457.
  50104. */
  50105. #ifndef NDEBUG
  50106. static void assertCellInfo(BtCursor *pCur){
  50107. CellInfo info;
  50108. int iPage = pCur->iPage;
  50109. memset(&info, 0, sizeof(info));
  50110. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  50111. assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  50112. }
  50113. #else
  50114. #define assertCellInfo(x)
  50115. #endif
  50116. #ifdef _MSC_VER
  50117. /* Use a real function in MSVC to work around bugs in that compiler. */
  50118. static void getCellInfo(BtCursor *pCur){
  50119. if( pCur->info.nSize==0 ){
  50120. int iPage = pCur->iPage;
  50121. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  50122. pCur->validNKey = 1;
  50123. }else{
  50124. assertCellInfo(pCur);
  50125. }
  50126. }
  50127. #else /* if not _MSC_VER */
  50128. /* Use a macro in all other compilers so that the function is inlined */
  50129. #define getCellInfo(pCur) \
  50130. if( pCur->info.nSize==0 ){ \
  50131. int iPage = pCur->iPage; \
  50132. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  50133. pCur->validNKey = 1; \
  50134. }else{ \
  50135. assertCellInfo(pCur); \
  50136. }
  50137. #endif /* _MSC_VER */
  50138. #ifndef NDEBUG /* The next routine used only within assert() statements */
  50139. /*
  50140. ** Return true if the given BtCursor is valid. A valid cursor is one
  50141. ** that is currently pointing to a row in a (non-empty) table.
  50142. ** This is a verification routine is used only within assert() statements.
  50143. */
  50144. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  50145. return pCur && pCur->eState==CURSOR_VALID;
  50146. }
  50147. #endif /* NDEBUG */
  50148. /*
  50149. ** Set *pSize to the size of the buffer needed to hold the value of
  50150. ** the key for the current entry. If the cursor is not pointing
  50151. ** to a valid entry, *pSize is set to 0.
  50152. **
  50153. ** For a table with the INTKEY flag set, this routine returns the key
  50154. ** itself, not the number of bytes in the key.
  50155. **
  50156. ** The caller must position the cursor prior to invoking this routine.
  50157. **
  50158. ** This routine cannot fail. It always returns SQLITE_OK.
  50159. */
  50160. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  50161. assert( cursorHoldsMutex(pCur) );
  50162. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  50163. if( pCur->eState!=CURSOR_VALID ){
  50164. *pSize = 0;
  50165. }else{
  50166. getCellInfo(pCur);
  50167. *pSize = pCur->info.nKey;
  50168. }
  50169. return SQLITE_OK;
  50170. }
  50171. /*
  50172. ** Set *pSize to the number of bytes of data in the entry the
  50173. ** cursor currently points to.
  50174. **
  50175. ** The caller must guarantee that the cursor is pointing to a non-NULL
  50176. ** valid entry. In other words, the calling procedure must guarantee
  50177. ** that the cursor has Cursor.eState==CURSOR_VALID.
  50178. **
  50179. ** Failure is not possible. This function always returns SQLITE_OK.
  50180. ** It might just as well be a procedure (returning void) but we continue
  50181. ** to return an integer result code for historical reasons.
  50182. */
  50183. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  50184. assert( cursorHoldsMutex(pCur) );
  50185. assert( pCur->eState==CURSOR_VALID );
  50186. getCellInfo(pCur);
  50187. *pSize = pCur->info.nData;
  50188. return SQLITE_OK;
  50189. }
  50190. /*
  50191. ** Given the page number of an overflow page in the database (parameter
  50192. ** ovfl), this function finds the page number of the next page in the
  50193. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  50194. ** pointer-map data instead of reading the content of page ovfl to do so.
  50195. **
  50196. ** If an error occurs an SQLite error code is returned. Otherwise:
  50197. **
  50198. ** The page number of the next overflow page in the linked list is
  50199. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  50200. ** list, *pPgnoNext is set to zero.
  50201. **
  50202. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  50203. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  50204. ** reference. It is the responsibility of the caller to call releasePage()
  50205. ** on *ppPage to free the reference. In no reference was obtained (because
  50206. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  50207. ** *ppPage is set to zero.
  50208. */
  50209. static int getOverflowPage(
  50210. BtShared *pBt, /* The database file */
  50211. Pgno ovfl, /* Current overflow page number */
  50212. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  50213. Pgno *pPgnoNext /* OUT: Next overflow page number */
  50214. ){
  50215. Pgno next = 0;
  50216. MemPage *pPage = 0;
  50217. int rc = SQLITE_OK;
  50218. assert( sqlite3_mutex_held(pBt->mutex) );
  50219. assert(pPgnoNext);
  50220. #ifndef SQLITE_OMIT_AUTOVACUUM
  50221. /* Try to find the next page in the overflow list using the
  50222. ** autovacuum pointer-map pages. Guess that the next page in
  50223. ** the overflow list is page number (ovfl+1). If that guess turns
  50224. ** out to be wrong, fall back to loading the data of page
  50225. ** number ovfl to determine the next page number.
  50226. */
  50227. if( pBt->autoVacuum ){
  50228. Pgno pgno;
  50229. Pgno iGuess = ovfl+1;
  50230. u8 eType;
  50231. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  50232. iGuess++;
  50233. }
  50234. if( iGuess<=btreePagecount(pBt) ){
  50235. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  50236. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  50237. next = iGuess;
  50238. rc = SQLITE_DONE;
  50239. }
  50240. }
  50241. }
  50242. #endif
  50243. assert( next==0 || rc==SQLITE_DONE );
  50244. if( rc==SQLITE_OK ){
  50245. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  50246. assert( rc==SQLITE_OK || pPage==0 );
  50247. if( rc==SQLITE_OK ){
  50248. next = get4byte(pPage->aData);
  50249. }
  50250. }
  50251. *pPgnoNext = next;
  50252. if( ppPage ){
  50253. *ppPage = pPage;
  50254. }else{
  50255. releasePage(pPage);
  50256. }
  50257. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  50258. }
  50259. /*
  50260. ** Copy data from a buffer to a page, or from a page to a buffer.
  50261. **
  50262. ** pPayload is a pointer to data stored on database page pDbPage.
  50263. ** If argument eOp is false, then nByte bytes of data are copied
  50264. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  50265. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  50266. ** of data are copied from the buffer pBuf to pPayload.
  50267. **
  50268. ** SQLITE_OK is returned on success, otherwise an error code.
  50269. */
  50270. static int copyPayload(
  50271. void *pPayload, /* Pointer to page data */
  50272. void *pBuf, /* Pointer to buffer */
  50273. int nByte, /* Number of bytes to copy */
  50274. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  50275. DbPage *pDbPage /* Page containing pPayload */
  50276. ){
  50277. if( eOp ){
  50278. /* Copy data from buffer to page (a write operation) */
  50279. int rc = sqlite3PagerWrite(pDbPage);
  50280. if( rc!=SQLITE_OK ){
  50281. return rc;
  50282. }
  50283. memcpy(pPayload, pBuf, nByte);
  50284. }else{
  50285. /* Copy data from page to buffer (a read operation) */
  50286. memcpy(pBuf, pPayload, nByte);
  50287. }
  50288. return SQLITE_OK;
  50289. }
  50290. /*
  50291. ** This function is used to read or overwrite payload information
  50292. ** for the entry that the pCur cursor is pointing to. If the eOp
  50293. ** parameter is 0, this is a read operation (data copied into
  50294. ** buffer pBuf). If it is non-zero, a write (data copied from
  50295. ** buffer pBuf).
  50296. **
  50297. ** A total of "amt" bytes are read or written beginning at "offset".
  50298. ** Data is read to or from the buffer pBuf.
  50299. **
  50300. ** The content being read or written might appear on the main page
  50301. ** or be scattered out on multiple overflow pages.
  50302. **
  50303. ** If the BtCursor.isIncrblobHandle flag is set, and the current
  50304. ** cursor entry uses one or more overflow pages, this function
  50305. ** allocates space for and lazily popluates the overflow page-list
  50306. ** cache array (BtCursor.aOverflow). Subsequent calls use this
  50307. ** cache to make seeking to the supplied offset more efficient.
  50308. **
  50309. ** Once an overflow page-list cache has been allocated, it may be
  50310. ** invalidated if some other cursor writes to the same table, or if
  50311. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  50312. ** mode, the following events may invalidate an overflow page-list cache.
  50313. **
  50314. ** * An incremental vacuum,
  50315. ** * A commit in auto_vacuum="full" mode,
  50316. ** * Creating a table (may require moving an overflow page).
  50317. */
  50318. static int accessPayload(
  50319. BtCursor *pCur, /* Cursor pointing to entry to read from */
  50320. u32 offset, /* Begin reading this far into payload */
  50321. u32 amt, /* Read this many bytes */
  50322. unsigned char *pBuf, /* Write the bytes into this buffer */
  50323. int eOp /* zero to read. non-zero to write. */
  50324. ){
  50325. unsigned char *aPayload;
  50326. int rc = SQLITE_OK;
  50327. u32 nKey;
  50328. int iIdx = 0;
  50329. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  50330. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  50331. assert( pPage );
  50332. assert( pCur->eState==CURSOR_VALID );
  50333. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  50334. assert( cursorHoldsMutex(pCur) );
  50335. getCellInfo(pCur);
  50336. aPayload = pCur->info.pCell + pCur->info.nHeader;
  50337. nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
  50338. if( NEVER(offset+amt > nKey+pCur->info.nData)
  50339. || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  50340. ){
  50341. /* Trying to read or write past the end of the data is an error */
  50342. return SQLITE_CORRUPT_BKPT;
  50343. }
  50344. /* Check if data must be read/written to/from the btree page itself. */
  50345. if( offset<pCur->info.nLocal ){
  50346. int a = amt;
  50347. if( a+offset>pCur->info.nLocal ){
  50348. a = pCur->info.nLocal - offset;
  50349. }
  50350. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  50351. offset = 0;
  50352. pBuf += a;
  50353. amt -= a;
  50354. }else{
  50355. offset -= pCur->info.nLocal;
  50356. }
  50357. if( rc==SQLITE_OK && amt>0 ){
  50358. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  50359. Pgno nextPage;
  50360. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  50361. #ifndef SQLITE_OMIT_INCRBLOB
  50362. /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
  50363. ** has not been allocated, allocate it now. The array is sized at
  50364. ** one entry for each overflow page in the overflow chain. The
  50365. ** page number of the first overflow page is stored in aOverflow[0],
  50366. ** etc. A value of 0 in the aOverflow[] array means "not yet known"
  50367. ** (the cache is lazily populated).
  50368. */
  50369. if( pCur->isIncrblobHandle && !pCur->aOverflow ){
  50370. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  50371. pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
  50372. /* nOvfl is always positive. If it were zero, fetchPayload would have
  50373. ** been used instead of this routine. */
  50374. if( ALWAYS(nOvfl) && !pCur->aOverflow ){
  50375. rc = SQLITE_NOMEM;
  50376. }
  50377. }
  50378. /* If the overflow page-list cache has been allocated and the
  50379. ** entry for the first required overflow page is valid, skip
  50380. ** directly to it.
  50381. */
  50382. if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
  50383. iIdx = (offset/ovflSize);
  50384. nextPage = pCur->aOverflow[iIdx];
  50385. offset = (offset%ovflSize);
  50386. }
  50387. #endif
  50388. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  50389. #ifndef SQLITE_OMIT_INCRBLOB
  50390. /* If required, populate the overflow page-list cache. */
  50391. if( pCur->aOverflow ){
  50392. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  50393. pCur->aOverflow[iIdx] = nextPage;
  50394. }
  50395. #endif
  50396. if( offset>=ovflSize ){
  50397. /* The only reason to read this page is to obtain the page
  50398. ** number for the next page in the overflow chain. The page
  50399. ** data is not required. So first try to lookup the overflow
  50400. ** page-list cache, if any, then fall back to the getOverflowPage()
  50401. ** function.
  50402. */
  50403. #ifndef SQLITE_OMIT_INCRBLOB
  50404. if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
  50405. nextPage = pCur->aOverflow[iIdx+1];
  50406. } else
  50407. #endif
  50408. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  50409. offset -= ovflSize;
  50410. }else{
  50411. /* Need to read this page properly. It contains some of the
  50412. ** range of data that is being read (eOp==0) or written (eOp!=0).
  50413. */
  50414. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  50415. sqlite3_file *fd;
  50416. #endif
  50417. int a = amt;
  50418. if( a + offset > ovflSize ){
  50419. a = ovflSize - offset;
  50420. }
  50421. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  50422. /* If all the following are true:
  50423. **
  50424. ** 1) this is a read operation, and
  50425. ** 2) data is required from the start of this overflow page, and
  50426. ** 3) the database is file-backed, and
  50427. ** 4) there is no open write-transaction, and
  50428. ** 5) the database is not a WAL database,
  50429. **
  50430. ** then data can be read directly from the database file into the
  50431. ** output buffer, bypassing the page-cache altogether. This speeds
  50432. ** up loading large records that span many overflow pages.
  50433. */
  50434. if( eOp==0 /* (1) */
  50435. && offset==0 /* (2) */
  50436. && pBt->inTransaction==TRANS_READ /* (4) */
  50437. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  50438. && pBt->pPage1->aData[19]==0x01 /* (5) */
  50439. ){
  50440. u8 aSave[4];
  50441. u8 *aWrite = &pBuf[-4];
  50442. memcpy(aSave, aWrite, 4);
  50443. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  50444. nextPage = get4byte(aWrite);
  50445. memcpy(aWrite, aSave, 4);
  50446. }else
  50447. #endif
  50448. {
  50449. DbPage *pDbPage;
  50450. rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
  50451. (eOp==0 ? PAGER_GET_READONLY : 0)
  50452. );
  50453. if( rc==SQLITE_OK ){
  50454. aPayload = sqlite3PagerGetData(pDbPage);
  50455. nextPage = get4byte(aPayload);
  50456. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  50457. sqlite3PagerUnref(pDbPage);
  50458. offset = 0;
  50459. }
  50460. }
  50461. amt -= a;
  50462. pBuf += a;
  50463. }
  50464. }
  50465. }
  50466. if( rc==SQLITE_OK && amt>0 ){
  50467. return SQLITE_CORRUPT_BKPT;
  50468. }
  50469. return rc;
  50470. }
  50471. /*
  50472. ** Read part of the key associated with cursor pCur. Exactly
  50473. ** "amt" bytes will be transfered into pBuf[]. The transfer
  50474. ** begins at "offset".
  50475. **
  50476. ** The caller must ensure that pCur is pointing to a valid row
  50477. ** in the table.
  50478. **
  50479. ** Return SQLITE_OK on success or an error code if anything goes
  50480. ** wrong. An error is returned if "offset+amt" is larger than
  50481. ** the available payload.
  50482. */
  50483. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  50484. assert( cursorHoldsMutex(pCur) );
  50485. assert( pCur->eState==CURSOR_VALID );
  50486. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  50487. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  50488. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  50489. }
  50490. /*
  50491. ** Read part of the data associated with cursor pCur. Exactly
  50492. ** "amt" bytes will be transfered into pBuf[]. The transfer
  50493. ** begins at "offset".
  50494. **
  50495. ** Return SQLITE_OK on success or an error code if anything goes
  50496. ** wrong. An error is returned if "offset+amt" is larger than
  50497. ** the available payload.
  50498. */
  50499. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  50500. int rc;
  50501. #ifndef SQLITE_OMIT_INCRBLOB
  50502. if ( pCur->eState==CURSOR_INVALID ){
  50503. return SQLITE_ABORT;
  50504. }
  50505. #endif
  50506. assert( cursorHoldsMutex(pCur) );
  50507. rc = restoreCursorPosition(pCur);
  50508. if( rc==SQLITE_OK ){
  50509. assert( pCur->eState==CURSOR_VALID );
  50510. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  50511. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  50512. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  50513. }
  50514. return rc;
  50515. }
  50516. /*
  50517. ** Return a pointer to payload information from the entry that the
  50518. ** pCur cursor is pointing to. The pointer is to the beginning of
  50519. ** the key if skipKey==0 and it points to the beginning of data if
  50520. ** skipKey==1. The number of bytes of available key/data is written
  50521. ** into *pAmt. If *pAmt==0, then the value returned will not be
  50522. ** a valid pointer.
  50523. **
  50524. ** This routine is an optimization. It is common for the entire key
  50525. ** and data to fit on the local page and for there to be no overflow
  50526. ** pages. When that is so, this routine can be used to access the
  50527. ** key and data without making a copy. If the key and/or data spills
  50528. ** onto overflow pages, then accessPayload() must be used to reassemble
  50529. ** the key/data and copy it into a preallocated buffer.
  50530. **
  50531. ** The pointer returned by this routine looks directly into the cached
  50532. ** page of the database. The data might change or move the next time
  50533. ** any btree routine is called.
  50534. */
  50535. static const unsigned char *fetchPayload(
  50536. BtCursor *pCur, /* Cursor pointing to entry to read from */
  50537. int *pAmt, /* Write the number of available bytes here */
  50538. int skipKey /* read beginning at data if this is true */
  50539. ){
  50540. unsigned char *aPayload;
  50541. MemPage *pPage;
  50542. u32 nKey;
  50543. u32 nLocal;
  50544. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  50545. assert( pCur->eState==CURSOR_VALID );
  50546. assert( cursorHoldsMutex(pCur) );
  50547. pPage = pCur->apPage[pCur->iPage];
  50548. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  50549. if( NEVER(pCur->info.nSize==0) ){
  50550. btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
  50551. &pCur->info);
  50552. }
  50553. aPayload = pCur->info.pCell;
  50554. aPayload += pCur->info.nHeader;
  50555. if( pPage->intKey ){
  50556. nKey = 0;
  50557. }else{
  50558. nKey = (int)pCur->info.nKey;
  50559. }
  50560. if( skipKey ){
  50561. aPayload += nKey;
  50562. nLocal = pCur->info.nLocal - nKey;
  50563. }else{
  50564. nLocal = pCur->info.nLocal;
  50565. assert( nLocal<=nKey );
  50566. }
  50567. *pAmt = nLocal;
  50568. return aPayload;
  50569. }
  50570. /*
  50571. ** For the entry that cursor pCur is point to, return as
  50572. ** many bytes of the key or data as are available on the local
  50573. ** b-tree page. Write the number of available bytes into *pAmt.
  50574. **
  50575. ** The pointer returned is ephemeral. The key/data may move
  50576. ** or be destroyed on the next call to any Btree routine,
  50577. ** including calls from other threads against the same cache.
  50578. ** Hence, a mutex on the BtShared should be held prior to calling
  50579. ** this routine.
  50580. **
  50581. ** These routines is used to get quick access to key and data
  50582. ** in the common case where no overflow pages are used.
  50583. */
  50584. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  50585. const void *p = 0;
  50586. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  50587. assert( cursorHoldsMutex(pCur) );
  50588. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  50589. p = (const void*)fetchPayload(pCur, pAmt, 0);
  50590. }
  50591. return p;
  50592. }
  50593. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  50594. const void *p = 0;
  50595. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  50596. assert( cursorHoldsMutex(pCur) );
  50597. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  50598. p = (const void*)fetchPayload(pCur, pAmt, 1);
  50599. }
  50600. return p;
  50601. }
  50602. /*
  50603. ** Move the cursor down to a new child page. The newPgno argument is the
  50604. ** page number of the child page to move to.
  50605. **
  50606. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  50607. ** the new child page does not match the flags field of the parent (i.e.
  50608. ** if an intkey page appears to be the parent of a non-intkey page, or
  50609. ** vice-versa).
  50610. */
  50611. static int moveToChild(BtCursor *pCur, u32 newPgno){
  50612. int rc;
  50613. int i = pCur->iPage;
  50614. MemPage *pNewPage;
  50615. BtShared *pBt = pCur->pBt;
  50616. assert( cursorHoldsMutex(pCur) );
  50617. assert( pCur->eState==CURSOR_VALID );
  50618. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  50619. assert( pCur->iPage>=0 );
  50620. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  50621. return SQLITE_CORRUPT_BKPT;
  50622. }
  50623. rc = getAndInitPage(pBt, newPgno, &pNewPage,
  50624. pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
  50625. if( rc ) return rc;
  50626. pCur->apPage[i+1] = pNewPage;
  50627. pCur->aiIdx[i+1] = 0;
  50628. pCur->iPage++;
  50629. pCur->info.nSize = 0;
  50630. pCur->validNKey = 0;
  50631. if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
  50632. return SQLITE_CORRUPT_BKPT;
  50633. }
  50634. return SQLITE_OK;
  50635. }
  50636. #if 0
  50637. /*
  50638. ** Page pParent is an internal (non-leaf) tree page. This function
  50639. ** asserts that page number iChild is the left-child if the iIdx'th
  50640. ** cell in page pParent. Or, if iIdx is equal to the total number of
  50641. ** cells in pParent, that page number iChild is the right-child of
  50642. ** the page.
  50643. */
  50644. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  50645. assert( iIdx<=pParent->nCell );
  50646. if( iIdx==pParent->nCell ){
  50647. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  50648. }else{
  50649. assert( get4byte(findCell(pParent, iIdx))==iChild );
  50650. }
  50651. }
  50652. #else
  50653. # define assertParentIndex(x,y,z)
  50654. #endif
  50655. /*
  50656. ** Move the cursor up to the parent page.
  50657. **
  50658. ** pCur->idx is set to the cell index that contains the pointer
  50659. ** to the page we are coming from. If we are coming from the
  50660. ** right-most child page then pCur->idx is set to one more than
  50661. ** the largest cell index.
  50662. */
  50663. static void moveToParent(BtCursor *pCur){
  50664. assert( cursorHoldsMutex(pCur) );
  50665. assert( pCur->eState==CURSOR_VALID );
  50666. assert( pCur->iPage>0 );
  50667. assert( pCur->apPage[pCur->iPage] );
  50668. /* UPDATE: It is actually possible for the condition tested by the assert
  50669. ** below to be untrue if the database file is corrupt. This can occur if
  50670. ** one cursor has modified page pParent while a reference to it is held
  50671. ** by a second cursor. Which can only happen if a single page is linked
  50672. ** into more than one b-tree structure in a corrupt database. */
  50673. #if 0
  50674. assertParentIndex(
  50675. pCur->apPage[pCur->iPage-1],
  50676. pCur->aiIdx[pCur->iPage-1],
  50677. pCur->apPage[pCur->iPage]->pgno
  50678. );
  50679. #endif
  50680. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  50681. releasePage(pCur->apPage[pCur->iPage]);
  50682. pCur->iPage--;
  50683. pCur->info.nSize = 0;
  50684. pCur->validNKey = 0;
  50685. }
  50686. /*
  50687. ** Move the cursor to point to the root page of its b-tree structure.
  50688. **
  50689. ** If the table has a virtual root page, then the cursor is moved to point
  50690. ** to the virtual root page instead of the actual root page. A table has a
  50691. ** virtual root page when the actual root page contains no cells and a
  50692. ** single child page. This can only happen with the table rooted at page 1.
  50693. **
  50694. ** If the b-tree structure is empty, the cursor state is set to
  50695. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  50696. ** cell located on the root (or virtual root) page and the cursor state
  50697. ** is set to CURSOR_VALID.
  50698. **
  50699. ** If this function returns successfully, it may be assumed that the
  50700. ** page-header flags indicate that the [virtual] root-page is the expected
  50701. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  50702. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  50703. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  50704. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  50705. ** b-tree).
  50706. */
  50707. static int moveToRoot(BtCursor *pCur){
  50708. MemPage *pRoot;
  50709. int rc = SQLITE_OK;
  50710. Btree *p = pCur->pBtree;
  50711. BtShared *pBt = p->pBt;
  50712. assert( cursorHoldsMutex(pCur) );
  50713. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  50714. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  50715. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  50716. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  50717. if( pCur->eState==CURSOR_FAULT ){
  50718. assert( pCur->skipNext!=SQLITE_OK );
  50719. return pCur->skipNext;
  50720. }
  50721. sqlite3BtreeClearCursor(pCur);
  50722. }
  50723. if( pCur->iPage>=0 ){
  50724. int i;
  50725. for(i=1; i<=pCur->iPage; i++){
  50726. releasePage(pCur->apPage[i]);
  50727. }
  50728. pCur->iPage = 0;
  50729. }else if( pCur->pgnoRoot==0 ){
  50730. pCur->eState = CURSOR_INVALID;
  50731. return SQLITE_OK;
  50732. }else{
  50733. rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0],
  50734. pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
  50735. if( rc!=SQLITE_OK ){
  50736. pCur->eState = CURSOR_INVALID;
  50737. return rc;
  50738. }
  50739. pCur->iPage = 0;
  50740. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  50741. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  50742. ** NULL, the caller expects a table b-tree. If this is not the case,
  50743. ** return an SQLITE_CORRUPT error. */
  50744. assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
  50745. if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
  50746. return SQLITE_CORRUPT_BKPT;
  50747. }
  50748. }
  50749. /* Assert that the root page is of the correct type. This must be the
  50750. ** case as the call to this function that loaded the root-page (either
  50751. ** this call or a previous invocation) would have detected corruption
  50752. ** if the assumption were not true, and it is not possible for the flags
  50753. ** byte to have been modified while this cursor is holding a reference
  50754. ** to the page. */
  50755. pRoot = pCur->apPage[0];
  50756. assert( pRoot->pgno==pCur->pgnoRoot );
  50757. assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
  50758. pCur->aiIdx[0] = 0;
  50759. pCur->info.nSize = 0;
  50760. pCur->atLast = 0;
  50761. pCur->validNKey = 0;
  50762. if( pRoot->nCell==0 && !pRoot->leaf ){
  50763. Pgno subpage;
  50764. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  50765. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  50766. pCur->eState = CURSOR_VALID;
  50767. rc = moveToChild(pCur, subpage);
  50768. }else{
  50769. pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  50770. }
  50771. return rc;
  50772. }
  50773. /*
  50774. ** Move the cursor down to the left-most leaf entry beneath the
  50775. ** entry to which it is currently pointing.
  50776. **
  50777. ** The left-most leaf is the one with the smallest key - the first
  50778. ** in ascending order.
  50779. */
  50780. static int moveToLeftmost(BtCursor *pCur){
  50781. Pgno pgno;
  50782. int rc = SQLITE_OK;
  50783. MemPage *pPage;
  50784. assert( cursorHoldsMutex(pCur) );
  50785. assert( pCur->eState==CURSOR_VALID );
  50786. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  50787. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  50788. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  50789. rc = moveToChild(pCur, pgno);
  50790. }
  50791. return rc;
  50792. }
  50793. /*
  50794. ** Move the cursor down to the right-most leaf entry beneath the
  50795. ** page to which it is currently pointing. Notice the difference
  50796. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  50797. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  50798. ** finds the right-most entry beneath the *page*.
  50799. **
  50800. ** The right-most entry is the one with the largest key - the last
  50801. ** key in ascending order.
  50802. */
  50803. static int moveToRightmost(BtCursor *pCur){
  50804. Pgno pgno;
  50805. int rc = SQLITE_OK;
  50806. MemPage *pPage = 0;
  50807. assert( cursorHoldsMutex(pCur) );
  50808. assert( pCur->eState==CURSOR_VALID );
  50809. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  50810. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  50811. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  50812. rc = moveToChild(pCur, pgno);
  50813. }
  50814. if( rc==SQLITE_OK ){
  50815. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  50816. pCur->info.nSize = 0;
  50817. pCur->validNKey = 0;
  50818. }
  50819. return rc;
  50820. }
  50821. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  50822. ** on success. Set *pRes to 0 if the cursor actually points to something
  50823. ** or set *pRes to 1 if the table is empty.
  50824. */
  50825. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  50826. int rc;
  50827. assert( cursorHoldsMutex(pCur) );
  50828. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  50829. rc = moveToRoot(pCur);
  50830. if( rc==SQLITE_OK ){
  50831. if( pCur->eState==CURSOR_INVALID ){
  50832. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  50833. *pRes = 1;
  50834. }else{
  50835. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  50836. *pRes = 0;
  50837. rc = moveToLeftmost(pCur);
  50838. }
  50839. }
  50840. return rc;
  50841. }
  50842. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  50843. ** on success. Set *pRes to 0 if the cursor actually points to something
  50844. ** or set *pRes to 1 if the table is empty.
  50845. */
  50846. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  50847. int rc;
  50848. assert( cursorHoldsMutex(pCur) );
  50849. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  50850. /* If the cursor already points to the last entry, this is a no-op. */
  50851. if( CURSOR_VALID==pCur->eState && pCur->atLast ){
  50852. #ifdef SQLITE_DEBUG
  50853. /* This block serves to assert() that the cursor really does point
  50854. ** to the last entry in the b-tree. */
  50855. int ii;
  50856. for(ii=0; ii<pCur->iPage; ii++){
  50857. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  50858. }
  50859. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  50860. assert( pCur->apPage[pCur->iPage]->leaf );
  50861. #endif
  50862. return SQLITE_OK;
  50863. }
  50864. rc = moveToRoot(pCur);
  50865. if( rc==SQLITE_OK ){
  50866. if( CURSOR_INVALID==pCur->eState ){
  50867. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  50868. *pRes = 1;
  50869. }else{
  50870. assert( pCur->eState==CURSOR_VALID );
  50871. *pRes = 0;
  50872. rc = moveToRightmost(pCur);
  50873. pCur->atLast = rc==SQLITE_OK ?1:0;
  50874. }
  50875. }
  50876. return rc;
  50877. }
  50878. /* Move the cursor so that it points to an entry near the key
  50879. ** specified by pIdxKey or intKey. Return a success code.
  50880. **
  50881. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  50882. ** must be NULL. For index tables, pIdxKey is used and intKey
  50883. ** is ignored.
  50884. **
  50885. ** If an exact match is not found, then the cursor is always
  50886. ** left pointing at a leaf page which would hold the entry if it
  50887. ** were present. The cursor might point to an entry that comes
  50888. ** before or after the key.
  50889. **
  50890. ** An integer is written into *pRes which is the result of
  50891. ** comparing the key with the entry to which the cursor is
  50892. ** pointing. The meaning of the integer written into
  50893. ** *pRes is as follows:
  50894. **
  50895. ** *pRes<0 The cursor is left pointing at an entry that
  50896. ** is smaller than intKey/pIdxKey or if the table is empty
  50897. ** and the cursor is therefore left point to nothing.
  50898. **
  50899. ** *pRes==0 The cursor is left pointing at an entry that
  50900. ** exactly matches intKey/pIdxKey.
  50901. **
  50902. ** *pRes>0 The cursor is left pointing at an entry that
  50903. ** is larger than intKey/pIdxKey.
  50904. **
  50905. */
  50906. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  50907. BtCursor *pCur, /* The cursor to be moved */
  50908. UnpackedRecord *pIdxKey, /* Unpacked index key */
  50909. i64 intKey, /* The table key */
  50910. int biasRight, /* If true, bias the search to the high end */
  50911. int *pRes /* Write search results here */
  50912. ){
  50913. int rc;
  50914. assert( cursorHoldsMutex(pCur) );
  50915. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  50916. assert( pRes );
  50917. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  50918. /* If the cursor is already positioned at the point we are trying
  50919. ** to move to, then just return without doing any work */
  50920. if( pCur->eState==CURSOR_VALID && pCur->validNKey
  50921. && pCur->apPage[0]->intKey
  50922. ){
  50923. if( pCur->info.nKey==intKey ){
  50924. *pRes = 0;
  50925. return SQLITE_OK;
  50926. }
  50927. if( pCur->atLast && pCur->info.nKey<intKey ){
  50928. *pRes = -1;
  50929. return SQLITE_OK;
  50930. }
  50931. }
  50932. rc = moveToRoot(pCur);
  50933. if( rc ){
  50934. return rc;
  50935. }
  50936. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  50937. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  50938. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  50939. if( pCur->eState==CURSOR_INVALID ){
  50940. *pRes = -1;
  50941. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  50942. return SQLITE_OK;
  50943. }
  50944. assert( pCur->apPage[0]->intKey || pIdxKey );
  50945. for(;;){
  50946. int lwr, upr, idx;
  50947. Pgno chldPg;
  50948. MemPage *pPage = pCur->apPage[pCur->iPage];
  50949. int c;
  50950. /* pPage->nCell must be greater than zero. If this is the root-page
  50951. ** the cursor would have been INVALID above and this for(;;) loop
  50952. ** not run. If this is not the root-page, then the moveToChild() routine
  50953. ** would have already detected db corruption. Similarly, pPage must
  50954. ** be the right kind (index or table) of b-tree page. Otherwise
  50955. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  50956. assert( pPage->nCell>0 );
  50957. assert( pPage->intKey==(pIdxKey==0) );
  50958. lwr = 0;
  50959. upr = pPage->nCell-1;
  50960. if( biasRight ){
  50961. pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
  50962. }else{
  50963. pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
  50964. }
  50965. for(;;){
  50966. u8 *pCell; /* Pointer to current cell in pPage */
  50967. assert( idx==pCur->aiIdx[pCur->iPage] );
  50968. pCur->info.nSize = 0;
  50969. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  50970. if( pPage->intKey ){
  50971. i64 nCellKey;
  50972. if( pPage->hasData ){
  50973. u32 dummy;
  50974. pCell += getVarint32(pCell, dummy);
  50975. }
  50976. getVarint(pCell, (u64*)&nCellKey);
  50977. if( nCellKey==intKey ){
  50978. c = 0;
  50979. }else if( nCellKey<intKey ){
  50980. c = -1;
  50981. }else{
  50982. assert( nCellKey>intKey );
  50983. c = +1;
  50984. }
  50985. pCur->validNKey = 1;
  50986. pCur->info.nKey = nCellKey;
  50987. }else{
  50988. /* The maximum supported page-size is 65536 bytes. This means that
  50989. ** the maximum number of record bytes stored on an index B-Tree
  50990. ** page is less than 16384 bytes and may be stored as a 2-byte
  50991. ** varint. This information is used to attempt to avoid parsing
  50992. ** the entire cell by checking for the cases where the record is
  50993. ** stored entirely within the b-tree page by inspecting the first
  50994. ** 2 bytes of the cell.
  50995. */
  50996. int nCell = pCell[0];
  50997. if( nCell<=pPage->max1bytePayload
  50998. /* && (pCell+nCell)<pPage->aDataEnd */
  50999. ){
  51000. /* This branch runs if the record-size field of the cell is a
  51001. ** single byte varint and the record fits entirely on the main
  51002. ** b-tree page. */
  51003. testcase( pCell+nCell+1==pPage->aDataEnd );
  51004. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  51005. }else if( !(pCell[1] & 0x80)
  51006. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  51007. /* && (pCell+nCell+2)<=pPage->aDataEnd */
  51008. ){
  51009. /* The record-size field is a 2 byte varint and the record
  51010. ** fits entirely on the main b-tree page. */
  51011. testcase( pCell+nCell+2==pPage->aDataEnd );
  51012. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  51013. }else{
  51014. /* The record flows over onto one or more overflow pages. In
  51015. ** this case the whole cell needs to be parsed, a buffer allocated
  51016. ** and accessPayload() used to retrieve the record into the
  51017. ** buffer before VdbeRecordCompare() can be called. */
  51018. void *pCellKey;
  51019. u8 * const pCellBody = pCell - pPage->childPtrSize;
  51020. btreeParseCellPtr(pPage, pCellBody, &pCur->info);
  51021. nCell = (int)pCur->info.nKey;
  51022. pCellKey = sqlite3Malloc( nCell );
  51023. if( pCellKey==0 ){
  51024. rc = SQLITE_NOMEM;
  51025. goto moveto_finish;
  51026. }
  51027. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  51028. if( rc ){
  51029. sqlite3_free(pCellKey);
  51030. goto moveto_finish;
  51031. }
  51032. c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
  51033. sqlite3_free(pCellKey);
  51034. }
  51035. }
  51036. if( c==0 ){
  51037. if( pPage->intKey && !pPage->leaf ){
  51038. lwr = idx;
  51039. break;
  51040. }else{
  51041. *pRes = 0;
  51042. rc = SQLITE_OK;
  51043. goto moveto_finish;
  51044. }
  51045. }
  51046. if( c<0 ){
  51047. lwr = idx+1;
  51048. }else{
  51049. upr = idx-1;
  51050. }
  51051. if( lwr>upr ){
  51052. break;
  51053. }
  51054. pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
  51055. }
  51056. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  51057. assert( pPage->isInit );
  51058. if( pPage->leaf ){
  51059. chldPg = 0;
  51060. }else if( lwr>=pPage->nCell ){
  51061. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  51062. }else{
  51063. chldPg = get4byte(findCell(pPage, lwr));
  51064. }
  51065. if( chldPg==0 ){
  51066. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  51067. *pRes = c;
  51068. rc = SQLITE_OK;
  51069. goto moveto_finish;
  51070. }
  51071. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  51072. pCur->info.nSize = 0;
  51073. pCur->validNKey = 0;
  51074. rc = moveToChild(pCur, chldPg);
  51075. if( rc ) goto moveto_finish;
  51076. }
  51077. moveto_finish:
  51078. return rc;
  51079. }
  51080. /*
  51081. ** Return TRUE if the cursor is not pointing at an entry of the table.
  51082. **
  51083. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  51084. ** past the last entry in the table or sqlite3BtreePrev() moves past
  51085. ** the first entry. TRUE is also returned if the table is empty.
  51086. */
  51087. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  51088. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  51089. ** have been deleted? This API will need to change to return an error code
  51090. ** as well as the boolean result value.
  51091. */
  51092. return (CURSOR_VALID!=pCur->eState);
  51093. }
  51094. /*
  51095. ** Advance the cursor to the next entry in the database. If
  51096. ** successful then set *pRes=0. If the cursor
  51097. ** was already pointing to the last entry in the database before
  51098. ** this routine was called, then set *pRes=1.
  51099. */
  51100. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  51101. int rc;
  51102. int idx;
  51103. MemPage *pPage;
  51104. assert( cursorHoldsMutex(pCur) );
  51105. assert( pRes!=0 );
  51106. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  51107. if( pCur->eState!=CURSOR_VALID ){
  51108. rc = restoreCursorPosition(pCur);
  51109. if( rc!=SQLITE_OK ){
  51110. *pRes = 0;
  51111. return rc;
  51112. }
  51113. if( CURSOR_INVALID==pCur->eState ){
  51114. *pRes = 1;
  51115. return SQLITE_OK;
  51116. }
  51117. if( pCur->skipNext ){
  51118. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  51119. pCur->eState = CURSOR_VALID;
  51120. if( pCur->skipNext>0 ){
  51121. pCur->skipNext = 0;
  51122. *pRes = 0;
  51123. return SQLITE_OK;
  51124. }
  51125. pCur->skipNext = 0;
  51126. }
  51127. }
  51128. pPage = pCur->apPage[pCur->iPage];
  51129. idx = ++pCur->aiIdx[pCur->iPage];
  51130. assert( pPage->isInit );
  51131. /* If the database file is corrupt, it is possible for the value of idx
  51132. ** to be invalid here. This can only occur if a second cursor modifies
  51133. ** the page while cursor pCur is holding a reference to it. Which can
  51134. ** only happen if the database is corrupt in such a way as to link the
  51135. ** page into more than one b-tree structure. */
  51136. testcase( idx>pPage->nCell );
  51137. pCur->info.nSize = 0;
  51138. pCur->validNKey = 0;
  51139. if( idx>=pPage->nCell ){
  51140. if( !pPage->leaf ){
  51141. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  51142. if( rc ){
  51143. *pRes = 0;
  51144. return rc;
  51145. }
  51146. rc = moveToLeftmost(pCur);
  51147. *pRes = 0;
  51148. return rc;
  51149. }
  51150. do{
  51151. if( pCur->iPage==0 ){
  51152. *pRes = 1;
  51153. pCur->eState = CURSOR_INVALID;
  51154. return SQLITE_OK;
  51155. }
  51156. moveToParent(pCur);
  51157. pPage = pCur->apPage[pCur->iPage];
  51158. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  51159. *pRes = 0;
  51160. if( pPage->intKey ){
  51161. rc = sqlite3BtreeNext(pCur, pRes);
  51162. }else{
  51163. rc = SQLITE_OK;
  51164. }
  51165. return rc;
  51166. }
  51167. *pRes = 0;
  51168. if( pPage->leaf ){
  51169. return SQLITE_OK;
  51170. }
  51171. rc = moveToLeftmost(pCur);
  51172. return rc;
  51173. }
  51174. /*
  51175. ** Step the cursor to the back to the previous entry in the database. If
  51176. ** successful then set *pRes=0. If the cursor
  51177. ** was already pointing to the first entry in the database before
  51178. ** this routine was called, then set *pRes=1.
  51179. */
  51180. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  51181. int rc;
  51182. MemPage *pPage;
  51183. assert( cursorHoldsMutex(pCur) );
  51184. assert( pRes!=0 );
  51185. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  51186. pCur->atLast = 0;
  51187. if( pCur->eState!=CURSOR_VALID ){
  51188. if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){
  51189. rc = btreeRestoreCursorPosition(pCur);
  51190. if( rc!=SQLITE_OK ){
  51191. *pRes = 0;
  51192. return rc;
  51193. }
  51194. }
  51195. if( CURSOR_INVALID==pCur->eState ){
  51196. *pRes = 1;
  51197. return SQLITE_OK;
  51198. }
  51199. if( pCur->skipNext ){
  51200. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  51201. pCur->eState = CURSOR_VALID;
  51202. if( pCur->skipNext<0 ){
  51203. pCur->skipNext = 0;
  51204. *pRes = 0;
  51205. return SQLITE_OK;
  51206. }
  51207. pCur->skipNext = 0;
  51208. }
  51209. }
  51210. pPage = pCur->apPage[pCur->iPage];
  51211. assert( pPage->isInit );
  51212. if( !pPage->leaf ){
  51213. int idx = pCur->aiIdx[pCur->iPage];
  51214. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  51215. if( rc ){
  51216. *pRes = 0;
  51217. return rc;
  51218. }
  51219. rc = moveToRightmost(pCur);
  51220. }else{
  51221. while( pCur->aiIdx[pCur->iPage]==0 ){
  51222. if( pCur->iPage==0 ){
  51223. pCur->eState = CURSOR_INVALID;
  51224. *pRes = 1;
  51225. return SQLITE_OK;
  51226. }
  51227. moveToParent(pCur);
  51228. }
  51229. pCur->info.nSize = 0;
  51230. pCur->validNKey = 0;
  51231. pCur->aiIdx[pCur->iPage]--;
  51232. pPage = pCur->apPage[pCur->iPage];
  51233. if( pPage->intKey && !pPage->leaf ){
  51234. rc = sqlite3BtreePrevious(pCur, pRes);
  51235. }else{
  51236. rc = SQLITE_OK;
  51237. }
  51238. }
  51239. *pRes = 0;
  51240. return rc;
  51241. }
  51242. /*
  51243. ** Allocate a new page from the database file.
  51244. **
  51245. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  51246. ** has already been called on the new page.) The new page has also
  51247. ** been referenced and the calling routine is responsible for calling
  51248. ** sqlite3PagerUnref() on the new page when it is done.
  51249. **
  51250. ** SQLITE_OK is returned on success. Any other return value indicates
  51251. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  51252. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  51253. **
  51254. ** If the "nearby" parameter is not 0, then an effort is made to
  51255. ** locate a page close to the page number "nearby". This can be used in an
  51256. ** attempt to keep related pages close to each other in the database file,
  51257. ** which in turn can make database access faster.
  51258. **
  51259. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  51260. ** anywhere on the free-list, then it is guaranteed to be returned. If
  51261. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  51262. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  51263. ** are no restrictions on which page is returned.
  51264. */
  51265. static int allocateBtreePage(
  51266. BtShared *pBt, /* The btree */
  51267. MemPage **ppPage, /* Store pointer to the allocated page here */
  51268. Pgno *pPgno, /* Store the page number here */
  51269. Pgno nearby, /* Search for a page near this one */
  51270. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  51271. ){
  51272. MemPage *pPage1;
  51273. int rc;
  51274. u32 n; /* Number of pages on the freelist */
  51275. u32 k; /* Number of leaves on the trunk of the freelist */
  51276. MemPage *pTrunk = 0;
  51277. MemPage *pPrevTrunk = 0;
  51278. Pgno mxPage; /* Total size of the database file */
  51279. assert( sqlite3_mutex_held(pBt->mutex) );
  51280. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  51281. pPage1 = pBt->pPage1;
  51282. mxPage = btreePagecount(pBt);
  51283. n = get4byte(&pPage1->aData[36]);
  51284. testcase( n==mxPage-1 );
  51285. if( n>=mxPage ){
  51286. return SQLITE_CORRUPT_BKPT;
  51287. }
  51288. if( n>0 ){
  51289. /* There are pages on the freelist. Reuse one of those pages. */
  51290. Pgno iTrunk;
  51291. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  51292. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  51293. ** shows that the page 'nearby' is somewhere on the free-list, then
  51294. ** the entire-list will be searched for that page.
  51295. */
  51296. #ifndef SQLITE_OMIT_AUTOVACUUM
  51297. if( eMode==BTALLOC_EXACT ){
  51298. if( nearby<=mxPage ){
  51299. u8 eType;
  51300. assert( nearby>0 );
  51301. assert( pBt->autoVacuum );
  51302. rc = ptrmapGet(pBt, nearby, &eType, 0);
  51303. if( rc ) return rc;
  51304. if( eType==PTRMAP_FREEPAGE ){
  51305. searchList = 1;
  51306. }
  51307. }
  51308. }else if( eMode==BTALLOC_LE ){
  51309. searchList = 1;
  51310. }
  51311. #endif
  51312. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  51313. ** first free-list trunk page. iPrevTrunk is initially 1.
  51314. */
  51315. rc = sqlite3PagerWrite(pPage1->pDbPage);
  51316. if( rc ) return rc;
  51317. put4byte(&pPage1->aData[36], n-1);
  51318. /* The code within this loop is run only once if the 'searchList' variable
  51319. ** is not true. Otherwise, it runs once for each trunk-page on the
  51320. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  51321. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  51322. */
  51323. do {
  51324. pPrevTrunk = pTrunk;
  51325. if( pPrevTrunk ){
  51326. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  51327. }else{
  51328. iTrunk = get4byte(&pPage1->aData[32]);
  51329. }
  51330. testcase( iTrunk==mxPage );
  51331. if( iTrunk>mxPage ){
  51332. rc = SQLITE_CORRUPT_BKPT;
  51333. }else{
  51334. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  51335. }
  51336. if( rc ){
  51337. pTrunk = 0;
  51338. goto end_allocate_page;
  51339. }
  51340. assert( pTrunk!=0 );
  51341. assert( pTrunk->aData!=0 );
  51342. k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
  51343. if( k==0 && !searchList ){
  51344. /* The trunk has no leaves and the list is not being searched.
  51345. ** So extract the trunk page itself and use it as the newly
  51346. ** allocated page */
  51347. assert( pPrevTrunk==0 );
  51348. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  51349. if( rc ){
  51350. goto end_allocate_page;
  51351. }
  51352. *pPgno = iTrunk;
  51353. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  51354. *ppPage = pTrunk;
  51355. pTrunk = 0;
  51356. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  51357. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  51358. /* Value of k is out of range. Database corruption */
  51359. rc = SQLITE_CORRUPT_BKPT;
  51360. goto end_allocate_page;
  51361. #ifndef SQLITE_OMIT_AUTOVACUUM
  51362. }else if( searchList
  51363. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  51364. ){
  51365. /* The list is being searched and this trunk page is the page
  51366. ** to allocate, regardless of whether it has leaves.
  51367. */
  51368. *pPgno = iTrunk;
  51369. *ppPage = pTrunk;
  51370. searchList = 0;
  51371. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  51372. if( rc ){
  51373. goto end_allocate_page;
  51374. }
  51375. if( k==0 ){
  51376. if( !pPrevTrunk ){
  51377. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  51378. }else{
  51379. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  51380. if( rc!=SQLITE_OK ){
  51381. goto end_allocate_page;
  51382. }
  51383. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  51384. }
  51385. }else{
  51386. /* The trunk page is required by the caller but it contains
  51387. ** pointers to free-list leaves. The first leaf becomes a trunk
  51388. ** page in this case.
  51389. */
  51390. MemPage *pNewTrunk;
  51391. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  51392. if( iNewTrunk>mxPage ){
  51393. rc = SQLITE_CORRUPT_BKPT;
  51394. goto end_allocate_page;
  51395. }
  51396. testcase( iNewTrunk==mxPage );
  51397. rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  51398. if( rc!=SQLITE_OK ){
  51399. goto end_allocate_page;
  51400. }
  51401. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  51402. if( rc!=SQLITE_OK ){
  51403. releasePage(pNewTrunk);
  51404. goto end_allocate_page;
  51405. }
  51406. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  51407. put4byte(&pNewTrunk->aData[4], k-1);
  51408. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  51409. releasePage(pNewTrunk);
  51410. if( !pPrevTrunk ){
  51411. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  51412. put4byte(&pPage1->aData[32], iNewTrunk);
  51413. }else{
  51414. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  51415. if( rc ){
  51416. goto end_allocate_page;
  51417. }
  51418. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  51419. }
  51420. }
  51421. pTrunk = 0;
  51422. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  51423. #endif
  51424. }else if( k>0 ){
  51425. /* Extract a leaf from the trunk */
  51426. u32 closest;
  51427. Pgno iPage;
  51428. unsigned char *aData = pTrunk->aData;
  51429. if( nearby>0 ){
  51430. u32 i;
  51431. closest = 0;
  51432. if( eMode==BTALLOC_LE ){
  51433. for(i=0; i<k; i++){
  51434. iPage = get4byte(&aData[8+i*4]);
  51435. if( iPage<=nearby ){
  51436. closest = i;
  51437. break;
  51438. }
  51439. }
  51440. }else{
  51441. int dist;
  51442. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  51443. for(i=1; i<k; i++){
  51444. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  51445. if( d2<dist ){
  51446. closest = i;
  51447. dist = d2;
  51448. }
  51449. }
  51450. }
  51451. }else{
  51452. closest = 0;
  51453. }
  51454. iPage = get4byte(&aData[8+closest*4]);
  51455. testcase( iPage==mxPage );
  51456. if( iPage>mxPage ){
  51457. rc = SQLITE_CORRUPT_BKPT;
  51458. goto end_allocate_page;
  51459. }
  51460. testcase( iPage==mxPage );
  51461. if( !searchList
  51462. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  51463. ){
  51464. int noContent;
  51465. *pPgno = iPage;
  51466. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  51467. ": %d more free pages\n",
  51468. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  51469. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  51470. if( rc ) goto end_allocate_page;
  51471. if( closest<k-1 ){
  51472. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  51473. }
  51474. put4byte(&aData[4], k-1);
  51475. noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
  51476. rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
  51477. if( rc==SQLITE_OK ){
  51478. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  51479. if( rc!=SQLITE_OK ){
  51480. releasePage(*ppPage);
  51481. }
  51482. }
  51483. searchList = 0;
  51484. }
  51485. }
  51486. releasePage(pPrevTrunk);
  51487. pPrevTrunk = 0;
  51488. }while( searchList );
  51489. }else{
  51490. /* There are no pages on the freelist, so append a new page to the
  51491. ** database image.
  51492. **
  51493. ** Normally, new pages allocated by this block can be requested from the
  51494. ** pager layer with the 'no-content' flag set. This prevents the pager
  51495. ** from trying to read the pages content from disk. However, if the
  51496. ** current transaction has already run one or more incremental-vacuum
  51497. ** steps, then the page we are about to allocate may contain content
  51498. ** that is required in the event of a rollback. In this case, do
  51499. ** not set the no-content flag. This causes the pager to load and journal
  51500. ** the current page content before overwriting it.
  51501. **
  51502. ** Note that the pager will not actually attempt to load or journal
  51503. ** content for any page that really does lie past the end of the database
  51504. ** file on disk. So the effects of disabling the no-content optimization
  51505. ** here are confined to those pages that lie between the end of the
  51506. ** database image and the end of the database file.
  51507. */
  51508. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
  51509. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  51510. if( rc ) return rc;
  51511. pBt->nPage++;
  51512. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  51513. #ifndef SQLITE_OMIT_AUTOVACUUM
  51514. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  51515. /* If *pPgno refers to a pointer-map page, allocate two new pages
  51516. ** at the end of the file instead of one. The first allocated page
  51517. ** becomes a new pointer-map page, the second is used by the caller.
  51518. */
  51519. MemPage *pPg = 0;
  51520. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  51521. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  51522. rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
  51523. if( rc==SQLITE_OK ){
  51524. rc = sqlite3PagerWrite(pPg->pDbPage);
  51525. releasePage(pPg);
  51526. }
  51527. if( rc ) return rc;
  51528. pBt->nPage++;
  51529. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  51530. }
  51531. #endif
  51532. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  51533. *pPgno = pBt->nPage;
  51534. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  51535. rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
  51536. if( rc ) return rc;
  51537. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  51538. if( rc!=SQLITE_OK ){
  51539. releasePage(*ppPage);
  51540. }
  51541. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  51542. }
  51543. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  51544. end_allocate_page:
  51545. releasePage(pTrunk);
  51546. releasePage(pPrevTrunk);
  51547. if( rc==SQLITE_OK ){
  51548. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  51549. releasePage(*ppPage);
  51550. return SQLITE_CORRUPT_BKPT;
  51551. }
  51552. (*ppPage)->isInit = 0;
  51553. }else{
  51554. *ppPage = 0;
  51555. }
  51556. assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
  51557. return rc;
  51558. }
  51559. /*
  51560. ** This function is used to add page iPage to the database file free-list.
  51561. ** It is assumed that the page is not already a part of the free-list.
  51562. **
  51563. ** The value passed as the second argument to this function is optional.
  51564. ** If the caller happens to have a pointer to the MemPage object
  51565. ** corresponding to page iPage handy, it may pass it as the second value.
  51566. ** Otherwise, it may pass NULL.
  51567. **
  51568. ** If a pointer to a MemPage object is passed as the second argument,
  51569. ** its reference count is not altered by this function.
  51570. */
  51571. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  51572. MemPage *pTrunk = 0; /* Free-list trunk page */
  51573. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  51574. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  51575. MemPage *pPage; /* Page being freed. May be NULL. */
  51576. int rc; /* Return Code */
  51577. int nFree; /* Initial number of pages on free-list */
  51578. assert( sqlite3_mutex_held(pBt->mutex) );
  51579. assert( iPage>1 );
  51580. assert( !pMemPage || pMemPage->pgno==iPage );
  51581. if( pMemPage ){
  51582. pPage = pMemPage;
  51583. sqlite3PagerRef(pPage->pDbPage);
  51584. }else{
  51585. pPage = btreePageLookup(pBt, iPage);
  51586. }
  51587. /* Increment the free page count on pPage1 */
  51588. rc = sqlite3PagerWrite(pPage1->pDbPage);
  51589. if( rc ) goto freepage_out;
  51590. nFree = get4byte(&pPage1->aData[36]);
  51591. put4byte(&pPage1->aData[36], nFree+1);
  51592. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  51593. /* If the secure_delete option is enabled, then
  51594. ** always fully overwrite deleted information with zeros.
  51595. */
  51596. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  51597. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  51598. ){
  51599. goto freepage_out;
  51600. }
  51601. memset(pPage->aData, 0, pPage->pBt->pageSize);
  51602. }
  51603. /* If the database supports auto-vacuum, write an entry in the pointer-map
  51604. ** to indicate that the page is free.
  51605. */
  51606. if( ISAUTOVACUUM ){
  51607. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  51608. if( rc ) goto freepage_out;
  51609. }
  51610. /* Now manipulate the actual database free-list structure. There are two
  51611. ** possibilities. If the free-list is currently empty, or if the first
  51612. ** trunk page in the free-list is full, then this page will become a
  51613. ** new free-list trunk page. Otherwise, it will become a leaf of the
  51614. ** first trunk page in the current free-list. This block tests if it
  51615. ** is possible to add the page as a new free-list leaf.
  51616. */
  51617. if( nFree!=0 ){
  51618. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  51619. iTrunk = get4byte(&pPage1->aData[32]);
  51620. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  51621. if( rc!=SQLITE_OK ){
  51622. goto freepage_out;
  51623. }
  51624. nLeaf = get4byte(&pTrunk->aData[4]);
  51625. assert( pBt->usableSize>32 );
  51626. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  51627. rc = SQLITE_CORRUPT_BKPT;
  51628. goto freepage_out;
  51629. }
  51630. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  51631. /* In this case there is room on the trunk page to insert the page
  51632. ** being freed as a new leaf.
  51633. **
  51634. ** Note that the trunk page is not really full until it contains
  51635. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  51636. ** coded. But due to a coding error in versions of SQLite prior to
  51637. ** 3.6.0, databases with freelist trunk pages holding more than
  51638. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  51639. ** to maintain backwards compatibility with older versions of SQLite,
  51640. ** we will continue to restrict the number of entries to usableSize/4 - 8
  51641. ** for now. At some point in the future (once everyone has upgraded
  51642. ** to 3.6.0 or later) we should consider fixing the conditional above
  51643. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  51644. */
  51645. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  51646. if( rc==SQLITE_OK ){
  51647. put4byte(&pTrunk->aData[4], nLeaf+1);
  51648. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  51649. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  51650. sqlite3PagerDontWrite(pPage->pDbPage);
  51651. }
  51652. rc = btreeSetHasContent(pBt, iPage);
  51653. }
  51654. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  51655. goto freepage_out;
  51656. }
  51657. }
  51658. /* If control flows to this point, then it was not possible to add the
  51659. ** the page being freed as a leaf page of the first trunk in the free-list.
  51660. ** Possibly because the free-list is empty, or possibly because the
  51661. ** first trunk in the free-list is full. Either way, the page being freed
  51662. ** will become the new first trunk page in the free-list.
  51663. */
  51664. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  51665. goto freepage_out;
  51666. }
  51667. rc = sqlite3PagerWrite(pPage->pDbPage);
  51668. if( rc!=SQLITE_OK ){
  51669. goto freepage_out;
  51670. }
  51671. put4byte(pPage->aData, iTrunk);
  51672. put4byte(&pPage->aData[4], 0);
  51673. put4byte(&pPage1->aData[32], iPage);
  51674. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  51675. freepage_out:
  51676. if( pPage ){
  51677. pPage->isInit = 0;
  51678. }
  51679. releasePage(pPage);
  51680. releasePage(pTrunk);
  51681. return rc;
  51682. }
  51683. static void freePage(MemPage *pPage, int *pRC){
  51684. if( (*pRC)==SQLITE_OK ){
  51685. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  51686. }
  51687. }
  51688. /*
  51689. ** Free any overflow pages associated with the given Cell.
  51690. */
  51691. static int clearCell(MemPage *pPage, unsigned char *pCell){
  51692. BtShared *pBt = pPage->pBt;
  51693. CellInfo info;
  51694. Pgno ovflPgno;
  51695. int rc;
  51696. int nOvfl;
  51697. u32 ovflPageSize;
  51698. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51699. btreeParseCellPtr(pPage, pCell, &info);
  51700. if( info.iOverflow==0 ){
  51701. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  51702. }
  51703. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  51704. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  51705. }
  51706. ovflPgno = get4byte(&pCell[info.iOverflow]);
  51707. assert( pBt->usableSize > 4 );
  51708. ovflPageSize = pBt->usableSize - 4;
  51709. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  51710. assert( ovflPgno==0 || nOvfl>0 );
  51711. while( nOvfl-- ){
  51712. Pgno iNext = 0;
  51713. MemPage *pOvfl = 0;
  51714. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  51715. /* 0 is not a legal page number and page 1 cannot be an
  51716. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  51717. ** file the database must be corrupt. */
  51718. return SQLITE_CORRUPT_BKPT;
  51719. }
  51720. if( nOvfl ){
  51721. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  51722. if( rc ) return rc;
  51723. }
  51724. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  51725. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  51726. ){
  51727. /* There is no reason any cursor should have an outstanding reference
  51728. ** to an overflow page belonging to a cell that is being deleted/updated.
  51729. ** So if there exists more than one reference to this page, then it
  51730. ** must not really be an overflow page and the database must be corrupt.
  51731. ** It is helpful to detect this before calling freePage2(), as
  51732. ** freePage2() may zero the page contents if secure-delete mode is
  51733. ** enabled. If this 'overflow' page happens to be a page that the
  51734. ** caller is iterating through or using in some other way, this
  51735. ** can be problematic.
  51736. */
  51737. rc = SQLITE_CORRUPT_BKPT;
  51738. }else{
  51739. rc = freePage2(pBt, pOvfl, ovflPgno);
  51740. }
  51741. if( pOvfl ){
  51742. sqlite3PagerUnref(pOvfl->pDbPage);
  51743. }
  51744. if( rc ) return rc;
  51745. ovflPgno = iNext;
  51746. }
  51747. return SQLITE_OK;
  51748. }
  51749. /*
  51750. ** Create the byte sequence used to represent a cell on page pPage
  51751. ** and write that byte sequence into pCell[]. Overflow pages are
  51752. ** allocated and filled in as necessary. The calling procedure
  51753. ** is responsible for making sure sufficient space has been allocated
  51754. ** for pCell[].
  51755. **
  51756. ** Note that pCell does not necessary need to point to the pPage->aData
  51757. ** area. pCell might point to some temporary storage. The cell will
  51758. ** be constructed in this temporary area then copied into pPage->aData
  51759. ** later.
  51760. */
  51761. static int fillInCell(
  51762. MemPage *pPage, /* The page that contains the cell */
  51763. unsigned char *pCell, /* Complete text of the cell */
  51764. const void *pKey, i64 nKey, /* The key */
  51765. const void *pData,int nData, /* The data */
  51766. int nZero, /* Extra zero bytes to append to pData */
  51767. int *pnSize /* Write cell size here */
  51768. ){
  51769. int nPayload;
  51770. const u8 *pSrc;
  51771. int nSrc, n, rc;
  51772. int spaceLeft;
  51773. MemPage *pOvfl = 0;
  51774. MemPage *pToRelease = 0;
  51775. unsigned char *pPrior;
  51776. unsigned char *pPayload;
  51777. BtShared *pBt = pPage->pBt;
  51778. Pgno pgnoOvfl = 0;
  51779. int nHeader;
  51780. CellInfo info;
  51781. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51782. /* pPage is not necessarily writeable since pCell might be auxiliary
  51783. ** buffer space that is separate from the pPage buffer area */
  51784. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  51785. || sqlite3PagerIswriteable(pPage->pDbPage) );
  51786. /* Fill in the header. */
  51787. nHeader = 0;
  51788. if( !pPage->leaf ){
  51789. nHeader += 4;
  51790. }
  51791. if( pPage->hasData ){
  51792. nHeader += putVarint(&pCell[nHeader], nData+nZero);
  51793. }else{
  51794. nData = nZero = 0;
  51795. }
  51796. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  51797. btreeParseCellPtr(pPage, pCell, &info);
  51798. assert( info.nHeader==nHeader );
  51799. assert( info.nKey==nKey );
  51800. assert( info.nData==(u32)(nData+nZero) );
  51801. /* Fill in the payload */
  51802. nPayload = nData + nZero;
  51803. if( pPage->intKey ){
  51804. pSrc = pData;
  51805. nSrc = nData;
  51806. nData = 0;
  51807. }else{
  51808. if( NEVER(nKey>0x7fffffff || pKey==0) ){
  51809. return SQLITE_CORRUPT_BKPT;
  51810. }
  51811. nPayload += (int)nKey;
  51812. pSrc = pKey;
  51813. nSrc = (int)nKey;
  51814. }
  51815. *pnSize = info.nSize;
  51816. spaceLeft = info.nLocal;
  51817. pPayload = &pCell[nHeader];
  51818. pPrior = &pCell[info.iOverflow];
  51819. while( nPayload>0 ){
  51820. if( spaceLeft==0 ){
  51821. #ifndef SQLITE_OMIT_AUTOVACUUM
  51822. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  51823. if( pBt->autoVacuum ){
  51824. do{
  51825. pgnoOvfl++;
  51826. } while(
  51827. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  51828. );
  51829. }
  51830. #endif
  51831. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  51832. #ifndef SQLITE_OMIT_AUTOVACUUM
  51833. /* If the database supports auto-vacuum, and the second or subsequent
  51834. ** overflow page is being allocated, add an entry to the pointer-map
  51835. ** for that page now.
  51836. **
  51837. ** If this is the first overflow page, then write a partial entry
  51838. ** to the pointer-map. If we write nothing to this pointer-map slot,
  51839. ** then the optimistic overflow chain processing in clearCell()
  51840. ** may misinterpret the uninitialized values and delete the
  51841. ** wrong pages from the database.
  51842. */
  51843. if( pBt->autoVacuum && rc==SQLITE_OK ){
  51844. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  51845. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  51846. if( rc ){
  51847. releasePage(pOvfl);
  51848. }
  51849. }
  51850. #endif
  51851. if( rc ){
  51852. releasePage(pToRelease);
  51853. return rc;
  51854. }
  51855. /* If pToRelease is not zero than pPrior points into the data area
  51856. ** of pToRelease. Make sure pToRelease is still writeable. */
  51857. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  51858. /* If pPrior is part of the data area of pPage, then make sure pPage
  51859. ** is still writeable */
  51860. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  51861. || sqlite3PagerIswriteable(pPage->pDbPage) );
  51862. put4byte(pPrior, pgnoOvfl);
  51863. releasePage(pToRelease);
  51864. pToRelease = pOvfl;
  51865. pPrior = pOvfl->aData;
  51866. put4byte(pPrior, 0);
  51867. pPayload = &pOvfl->aData[4];
  51868. spaceLeft = pBt->usableSize - 4;
  51869. }
  51870. n = nPayload;
  51871. if( n>spaceLeft ) n = spaceLeft;
  51872. /* If pToRelease is not zero than pPayload points into the data area
  51873. ** of pToRelease. Make sure pToRelease is still writeable. */
  51874. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  51875. /* If pPayload is part of the data area of pPage, then make sure pPage
  51876. ** is still writeable */
  51877. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  51878. || sqlite3PagerIswriteable(pPage->pDbPage) );
  51879. if( nSrc>0 ){
  51880. if( n>nSrc ) n = nSrc;
  51881. assert( pSrc );
  51882. memcpy(pPayload, pSrc, n);
  51883. }else{
  51884. memset(pPayload, 0, n);
  51885. }
  51886. nPayload -= n;
  51887. pPayload += n;
  51888. pSrc += n;
  51889. nSrc -= n;
  51890. spaceLeft -= n;
  51891. if( nSrc==0 ){
  51892. nSrc = nData;
  51893. pSrc = pData;
  51894. }
  51895. }
  51896. releasePage(pToRelease);
  51897. return SQLITE_OK;
  51898. }
  51899. /*
  51900. ** Remove the i-th cell from pPage. This routine effects pPage only.
  51901. ** The cell content is not freed or deallocated. It is assumed that
  51902. ** the cell content has been copied someplace else. This routine just
  51903. ** removes the reference to the cell from pPage.
  51904. **
  51905. ** "sz" must be the number of bytes in the cell.
  51906. */
  51907. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  51908. u32 pc; /* Offset to cell content of cell being deleted */
  51909. u8 *data; /* pPage->aData */
  51910. u8 *ptr; /* Used to move bytes around within data[] */
  51911. u8 *endPtr; /* End of loop */
  51912. int rc; /* The return code */
  51913. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  51914. if( *pRC ) return;
  51915. assert( idx>=0 && idx<pPage->nCell );
  51916. assert( sz==cellSize(pPage, idx) );
  51917. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51918. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51919. data = pPage->aData;
  51920. ptr = &pPage->aCellIdx[2*idx];
  51921. pc = get2byte(ptr);
  51922. hdr = pPage->hdrOffset;
  51923. testcase( pc==get2byte(&data[hdr+5]) );
  51924. testcase( pc+sz==pPage->pBt->usableSize );
  51925. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  51926. *pRC = SQLITE_CORRUPT_BKPT;
  51927. return;
  51928. }
  51929. rc = freeSpace(pPage, pc, sz);
  51930. if( rc ){
  51931. *pRC = rc;
  51932. return;
  51933. }
  51934. endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
  51935. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  51936. while( ptr<endPtr ){
  51937. *(u16*)ptr = *(u16*)&ptr[2];
  51938. ptr += 2;
  51939. }
  51940. pPage->nCell--;
  51941. put2byte(&data[hdr+3], pPage->nCell);
  51942. pPage->nFree += 2;
  51943. }
  51944. /*
  51945. ** Insert a new cell on pPage at cell index "i". pCell points to the
  51946. ** content of the cell.
  51947. **
  51948. ** If the cell content will fit on the page, then put it there. If it
  51949. ** will not fit, then make a copy of the cell content into pTemp if
  51950. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  51951. ** in pPage->apOvfl[] and make it point to the cell content (either
  51952. ** in pTemp or the original pCell) and also record its index.
  51953. ** Allocating a new entry in pPage->aCell[] implies that
  51954. ** pPage->nOverflow is incremented.
  51955. **
  51956. ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
  51957. ** cell. The caller will overwrite them after this function returns. If
  51958. ** nSkip is non-zero, then pCell may not point to an invalid memory location
  51959. ** (but pCell+nSkip is always valid).
  51960. */
  51961. static void insertCell(
  51962. MemPage *pPage, /* Page into which we are copying */
  51963. int i, /* New cell becomes the i-th cell of the page */
  51964. u8 *pCell, /* Content of the new cell */
  51965. int sz, /* Bytes of content in pCell */
  51966. u8 *pTemp, /* Temp storage space for pCell, if needed */
  51967. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  51968. int *pRC /* Read and write return code from here */
  51969. ){
  51970. int idx = 0; /* Where to write new cell content in data[] */
  51971. int j; /* Loop counter */
  51972. int end; /* First byte past the last cell pointer in data[] */
  51973. int ins; /* Index in data[] where new cell pointer is inserted */
  51974. int cellOffset; /* Address of first cell pointer in data[] */
  51975. u8 *data; /* The content of the whole page */
  51976. u8 *ptr; /* Used for moving information around in data[] */
  51977. u8 *endPtr; /* End of the loop */
  51978. int nSkip = (iChild ? 4 : 0);
  51979. if( *pRC ) return;
  51980. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  51981. assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
  51982. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  51983. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  51984. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51985. /* The cell should normally be sized correctly. However, when moving a
  51986. ** malformed cell from a leaf page to an interior page, if the cell size
  51987. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  51988. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  51989. ** the term after the || in the following assert(). */
  51990. assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
  51991. if( pPage->nOverflow || sz+2>pPage->nFree ){
  51992. if( pTemp ){
  51993. memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
  51994. pCell = pTemp;
  51995. }
  51996. if( iChild ){
  51997. put4byte(pCell, iChild);
  51998. }
  51999. j = pPage->nOverflow++;
  52000. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  52001. pPage->apOvfl[j] = pCell;
  52002. pPage->aiOvfl[j] = (u16)i;
  52003. }else{
  52004. int rc = sqlite3PagerWrite(pPage->pDbPage);
  52005. if( rc!=SQLITE_OK ){
  52006. *pRC = rc;
  52007. return;
  52008. }
  52009. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52010. data = pPage->aData;
  52011. cellOffset = pPage->cellOffset;
  52012. end = cellOffset + 2*pPage->nCell;
  52013. ins = cellOffset + 2*i;
  52014. rc = allocateSpace(pPage, sz, &idx);
  52015. if( rc ){ *pRC = rc; return; }
  52016. /* The allocateSpace() routine guarantees the following two properties
  52017. ** if it returns success */
  52018. assert( idx >= end+2 );
  52019. assert( idx+sz <= (int)pPage->pBt->usableSize );
  52020. pPage->nCell++;
  52021. pPage->nFree -= (u16)(2 + sz);
  52022. memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
  52023. if( iChild ){
  52024. put4byte(&data[idx], iChild);
  52025. }
  52026. ptr = &data[end];
  52027. endPtr = &data[ins];
  52028. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  52029. while( ptr>endPtr ){
  52030. *(u16*)ptr = *(u16*)&ptr[-2];
  52031. ptr -= 2;
  52032. }
  52033. put2byte(&data[ins], idx);
  52034. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  52035. #ifndef SQLITE_OMIT_AUTOVACUUM
  52036. if( pPage->pBt->autoVacuum ){
  52037. /* The cell may contain a pointer to an overflow page. If so, write
  52038. ** the entry for the overflow page into the pointer map.
  52039. */
  52040. ptrmapPutOvflPtr(pPage, pCell, pRC);
  52041. }
  52042. #endif
  52043. }
  52044. }
  52045. /*
  52046. ** Add a list of cells to a page. The page should be initially empty.
  52047. ** The cells are guaranteed to fit on the page.
  52048. */
  52049. static void assemblePage(
  52050. MemPage *pPage, /* The page to be assemblied */
  52051. int nCell, /* The number of cells to add to this page */
  52052. u8 **apCell, /* Pointers to cell bodies */
  52053. u16 *aSize /* Sizes of the cells */
  52054. ){
  52055. int i; /* Loop counter */
  52056. u8 *pCellptr; /* Address of next cell pointer */
  52057. int cellbody; /* Address of next cell body */
  52058. u8 * const data = pPage->aData; /* Pointer to data for pPage */
  52059. const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
  52060. const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
  52061. assert( pPage->nOverflow==0 );
  52062. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52063. assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
  52064. && (int)MX_CELL(pPage->pBt)<=10921);
  52065. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52066. /* Check that the page has just been zeroed by zeroPage() */
  52067. assert( pPage->nCell==0 );
  52068. assert( get2byteNotZero(&data[hdr+5])==nUsable );
  52069. pCellptr = &pPage->aCellIdx[nCell*2];
  52070. cellbody = nUsable;
  52071. for(i=nCell-1; i>=0; i--){
  52072. u16 sz = aSize[i];
  52073. pCellptr -= 2;
  52074. cellbody -= sz;
  52075. put2byte(pCellptr, cellbody);
  52076. memcpy(&data[cellbody], apCell[i], sz);
  52077. }
  52078. put2byte(&data[hdr+3], nCell);
  52079. put2byte(&data[hdr+5], cellbody);
  52080. pPage->nFree -= (nCell*2 + nUsable - cellbody);
  52081. pPage->nCell = (u16)nCell;
  52082. }
  52083. /*
  52084. ** The following parameters determine how many adjacent pages get involved
  52085. ** in a balancing operation. NN is the number of neighbors on either side
  52086. ** of the page that participate in the balancing operation. NB is the
  52087. ** total number of pages that participate, including the target page and
  52088. ** NN neighbors on either side.
  52089. **
  52090. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  52091. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  52092. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  52093. ** The value of NN appears to give the best results overall.
  52094. */
  52095. #define NN 1 /* Number of neighbors on either side of pPage */
  52096. #define NB (NN*2+1) /* Total pages involved in the balance */
  52097. #ifndef SQLITE_OMIT_QUICKBALANCE
  52098. /*
  52099. ** This version of balance() handles the common special case where
  52100. ** a new entry is being inserted on the extreme right-end of the
  52101. ** tree, in other words, when the new entry will become the largest
  52102. ** entry in the tree.
  52103. **
  52104. ** Instead of trying to balance the 3 right-most leaf pages, just add
  52105. ** a new page to the right-hand side and put the one new entry in
  52106. ** that page. This leaves the right side of the tree somewhat
  52107. ** unbalanced. But odds are that we will be inserting new entries
  52108. ** at the end soon afterwards so the nearly empty page will quickly
  52109. ** fill up. On average.
  52110. **
  52111. ** pPage is the leaf page which is the right-most page in the tree.
  52112. ** pParent is its parent. pPage must have a single overflow entry
  52113. ** which is also the right-most entry on the page.
  52114. **
  52115. ** The pSpace buffer is used to store a temporary copy of the divider
  52116. ** cell that will be inserted into pParent. Such a cell consists of a 4
  52117. ** byte page number followed by a variable length integer. In other
  52118. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  52119. ** least 13 bytes in size.
  52120. */
  52121. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  52122. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  52123. MemPage *pNew; /* Newly allocated page */
  52124. int rc; /* Return Code */
  52125. Pgno pgnoNew; /* Page number of pNew */
  52126. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52127. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  52128. assert( pPage->nOverflow==1 );
  52129. /* This error condition is now caught prior to reaching this function */
  52130. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
  52131. /* Allocate a new page. This page will become the right-sibling of
  52132. ** pPage. Make the parent page writable, so that the new divider cell
  52133. ** may be inserted. If both these operations are successful, proceed.
  52134. */
  52135. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  52136. if( rc==SQLITE_OK ){
  52137. u8 *pOut = &pSpace[4];
  52138. u8 *pCell = pPage->apOvfl[0];
  52139. u16 szCell = cellSizePtr(pPage, pCell);
  52140. u8 *pStop;
  52141. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  52142. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  52143. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  52144. assemblePage(pNew, 1, &pCell, &szCell);
  52145. /* If this is an auto-vacuum database, update the pointer map
  52146. ** with entries for the new page, and any pointer from the
  52147. ** cell on the page to an overflow page. If either of these
  52148. ** operations fails, the return code is set, but the contents
  52149. ** of the parent page are still manipulated by thh code below.
  52150. ** That is Ok, at this point the parent page is guaranteed to
  52151. ** be marked as dirty. Returning an error code will cause a
  52152. ** rollback, undoing any changes made to the parent page.
  52153. */
  52154. if( ISAUTOVACUUM ){
  52155. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  52156. if( szCell>pNew->minLocal ){
  52157. ptrmapPutOvflPtr(pNew, pCell, &rc);
  52158. }
  52159. }
  52160. /* Create a divider cell to insert into pParent. The divider cell
  52161. ** consists of a 4-byte page number (the page number of pPage) and
  52162. ** a variable length key value (which must be the same value as the
  52163. ** largest key on pPage).
  52164. **
  52165. ** To find the largest key value on pPage, first find the right-most
  52166. ** cell on pPage. The first two fields of this cell are the
  52167. ** record-length (a variable length integer at most 32-bits in size)
  52168. ** and the key value (a variable length integer, may have any value).
  52169. ** The first of the while(...) loops below skips over the record-length
  52170. ** field. The second while(...) loop copies the key value from the
  52171. ** cell on pPage into the pSpace buffer.
  52172. */
  52173. pCell = findCell(pPage, pPage->nCell-1);
  52174. pStop = &pCell[9];
  52175. while( (*(pCell++)&0x80) && pCell<pStop );
  52176. pStop = &pCell[9];
  52177. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  52178. /* Insert the new divider cell into pParent. */
  52179. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  52180. 0, pPage->pgno, &rc);
  52181. /* Set the right-child pointer of pParent to point to the new page. */
  52182. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  52183. /* Release the reference to the new page. */
  52184. releasePage(pNew);
  52185. }
  52186. return rc;
  52187. }
  52188. #endif /* SQLITE_OMIT_QUICKBALANCE */
  52189. #if 0
  52190. /*
  52191. ** This function does not contribute anything to the operation of SQLite.
  52192. ** it is sometimes activated temporarily while debugging code responsible
  52193. ** for setting pointer-map entries.
  52194. */
  52195. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  52196. int i, j;
  52197. for(i=0; i<nPage; i++){
  52198. Pgno n;
  52199. u8 e;
  52200. MemPage *pPage = apPage[i];
  52201. BtShared *pBt = pPage->pBt;
  52202. assert( pPage->isInit );
  52203. for(j=0; j<pPage->nCell; j++){
  52204. CellInfo info;
  52205. u8 *z;
  52206. z = findCell(pPage, j);
  52207. btreeParseCellPtr(pPage, z, &info);
  52208. if( info.iOverflow ){
  52209. Pgno ovfl = get4byte(&z[info.iOverflow]);
  52210. ptrmapGet(pBt, ovfl, &e, &n);
  52211. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  52212. }
  52213. if( !pPage->leaf ){
  52214. Pgno child = get4byte(z);
  52215. ptrmapGet(pBt, child, &e, &n);
  52216. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  52217. }
  52218. }
  52219. if( !pPage->leaf ){
  52220. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  52221. ptrmapGet(pBt, child, &e, &n);
  52222. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  52223. }
  52224. }
  52225. return 1;
  52226. }
  52227. #endif
  52228. /*
  52229. ** This function is used to copy the contents of the b-tree node stored
  52230. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  52231. ** the pointer-map entries for each child page are updated so that the
  52232. ** parent page stored in the pointer map is page pTo. If pFrom contained
  52233. ** any cells with overflow page pointers, then the corresponding pointer
  52234. ** map entries are also updated so that the parent page is page pTo.
  52235. **
  52236. ** If pFrom is currently carrying any overflow cells (entries in the
  52237. ** MemPage.apOvfl[] array), they are not copied to pTo.
  52238. **
  52239. ** Before returning, page pTo is reinitialized using btreeInitPage().
  52240. **
  52241. ** The performance of this function is not critical. It is only used by
  52242. ** the balance_shallower() and balance_deeper() procedures, neither of
  52243. ** which are called often under normal circumstances.
  52244. */
  52245. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  52246. if( (*pRC)==SQLITE_OK ){
  52247. BtShared * const pBt = pFrom->pBt;
  52248. u8 * const aFrom = pFrom->aData;
  52249. u8 * const aTo = pTo->aData;
  52250. int const iFromHdr = pFrom->hdrOffset;
  52251. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  52252. int rc;
  52253. int iData;
  52254. assert( pFrom->isInit );
  52255. assert( pFrom->nFree>=iToHdr );
  52256. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  52257. /* Copy the b-tree node content from page pFrom to page pTo. */
  52258. iData = get2byte(&aFrom[iFromHdr+5]);
  52259. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  52260. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  52261. /* Reinitialize page pTo so that the contents of the MemPage structure
  52262. ** match the new data. The initialization of pTo can actually fail under
  52263. ** fairly obscure circumstances, even though it is a copy of initialized
  52264. ** page pFrom.
  52265. */
  52266. pTo->isInit = 0;
  52267. rc = btreeInitPage(pTo);
  52268. if( rc!=SQLITE_OK ){
  52269. *pRC = rc;
  52270. return;
  52271. }
  52272. /* If this is an auto-vacuum database, update the pointer-map entries
  52273. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  52274. */
  52275. if( ISAUTOVACUUM ){
  52276. *pRC = setChildPtrmaps(pTo);
  52277. }
  52278. }
  52279. }
  52280. /*
  52281. ** This routine redistributes cells on the iParentIdx'th child of pParent
  52282. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  52283. ** same amount of free space. Usually a single sibling on either side of the
  52284. ** page are used in the balancing, though both siblings might come from one
  52285. ** side if the page is the first or last child of its parent. If the page
  52286. ** has fewer than 2 siblings (something which can only happen if the page
  52287. ** is a root page or a child of a root page) then all available siblings
  52288. ** participate in the balancing.
  52289. **
  52290. ** The number of siblings of the page might be increased or decreased by
  52291. ** one or two in an effort to keep pages nearly full but not over full.
  52292. **
  52293. ** Note that when this routine is called, some of the cells on the page
  52294. ** might not actually be stored in MemPage.aData[]. This can happen
  52295. ** if the page is overfull. This routine ensures that all cells allocated
  52296. ** to the page and its siblings fit into MemPage.aData[] before returning.
  52297. **
  52298. ** In the course of balancing the page and its siblings, cells may be
  52299. ** inserted into or removed from the parent page (pParent). Doing so
  52300. ** may cause the parent page to become overfull or underfull. If this
  52301. ** happens, it is the responsibility of the caller to invoke the correct
  52302. ** balancing routine to fix this problem (see the balance() routine).
  52303. **
  52304. ** If this routine fails for any reason, it might leave the database
  52305. ** in a corrupted state. So if this routine fails, the database should
  52306. ** be rolled back.
  52307. **
  52308. ** The third argument to this function, aOvflSpace, is a pointer to a
  52309. ** buffer big enough to hold one page. If while inserting cells into the parent
  52310. ** page (pParent) the parent page becomes overfull, this buffer is
  52311. ** used to store the parent's overflow cells. Because this function inserts
  52312. ** a maximum of four divider cells into the parent page, and the maximum
  52313. ** size of a cell stored within an internal node is always less than 1/4
  52314. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  52315. ** enough for all overflow cells.
  52316. **
  52317. ** If aOvflSpace is set to a null pointer, this function returns
  52318. ** SQLITE_NOMEM.
  52319. */
  52320. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  52321. #pragma optimize("", off)
  52322. #endif
  52323. static int balance_nonroot(
  52324. MemPage *pParent, /* Parent page of siblings being balanced */
  52325. int iParentIdx, /* Index of "the page" in pParent */
  52326. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  52327. int isRoot, /* True if pParent is a root-page */
  52328. int bBulk /* True if this call is part of a bulk load */
  52329. ){
  52330. BtShared *pBt; /* The whole database */
  52331. int nCell = 0; /* Number of cells in apCell[] */
  52332. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  52333. int nNew = 0; /* Number of pages in apNew[] */
  52334. int nOld; /* Number of pages in apOld[] */
  52335. int i, j, k; /* Loop counters */
  52336. int nxDiv; /* Next divider slot in pParent->aCell[] */
  52337. int rc = SQLITE_OK; /* The return code */
  52338. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  52339. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  52340. int usableSpace; /* Bytes in pPage beyond the header */
  52341. int pageFlags; /* Value of pPage->aData[0] */
  52342. int subtotal; /* Subtotal of bytes in cells on one page */
  52343. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  52344. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  52345. int szScratch; /* Size of scratch memory requested */
  52346. MemPage *apOld[NB]; /* pPage and up to two siblings */
  52347. MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
  52348. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  52349. u8 *pRight; /* Location in parent of right-sibling pointer */
  52350. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  52351. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  52352. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  52353. u8 **apCell = 0; /* All cells begin balanced */
  52354. u16 *szCell; /* Local size of all cells in apCell[] */
  52355. u8 *aSpace1; /* Space for copies of dividers cells */
  52356. Pgno pgno; /* Temp var to store a page number in */
  52357. pBt = pParent->pBt;
  52358. assert( sqlite3_mutex_held(pBt->mutex) );
  52359. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  52360. #if 0
  52361. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  52362. #endif
  52363. /* At this point pParent may have at most one overflow cell. And if
  52364. ** this overflow cell is present, it must be the cell with
  52365. ** index iParentIdx. This scenario comes about when this function
  52366. ** is called (indirectly) from sqlite3BtreeDelete().
  52367. */
  52368. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  52369. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  52370. if( !aOvflSpace ){
  52371. return SQLITE_NOMEM;
  52372. }
  52373. /* Find the sibling pages to balance. Also locate the cells in pParent
  52374. ** that divide the siblings. An attempt is made to find NN siblings on
  52375. ** either side of pPage. More siblings are taken from one side, however,
  52376. ** if there are fewer than NN siblings on the other side. If pParent
  52377. ** has NB or fewer children then all children of pParent are taken.
  52378. **
  52379. ** This loop also drops the divider cells from the parent page. This
  52380. ** way, the remainder of the function does not have to deal with any
  52381. ** overflow cells in the parent page, since if any existed they will
  52382. ** have already been removed.
  52383. */
  52384. i = pParent->nOverflow + pParent->nCell;
  52385. if( i<2 ){
  52386. nxDiv = 0;
  52387. }else{
  52388. assert( bBulk==0 || bBulk==1 );
  52389. if( iParentIdx==0 ){
  52390. nxDiv = 0;
  52391. }else if( iParentIdx==i ){
  52392. nxDiv = i-2+bBulk;
  52393. }else{
  52394. assert( bBulk==0 );
  52395. nxDiv = iParentIdx-1;
  52396. }
  52397. i = 2-bBulk;
  52398. }
  52399. nOld = i+1;
  52400. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  52401. pRight = &pParent->aData[pParent->hdrOffset+8];
  52402. }else{
  52403. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  52404. }
  52405. pgno = get4byte(pRight);
  52406. while( 1 ){
  52407. rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
  52408. if( rc ){
  52409. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  52410. goto balance_cleanup;
  52411. }
  52412. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  52413. if( (i--)==0 ) break;
  52414. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  52415. apDiv[i] = pParent->apOvfl[0];
  52416. pgno = get4byte(apDiv[i]);
  52417. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  52418. pParent->nOverflow = 0;
  52419. }else{
  52420. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  52421. pgno = get4byte(apDiv[i]);
  52422. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  52423. /* Drop the cell from the parent page. apDiv[i] still points to
  52424. ** the cell within the parent, even though it has been dropped.
  52425. ** This is safe because dropping a cell only overwrites the first
  52426. ** four bytes of it, and this function does not need the first
  52427. ** four bytes of the divider cell. So the pointer is safe to use
  52428. ** later on.
  52429. **
  52430. ** But not if we are in secure-delete mode. In secure-delete mode,
  52431. ** the dropCell() routine will overwrite the entire cell with zeroes.
  52432. ** In this case, temporarily copy the cell into the aOvflSpace[]
  52433. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  52434. ** is allocated. */
  52435. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  52436. int iOff;
  52437. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  52438. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  52439. rc = SQLITE_CORRUPT_BKPT;
  52440. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  52441. goto balance_cleanup;
  52442. }else{
  52443. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  52444. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  52445. }
  52446. }
  52447. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  52448. }
  52449. }
  52450. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  52451. ** alignment */
  52452. nMaxCells = (nMaxCells + 3)&~3;
  52453. /*
  52454. ** Allocate space for memory structures
  52455. */
  52456. k = pBt->pageSize + ROUND8(sizeof(MemPage));
  52457. szScratch =
  52458. nMaxCells*sizeof(u8*) /* apCell */
  52459. + nMaxCells*sizeof(u16) /* szCell */
  52460. + pBt->pageSize /* aSpace1 */
  52461. + k*nOld; /* Page copies (apCopy) */
  52462. apCell = sqlite3ScratchMalloc( szScratch );
  52463. if( apCell==0 ){
  52464. rc = SQLITE_NOMEM;
  52465. goto balance_cleanup;
  52466. }
  52467. szCell = (u16*)&apCell[nMaxCells];
  52468. aSpace1 = (u8*)&szCell[nMaxCells];
  52469. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  52470. /*
  52471. ** Load pointers to all cells on sibling pages and the divider cells
  52472. ** into the local apCell[] array. Make copies of the divider cells
  52473. ** into space obtained from aSpace1[] and remove the divider cells
  52474. ** from pParent.
  52475. **
  52476. ** If the siblings are on leaf pages, then the child pointers of the
  52477. ** divider cells are stripped from the cells before they are copied
  52478. ** into aSpace1[]. In this way, all cells in apCell[] are without
  52479. ** child pointers. If siblings are not leaves, then all cell in
  52480. ** apCell[] include child pointers. Either way, all cells in apCell[]
  52481. ** are alike.
  52482. **
  52483. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  52484. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  52485. */
  52486. leafCorrection = apOld[0]->leaf*4;
  52487. leafData = apOld[0]->hasData;
  52488. for(i=0; i<nOld; i++){
  52489. int limit;
  52490. /* Before doing anything else, take a copy of the i'th original sibling
  52491. ** The rest of this function will use data from the copies rather
  52492. ** that the original pages since the original pages will be in the
  52493. ** process of being overwritten. */
  52494. MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
  52495. memcpy(pOld, apOld[i], sizeof(MemPage));
  52496. pOld->aData = (void*)&pOld[1];
  52497. memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
  52498. limit = pOld->nCell+pOld->nOverflow;
  52499. if( pOld->nOverflow>0 ){
  52500. for(j=0; j<limit; j++){
  52501. assert( nCell<nMaxCells );
  52502. apCell[nCell] = findOverflowCell(pOld, j);
  52503. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  52504. nCell++;
  52505. }
  52506. }else{
  52507. u8 *aData = pOld->aData;
  52508. u16 maskPage = pOld->maskPage;
  52509. u16 cellOffset = pOld->cellOffset;
  52510. for(j=0; j<limit; j++){
  52511. assert( nCell<nMaxCells );
  52512. apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
  52513. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  52514. nCell++;
  52515. }
  52516. }
  52517. if( i<nOld-1 && !leafData){
  52518. u16 sz = (u16)szNew[i];
  52519. u8 *pTemp;
  52520. assert( nCell<nMaxCells );
  52521. szCell[nCell] = sz;
  52522. pTemp = &aSpace1[iSpace1];
  52523. iSpace1 += sz;
  52524. assert( sz<=pBt->maxLocal+23 );
  52525. assert( iSpace1 <= (int)pBt->pageSize );
  52526. memcpy(pTemp, apDiv[i], sz);
  52527. apCell[nCell] = pTemp+leafCorrection;
  52528. assert( leafCorrection==0 || leafCorrection==4 );
  52529. szCell[nCell] = szCell[nCell] - leafCorrection;
  52530. if( !pOld->leaf ){
  52531. assert( leafCorrection==0 );
  52532. assert( pOld->hdrOffset==0 );
  52533. /* The right pointer of the child page pOld becomes the left
  52534. ** pointer of the divider cell */
  52535. memcpy(apCell[nCell], &pOld->aData[8], 4);
  52536. }else{
  52537. assert( leafCorrection==4 );
  52538. if( szCell[nCell]<4 ){
  52539. /* Do not allow any cells smaller than 4 bytes. */
  52540. szCell[nCell] = 4;
  52541. }
  52542. }
  52543. nCell++;
  52544. }
  52545. }
  52546. /*
  52547. ** Figure out the number of pages needed to hold all nCell cells.
  52548. ** Store this number in "k". Also compute szNew[] which is the total
  52549. ** size of all cells on the i-th page and cntNew[] which is the index
  52550. ** in apCell[] of the cell that divides page i from page i+1.
  52551. ** cntNew[k] should equal nCell.
  52552. **
  52553. ** Values computed by this block:
  52554. **
  52555. ** k: The total number of sibling pages
  52556. ** szNew[i]: Spaced used on the i-th sibling page.
  52557. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  52558. ** the right of the i-th sibling page.
  52559. ** usableSpace: Number of bytes of space available on each sibling.
  52560. **
  52561. */
  52562. usableSpace = pBt->usableSize - 12 + leafCorrection;
  52563. for(subtotal=k=i=0; i<nCell; i++){
  52564. assert( i<nMaxCells );
  52565. subtotal += szCell[i] + 2;
  52566. if( subtotal > usableSpace ){
  52567. szNew[k] = subtotal - szCell[i];
  52568. cntNew[k] = i;
  52569. if( leafData ){ i--; }
  52570. subtotal = 0;
  52571. k++;
  52572. if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  52573. }
  52574. }
  52575. szNew[k] = subtotal;
  52576. cntNew[k] = nCell;
  52577. k++;
  52578. /*
  52579. ** The packing computed by the previous block is biased toward the siblings
  52580. ** on the left side. The left siblings are always nearly full, while the
  52581. ** right-most sibling might be nearly empty. This block of code attempts
  52582. ** to adjust the packing of siblings to get a better balance.
  52583. **
  52584. ** This adjustment is more than an optimization. The packing above might
  52585. ** be so out of balance as to be illegal. For example, the right-most
  52586. ** sibling might be completely empty. This adjustment is not optional.
  52587. */
  52588. for(i=k-1; i>0; i--){
  52589. int szRight = szNew[i]; /* Size of sibling on the right */
  52590. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  52591. int r; /* Index of right-most cell in left sibling */
  52592. int d; /* Index of first cell to the left of right sibling */
  52593. r = cntNew[i-1] - 1;
  52594. d = r + 1 - leafData;
  52595. assert( d<nMaxCells );
  52596. assert( r<nMaxCells );
  52597. while( szRight==0
  52598. || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
  52599. ){
  52600. szRight += szCell[d] + 2;
  52601. szLeft -= szCell[r] + 2;
  52602. cntNew[i-1]--;
  52603. r = cntNew[i-1] - 1;
  52604. d = r + 1 - leafData;
  52605. }
  52606. szNew[i] = szRight;
  52607. szNew[i-1] = szLeft;
  52608. }
  52609. /* Either we found one or more cells (cntnew[0])>0) or pPage is
  52610. ** a virtual root page. A virtual root page is when the real root
  52611. ** page is page 1 and we are the only child of that page.
  52612. **
  52613. ** UPDATE: The assert() below is not necessarily true if the database
  52614. ** file is corrupt. The corruption will be detected and reported later
  52615. ** in this procedure so there is no need to act upon it now.
  52616. */
  52617. #if 0
  52618. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  52619. #endif
  52620. TRACE(("BALANCE: old: %d %d %d ",
  52621. apOld[0]->pgno,
  52622. nOld>=2 ? apOld[1]->pgno : 0,
  52623. nOld>=3 ? apOld[2]->pgno : 0
  52624. ));
  52625. /*
  52626. ** Allocate k new pages. Reuse old pages where possible.
  52627. */
  52628. if( apOld[0]->pgno<=1 ){
  52629. rc = SQLITE_CORRUPT_BKPT;
  52630. goto balance_cleanup;
  52631. }
  52632. pageFlags = apOld[0]->aData[0];
  52633. for(i=0; i<k; i++){
  52634. MemPage *pNew;
  52635. if( i<nOld ){
  52636. pNew = apNew[i] = apOld[i];
  52637. apOld[i] = 0;
  52638. rc = sqlite3PagerWrite(pNew->pDbPage);
  52639. nNew++;
  52640. if( rc ) goto balance_cleanup;
  52641. }else{
  52642. assert( i>0 );
  52643. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  52644. if( rc ) goto balance_cleanup;
  52645. apNew[i] = pNew;
  52646. nNew++;
  52647. /* Set the pointer-map entry for the new sibling page. */
  52648. if( ISAUTOVACUUM ){
  52649. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  52650. if( rc!=SQLITE_OK ){
  52651. goto balance_cleanup;
  52652. }
  52653. }
  52654. }
  52655. }
  52656. /* Free any old pages that were not reused as new pages.
  52657. */
  52658. while( i<nOld ){
  52659. freePage(apOld[i], &rc);
  52660. if( rc ) goto balance_cleanup;
  52661. releasePage(apOld[i]);
  52662. apOld[i] = 0;
  52663. i++;
  52664. }
  52665. /*
  52666. ** Put the new pages in accending order. This helps to
  52667. ** keep entries in the disk file in order so that a scan
  52668. ** of the table is a linear scan through the file. That
  52669. ** in turn helps the operating system to deliver pages
  52670. ** from the disk more rapidly.
  52671. **
  52672. ** An O(n^2) insertion sort algorithm is used, but since
  52673. ** n is never more than NB (a small constant), that should
  52674. ** not be a problem.
  52675. **
  52676. ** When NB==3, this one optimization makes the database
  52677. ** about 25% faster for large insertions and deletions.
  52678. */
  52679. for(i=0; i<k-1; i++){
  52680. int minV = apNew[i]->pgno;
  52681. int minI = i;
  52682. for(j=i+1; j<k; j++){
  52683. if( apNew[j]->pgno<(unsigned)minV ){
  52684. minI = j;
  52685. minV = apNew[j]->pgno;
  52686. }
  52687. }
  52688. if( minI>i ){
  52689. MemPage *pT;
  52690. pT = apNew[i];
  52691. apNew[i] = apNew[minI];
  52692. apNew[minI] = pT;
  52693. }
  52694. }
  52695. TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
  52696. apNew[0]->pgno, szNew[0],
  52697. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  52698. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  52699. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  52700. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
  52701. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  52702. put4byte(pRight, apNew[nNew-1]->pgno);
  52703. /*
  52704. ** Evenly distribute the data in apCell[] across the new pages.
  52705. ** Insert divider cells into pParent as necessary.
  52706. */
  52707. j = 0;
  52708. for(i=0; i<nNew; i++){
  52709. /* Assemble the new sibling page. */
  52710. MemPage *pNew = apNew[i];
  52711. assert( j<nMaxCells );
  52712. zeroPage(pNew, pageFlags);
  52713. assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
  52714. assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
  52715. assert( pNew->nOverflow==0 );
  52716. j = cntNew[i];
  52717. /* If the sibling page assembled above was not the right-most sibling,
  52718. ** insert a divider cell into the parent page.
  52719. */
  52720. assert( i<nNew-1 || j==nCell );
  52721. if( j<nCell ){
  52722. u8 *pCell;
  52723. u8 *pTemp;
  52724. int sz;
  52725. assert( j<nMaxCells );
  52726. pCell = apCell[j];
  52727. sz = szCell[j] + leafCorrection;
  52728. pTemp = &aOvflSpace[iOvflSpace];
  52729. if( !pNew->leaf ){
  52730. memcpy(&pNew->aData[8], pCell, 4);
  52731. }else if( leafData ){
  52732. /* If the tree is a leaf-data tree, and the siblings are leaves,
  52733. ** then there is no divider cell in apCell[]. Instead, the divider
  52734. ** cell consists of the integer key for the right-most cell of
  52735. ** the sibling-page assembled above only.
  52736. */
  52737. CellInfo info;
  52738. j--;
  52739. btreeParseCellPtr(pNew, apCell[j], &info);
  52740. pCell = pTemp;
  52741. sz = 4 + putVarint(&pCell[4], info.nKey);
  52742. pTemp = 0;
  52743. }else{
  52744. pCell -= 4;
  52745. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  52746. ** previously stored on a leaf node, and its reported size was 4
  52747. ** bytes, then it may actually be smaller than this
  52748. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  52749. ** any cell). But it is important to pass the correct size to
  52750. ** insertCell(), so reparse the cell now.
  52751. **
  52752. ** Note that this can never happen in an SQLite data file, as all
  52753. ** cells are at least 4 bytes. It only happens in b-trees used
  52754. ** to evaluate "IN (SELECT ...)" and similar clauses.
  52755. */
  52756. if( szCell[j]==4 ){
  52757. assert(leafCorrection==4);
  52758. sz = cellSizePtr(pParent, pCell);
  52759. }
  52760. }
  52761. iOvflSpace += sz;
  52762. assert( sz<=pBt->maxLocal+23 );
  52763. assert( iOvflSpace <= (int)pBt->pageSize );
  52764. insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
  52765. if( rc!=SQLITE_OK ) goto balance_cleanup;
  52766. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  52767. j++;
  52768. nxDiv++;
  52769. }
  52770. }
  52771. assert( j==nCell );
  52772. assert( nOld>0 );
  52773. assert( nNew>0 );
  52774. if( (pageFlags & PTF_LEAF)==0 ){
  52775. u8 *zChild = &apCopy[nOld-1]->aData[8];
  52776. memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  52777. }
  52778. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  52779. /* The root page of the b-tree now contains no cells. The only sibling
  52780. ** page is the right-child of the parent. Copy the contents of the
  52781. ** child page into the parent, decreasing the overall height of the
  52782. ** b-tree structure by one. This is described as the "balance-shallower"
  52783. ** sub-algorithm in some documentation.
  52784. **
  52785. ** If this is an auto-vacuum database, the call to copyNodeContent()
  52786. ** sets all pointer-map entries corresponding to database image pages
  52787. ** for which the pointer is stored within the content being copied.
  52788. **
  52789. ** The second assert below verifies that the child page is defragmented
  52790. ** (it must be, as it was just reconstructed using assemblePage()). This
  52791. ** is important if the parent page happens to be page 1 of the database
  52792. ** image. */
  52793. assert( nNew==1 );
  52794. assert( apNew[0]->nFree ==
  52795. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  52796. );
  52797. copyNodeContent(apNew[0], pParent, &rc);
  52798. freePage(apNew[0], &rc);
  52799. }else if( ISAUTOVACUUM ){
  52800. /* Fix the pointer-map entries for all the cells that were shifted around.
  52801. ** There are several different types of pointer-map entries that need to
  52802. ** be dealt with by this routine. Some of these have been set already, but
  52803. ** many have not. The following is a summary:
  52804. **
  52805. ** 1) The entries associated with new sibling pages that were not
  52806. ** siblings when this function was called. These have already
  52807. ** been set. We don't need to worry about old siblings that were
  52808. ** moved to the free-list - the freePage() code has taken care
  52809. ** of those.
  52810. **
  52811. ** 2) The pointer-map entries associated with the first overflow
  52812. ** page in any overflow chains used by new divider cells. These
  52813. ** have also already been taken care of by the insertCell() code.
  52814. **
  52815. ** 3) If the sibling pages are not leaves, then the child pages of
  52816. ** cells stored on the sibling pages may need to be updated.
  52817. **
  52818. ** 4) If the sibling pages are not internal intkey nodes, then any
  52819. ** overflow pages used by these cells may need to be updated
  52820. ** (internal intkey nodes never contain pointers to overflow pages).
  52821. **
  52822. ** 5) If the sibling pages are not leaves, then the pointer-map
  52823. ** entries for the right-child pages of each sibling may need
  52824. ** to be updated.
  52825. **
  52826. ** Cases 1 and 2 are dealt with above by other code. The next
  52827. ** block deals with cases 3 and 4 and the one after that, case 5. Since
  52828. ** setting a pointer map entry is a relatively expensive operation, this
  52829. ** code only sets pointer map entries for child or overflow pages that have
  52830. ** actually moved between pages. */
  52831. MemPage *pNew = apNew[0];
  52832. MemPage *pOld = apCopy[0];
  52833. int nOverflow = pOld->nOverflow;
  52834. int iNextOld = pOld->nCell + nOverflow;
  52835. int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
  52836. j = 0; /* Current 'old' sibling page */
  52837. k = 0; /* Current 'new' sibling page */
  52838. for(i=0; i<nCell; i++){
  52839. int isDivider = 0;
  52840. while( i==iNextOld ){
  52841. /* Cell i is the cell immediately following the last cell on old
  52842. ** sibling page j. If the siblings are not leaf pages of an
  52843. ** intkey b-tree, then cell i was a divider cell. */
  52844. assert( j+1 < ArraySize(apCopy) );
  52845. assert( j+1 < nOld );
  52846. pOld = apCopy[++j];
  52847. iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
  52848. if( pOld->nOverflow ){
  52849. nOverflow = pOld->nOverflow;
  52850. iOverflow = i + !leafData + pOld->aiOvfl[0];
  52851. }
  52852. isDivider = !leafData;
  52853. }
  52854. assert(nOverflow>0 || iOverflow<i );
  52855. assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
  52856. assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
  52857. if( i==iOverflow ){
  52858. isDivider = 1;
  52859. if( (--nOverflow)>0 ){
  52860. iOverflow++;
  52861. }
  52862. }
  52863. if( i==cntNew[k] ){
  52864. /* Cell i is the cell immediately following the last cell on new
  52865. ** sibling page k. If the siblings are not leaf pages of an
  52866. ** intkey b-tree, then cell i is a divider cell. */
  52867. pNew = apNew[++k];
  52868. if( !leafData ) continue;
  52869. }
  52870. assert( j<nOld );
  52871. assert( k<nNew );
  52872. /* If the cell was originally divider cell (and is not now) or
  52873. ** an overflow cell, or if the cell was located on a different sibling
  52874. ** page before the balancing, then the pointer map entries associated
  52875. ** with any child or overflow pages need to be updated. */
  52876. if( isDivider || pOld->pgno!=pNew->pgno ){
  52877. if( !leafCorrection ){
  52878. ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
  52879. }
  52880. if( szCell[i]>pNew->minLocal ){
  52881. ptrmapPutOvflPtr(pNew, apCell[i], &rc);
  52882. }
  52883. }
  52884. }
  52885. if( !leafCorrection ){
  52886. for(i=0; i<nNew; i++){
  52887. u32 key = get4byte(&apNew[i]->aData[8]);
  52888. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  52889. }
  52890. }
  52891. #if 0
  52892. /* The ptrmapCheckPages() contains assert() statements that verify that
  52893. ** all pointer map pages are set correctly. This is helpful while
  52894. ** debugging. This is usually disabled because a corrupt database may
  52895. ** cause an assert() statement to fail. */
  52896. ptrmapCheckPages(apNew, nNew);
  52897. ptrmapCheckPages(&pParent, 1);
  52898. #endif
  52899. }
  52900. assert( pParent->isInit );
  52901. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  52902. nOld, nNew, nCell));
  52903. /*
  52904. ** Cleanup before returning.
  52905. */
  52906. balance_cleanup:
  52907. sqlite3ScratchFree(apCell);
  52908. for(i=0; i<nOld; i++){
  52909. releasePage(apOld[i]);
  52910. }
  52911. for(i=0; i<nNew; i++){
  52912. releasePage(apNew[i]);
  52913. }
  52914. return rc;
  52915. }
  52916. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  52917. #pragma optimize("", on)
  52918. #endif
  52919. /*
  52920. ** This function is called when the root page of a b-tree structure is
  52921. ** overfull (has one or more overflow pages).
  52922. **
  52923. ** A new child page is allocated and the contents of the current root
  52924. ** page, including overflow cells, are copied into the child. The root
  52925. ** page is then overwritten to make it an empty page with the right-child
  52926. ** pointer pointing to the new page.
  52927. **
  52928. ** Before returning, all pointer-map entries corresponding to pages
  52929. ** that the new child-page now contains pointers to are updated. The
  52930. ** entry corresponding to the new right-child pointer of the root
  52931. ** page is also updated.
  52932. **
  52933. ** If successful, *ppChild is set to contain a reference to the child
  52934. ** page and SQLITE_OK is returned. In this case the caller is required
  52935. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  52936. ** an error code is returned and *ppChild is set to 0.
  52937. */
  52938. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  52939. int rc; /* Return value from subprocedures */
  52940. MemPage *pChild = 0; /* Pointer to a new child page */
  52941. Pgno pgnoChild = 0; /* Page number of the new child page */
  52942. BtShared *pBt = pRoot->pBt; /* The BTree */
  52943. assert( pRoot->nOverflow>0 );
  52944. assert( sqlite3_mutex_held(pBt->mutex) );
  52945. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  52946. ** page that will become the new right-child of pPage. Copy the contents
  52947. ** of the node stored on pRoot into the new child page.
  52948. */
  52949. rc = sqlite3PagerWrite(pRoot->pDbPage);
  52950. if( rc==SQLITE_OK ){
  52951. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  52952. copyNodeContent(pRoot, pChild, &rc);
  52953. if( ISAUTOVACUUM ){
  52954. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  52955. }
  52956. }
  52957. if( rc ){
  52958. *ppChild = 0;
  52959. releasePage(pChild);
  52960. return rc;
  52961. }
  52962. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  52963. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  52964. assert( pChild->nCell==pRoot->nCell );
  52965. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  52966. /* Copy the overflow cells from pRoot to pChild */
  52967. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  52968. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  52969. memcpy(pChild->apOvfl, pRoot->apOvfl,
  52970. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  52971. pChild->nOverflow = pRoot->nOverflow;
  52972. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  52973. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  52974. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  52975. *ppChild = pChild;
  52976. return SQLITE_OK;
  52977. }
  52978. /*
  52979. ** The page that pCur currently points to has just been modified in
  52980. ** some way. This function figures out if this modification means the
  52981. ** tree needs to be balanced, and if so calls the appropriate balancing
  52982. ** routine. Balancing routines are:
  52983. **
  52984. ** balance_quick()
  52985. ** balance_deeper()
  52986. ** balance_nonroot()
  52987. */
  52988. static int balance(BtCursor *pCur){
  52989. int rc = SQLITE_OK;
  52990. const int nMin = pCur->pBt->usableSize * 2 / 3;
  52991. u8 aBalanceQuickSpace[13];
  52992. u8 *pFree = 0;
  52993. TESTONLY( int balance_quick_called = 0 );
  52994. TESTONLY( int balance_deeper_called = 0 );
  52995. do {
  52996. int iPage = pCur->iPage;
  52997. MemPage *pPage = pCur->apPage[iPage];
  52998. if( iPage==0 ){
  52999. if( pPage->nOverflow ){
  53000. /* The root page of the b-tree is overfull. In this case call the
  53001. ** balance_deeper() function to create a new child for the root-page
  53002. ** and copy the current contents of the root-page to it. The
  53003. ** next iteration of the do-loop will balance the child page.
  53004. */
  53005. assert( (balance_deeper_called++)==0 );
  53006. rc = balance_deeper(pPage, &pCur->apPage[1]);
  53007. if( rc==SQLITE_OK ){
  53008. pCur->iPage = 1;
  53009. pCur->aiIdx[0] = 0;
  53010. pCur->aiIdx[1] = 0;
  53011. assert( pCur->apPage[1]->nOverflow );
  53012. }
  53013. }else{
  53014. break;
  53015. }
  53016. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  53017. break;
  53018. }else{
  53019. MemPage * const pParent = pCur->apPage[iPage-1];
  53020. int const iIdx = pCur->aiIdx[iPage-1];
  53021. rc = sqlite3PagerWrite(pParent->pDbPage);
  53022. if( rc==SQLITE_OK ){
  53023. #ifndef SQLITE_OMIT_QUICKBALANCE
  53024. if( pPage->hasData
  53025. && pPage->nOverflow==1
  53026. && pPage->aiOvfl[0]==pPage->nCell
  53027. && pParent->pgno!=1
  53028. && pParent->nCell==iIdx
  53029. ){
  53030. /* Call balance_quick() to create a new sibling of pPage on which
  53031. ** to store the overflow cell. balance_quick() inserts a new cell
  53032. ** into pParent, which may cause pParent overflow. If this
  53033. ** happens, the next interation of the do-loop will balance pParent
  53034. ** use either balance_nonroot() or balance_deeper(). Until this
  53035. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  53036. ** buffer.
  53037. **
  53038. ** The purpose of the following assert() is to check that only a
  53039. ** single call to balance_quick() is made for each call to this
  53040. ** function. If this were not verified, a subtle bug involving reuse
  53041. ** of the aBalanceQuickSpace[] might sneak in.
  53042. */
  53043. assert( (balance_quick_called++)==0 );
  53044. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  53045. }else
  53046. #endif
  53047. {
  53048. /* In this case, call balance_nonroot() to redistribute cells
  53049. ** between pPage and up to 2 of its sibling pages. This involves
  53050. ** modifying the contents of pParent, which may cause pParent to
  53051. ** become overfull or underfull. The next iteration of the do-loop
  53052. ** will balance the parent page to correct this.
  53053. **
  53054. ** If the parent page becomes overfull, the overflow cell or cells
  53055. ** are stored in the pSpace buffer allocated immediately below.
  53056. ** A subsequent iteration of the do-loop will deal with this by
  53057. ** calling balance_nonroot() (balance_deeper() may be called first,
  53058. ** but it doesn't deal with overflow cells - just moves them to a
  53059. ** different page). Once this subsequent call to balance_nonroot()
  53060. ** has completed, it is safe to release the pSpace buffer used by
  53061. ** the previous call, as the overflow cell data will have been
  53062. ** copied either into the body of a database page or into the new
  53063. ** pSpace buffer passed to the latter call to balance_nonroot().
  53064. */
  53065. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  53066. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
  53067. if( pFree ){
  53068. /* If pFree is not NULL, it points to the pSpace buffer used
  53069. ** by a previous call to balance_nonroot(). Its contents are
  53070. ** now stored either on real database pages or within the
  53071. ** new pSpace buffer, so it may be safely freed here. */
  53072. sqlite3PageFree(pFree);
  53073. }
  53074. /* The pSpace buffer will be freed after the next call to
  53075. ** balance_nonroot(), or just before this function returns, whichever
  53076. ** comes first. */
  53077. pFree = pSpace;
  53078. }
  53079. }
  53080. pPage->nOverflow = 0;
  53081. /* The next iteration of the do-loop balances the parent page. */
  53082. releasePage(pPage);
  53083. pCur->iPage--;
  53084. }
  53085. }while( rc==SQLITE_OK );
  53086. if( pFree ){
  53087. sqlite3PageFree(pFree);
  53088. }
  53089. return rc;
  53090. }
  53091. /*
  53092. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  53093. ** and the data is given by (pData,nData). The cursor is used only to
  53094. ** define what table the record should be inserted into. The cursor
  53095. ** is left pointing at a random location.
  53096. **
  53097. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  53098. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  53099. **
  53100. ** If the seekResult parameter is non-zero, then a successful call to
  53101. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  53102. ** been performed. seekResult is the search result returned (a negative
  53103. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  53104. ** a positive value if pCur points at an etry that is larger than
  53105. ** (pKey, nKey)).
  53106. **
  53107. ** If the seekResult parameter is non-zero, then the caller guarantees that
  53108. ** cursor pCur is pointing at the existing copy of a row that is to be
  53109. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  53110. ** point to any entry or to no entry at all and so this function has to seek
  53111. ** the cursor before the new key can be inserted.
  53112. */
  53113. SQLITE_PRIVATE int sqlite3BtreeInsert(
  53114. BtCursor *pCur, /* Insert data into the table of this cursor */
  53115. const void *pKey, i64 nKey, /* The key of the new record */
  53116. const void *pData, int nData, /* The data of the new record */
  53117. int nZero, /* Number of extra 0 bytes to append to data */
  53118. int appendBias, /* True if this is likely an append */
  53119. int seekResult /* Result of prior MovetoUnpacked() call */
  53120. ){
  53121. int rc;
  53122. int loc = seekResult; /* -1: before desired location +1: after */
  53123. int szNew = 0;
  53124. int idx;
  53125. MemPage *pPage;
  53126. Btree *p = pCur->pBtree;
  53127. BtShared *pBt = p->pBt;
  53128. unsigned char *oldCell;
  53129. unsigned char *newCell = 0;
  53130. if( pCur->eState==CURSOR_FAULT ){
  53131. assert( pCur->skipNext!=SQLITE_OK );
  53132. return pCur->skipNext;
  53133. }
  53134. assert( cursorHoldsMutex(pCur) );
  53135. assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
  53136. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  53137. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  53138. /* Assert that the caller has been consistent. If this cursor was opened
  53139. ** expecting an index b-tree, then the caller should be inserting blob
  53140. ** keys with no associated data. If the cursor was opened expecting an
  53141. ** intkey table, the caller should be inserting integer keys with a
  53142. ** blob of associated data. */
  53143. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  53144. /* Save the positions of any other cursors open on this table.
  53145. **
  53146. ** In some cases, the call to btreeMoveto() below is a no-op. For
  53147. ** example, when inserting data into a table with auto-generated integer
  53148. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  53149. ** integer key to use. It then calls this function to actually insert the
  53150. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  53151. ** that the cursor is already where it needs to be and returns without
  53152. ** doing any work. To avoid thwarting these optimizations, it is important
  53153. ** not to clear the cursor here.
  53154. */
  53155. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  53156. if( rc ) return rc;
  53157. /* If this is an insert into a table b-tree, invalidate any incrblob
  53158. ** cursors open on the row being replaced (assuming this is a replace
  53159. ** operation - if it is not, the following is a no-op). */
  53160. if( pCur->pKeyInfo==0 ){
  53161. invalidateIncrblobCursors(p, nKey, 0);
  53162. }
  53163. if( !loc ){
  53164. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  53165. if( rc ) return rc;
  53166. }
  53167. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  53168. pPage = pCur->apPage[pCur->iPage];
  53169. assert( pPage->intKey || nKey>=0 );
  53170. assert( pPage->leaf || !pPage->intKey );
  53171. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  53172. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  53173. loc==0 ? "overwrite" : "new entry"));
  53174. assert( pPage->isInit );
  53175. allocateTempSpace(pBt);
  53176. newCell = pBt->pTmpSpace;
  53177. if( newCell==0 ) return SQLITE_NOMEM;
  53178. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  53179. if( rc ) goto end_insert;
  53180. assert( szNew==cellSizePtr(pPage, newCell) );
  53181. assert( szNew <= MX_CELL_SIZE(pBt) );
  53182. idx = pCur->aiIdx[pCur->iPage];
  53183. if( loc==0 ){
  53184. u16 szOld;
  53185. assert( idx<pPage->nCell );
  53186. rc = sqlite3PagerWrite(pPage->pDbPage);
  53187. if( rc ){
  53188. goto end_insert;
  53189. }
  53190. oldCell = findCell(pPage, idx);
  53191. if( !pPage->leaf ){
  53192. memcpy(newCell, oldCell, 4);
  53193. }
  53194. szOld = cellSizePtr(pPage, oldCell);
  53195. rc = clearCell(pPage, oldCell);
  53196. dropCell(pPage, idx, szOld, &rc);
  53197. if( rc ) goto end_insert;
  53198. }else if( loc<0 && pPage->nCell>0 ){
  53199. assert( pPage->leaf );
  53200. idx = ++pCur->aiIdx[pCur->iPage];
  53201. }else{
  53202. assert( pPage->leaf );
  53203. }
  53204. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  53205. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  53206. /* If no error has occurred and pPage has an overflow cell, call balance()
  53207. ** to redistribute the cells within the tree. Since balance() may move
  53208. ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
  53209. ** variables.
  53210. **
  53211. ** Previous versions of SQLite called moveToRoot() to move the cursor
  53212. ** back to the root page as balance() used to invalidate the contents
  53213. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  53214. ** set the cursor state to "invalid". This makes common insert operations
  53215. ** slightly faster.
  53216. **
  53217. ** There is a subtle but important optimization here too. When inserting
  53218. ** multiple records into an intkey b-tree using a single cursor (as can
  53219. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  53220. ** is advantageous to leave the cursor pointing to the last entry in
  53221. ** the b-tree if possible. If the cursor is left pointing to the last
  53222. ** entry in the table, and the next row inserted has an integer key
  53223. ** larger than the largest existing key, it is possible to insert the
  53224. ** row without seeking the cursor. This can be a big performance boost.
  53225. */
  53226. pCur->info.nSize = 0;
  53227. pCur->validNKey = 0;
  53228. if( rc==SQLITE_OK && pPage->nOverflow ){
  53229. rc = balance(pCur);
  53230. /* Must make sure nOverflow is reset to zero even if the balance()
  53231. ** fails. Internal data structure corruption will result otherwise.
  53232. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  53233. ** from trying to save the current position of the cursor. */
  53234. pCur->apPage[pCur->iPage]->nOverflow = 0;
  53235. pCur->eState = CURSOR_INVALID;
  53236. }
  53237. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  53238. end_insert:
  53239. return rc;
  53240. }
  53241. /*
  53242. ** Delete the entry that the cursor is pointing to. The cursor
  53243. ** is left pointing at a arbitrary location.
  53244. */
  53245. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  53246. Btree *p = pCur->pBtree;
  53247. BtShared *pBt = p->pBt;
  53248. int rc; /* Return code */
  53249. MemPage *pPage; /* Page to delete cell from */
  53250. unsigned char *pCell; /* Pointer to cell to delete */
  53251. int iCellIdx; /* Index of cell to delete */
  53252. int iCellDepth; /* Depth of node containing pCell */
  53253. assert( cursorHoldsMutex(pCur) );
  53254. assert( pBt->inTransaction==TRANS_WRITE );
  53255. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  53256. assert( pCur->wrFlag );
  53257. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  53258. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  53259. if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
  53260. || NEVER(pCur->eState!=CURSOR_VALID)
  53261. ){
  53262. return SQLITE_ERROR; /* Something has gone awry. */
  53263. }
  53264. iCellDepth = pCur->iPage;
  53265. iCellIdx = pCur->aiIdx[iCellDepth];
  53266. pPage = pCur->apPage[iCellDepth];
  53267. pCell = findCell(pPage, iCellIdx);
  53268. /* If the page containing the entry to delete is not a leaf page, move
  53269. ** the cursor to the largest entry in the tree that is smaller than
  53270. ** the entry being deleted. This cell will replace the cell being deleted
  53271. ** from the internal node. The 'previous' entry is used for this instead
  53272. ** of the 'next' entry, as the previous entry is always a part of the
  53273. ** sub-tree headed by the child page of the cell being deleted. This makes
  53274. ** balancing the tree following the delete operation easier. */
  53275. if( !pPage->leaf ){
  53276. int notUsed;
  53277. rc = sqlite3BtreePrevious(pCur, &notUsed);
  53278. if( rc ) return rc;
  53279. }
  53280. /* Save the positions of any other cursors open on this table before
  53281. ** making any modifications. Make the page containing the entry to be
  53282. ** deleted writable. Then free any overflow pages associated with the
  53283. ** entry and finally remove the cell itself from within the page.
  53284. */
  53285. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  53286. if( rc ) return rc;
  53287. /* If this is a delete operation to remove a row from a table b-tree,
  53288. ** invalidate any incrblob cursors open on the row being deleted. */
  53289. if( pCur->pKeyInfo==0 ){
  53290. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  53291. }
  53292. rc = sqlite3PagerWrite(pPage->pDbPage);
  53293. if( rc ) return rc;
  53294. rc = clearCell(pPage, pCell);
  53295. dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
  53296. if( rc ) return rc;
  53297. /* If the cell deleted was not located on a leaf page, then the cursor
  53298. ** is currently pointing to the largest entry in the sub-tree headed
  53299. ** by the child-page of the cell that was just deleted from an internal
  53300. ** node. The cell from the leaf node needs to be moved to the internal
  53301. ** node to replace the deleted cell. */
  53302. if( !pPage->leaf ){
  53303. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  53304. int nCell;
  53305. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  53306. unsigned char *pTmp;
  53307. pCell = findCell(pLeaf, pLeaf->nCell-1);
  53308. nCell = cellSizePtr(pLeaf, pCell);
  53309. assert( MX_CELL_SIZE(pBt) >= nCell );
  53310. allocateTempSpace(pBt);
  53311. pTmp = pBt->pTmpSpace;
  53312. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  53313. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  53314. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  53315. if( rc ) return rc;
  53316. }
  53317. /* Balance the tree. If the entry deleted was located on a leaf page,
  53318. ** then the cursor still points to that page. In this case the first
  53319. ** call to balance() repairs the tree, and the if(...) condition is
  53320. ** never true.
  53321. **
  53322. ** Otherwise, if the entry deleted was on an internal node page, then
  53323. ** pCur is pointing to the leaf page from which a cell was removed to
  53324. ** replace the cell deleted from the internal node. This is slightly
  53325. ** tricky as the leaf node may be underfull, and the internal node may
  53326. ** be either under or overfull. In this case run the balancing algorithm
  53327. ** on the leaf node first. If the balance proceeds far enough up the
  53328. ** tree that we can be sure that any problem in the internal node has
  53329. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  53330. ** walk the cursor up the tree to the internal node and balance it as
  53331. ** well. */
  53332. rc = balance(pCur);
  53333. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  53334. while( pCur->iPage>iCellDepth ){
  53335. releasePage(pCur->apPage[pCur->iPage--]);
  53336. }
  53337. rc = balance(pCur);
  53338. }
  53339. if( rc==SQLITE_OK ){
  53340. moveToRoot(pCur);
  53341. }
  53342. return rc;
  53343. }
  53344. /*
  53345. ** Create a new BTree table. Write into *piTable the page
  53346. ** number for the root page of the new table.
  53347. **
  53348. ** The type of type is determined by the flags parameter. Only the
  53349. ** following values of flags are currently in use. Other values for
  53350. ** flags might not work:
  53351. **
  53352. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  53353. ** BTREE_ZERODATA Used for SQL indices
  53354. */
  53355. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  53356. BtShared *pBt = p->pBt;
  53357. MemPage *pRoot;
  53358. Pgno pgnoRoot;
  53359. int rc;
  53360. int ptfFlags; /* Page-type flage for the root page of new table */
  53361. assert( sqlite3BtreeHoldsMutex(p) );
  53362. assert( pBt->inTransaction==TRANS_WRITE );
  53363. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  53364. #ifdef SQLITE_OMIT_AUTOVACUUM
  53365. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  53366. if( rc ){
  53367. return rc;
  53368. }
  53369. #else
  53370. if( pBt->autoVacuum ){
  53371. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  53372. MemPage *pPageMove; /* The page to move to. */
  53373. /* Creating a new table may probably require moving an existing database
  53374. ** to make room for the new tables root page. In case this page turns
  53375. ** out to be an overflow page, delete all overflow page-map caches
  53376. ** held by open cursors.
  53377. */
  53378. invalidateAllOverflowCache(pBt);
  53379. /* Read the value of meta[3] from the database to determine where the
  53380. ** root page of the new table should go. meta[3] is the largest root-page
  53381. ** created so far, so the new root-page is (meta[3]+1).
  53382. */
  53383. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  53384. pgnoRoot++;
  53385. /* The new root-page may not be allocated on a pointer-map page, or the
  53386. ** PENDING_BYTE page.
  53387. */
  53388. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  53389. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  53390. pgnoRoot++;
  53391. }
  53392. assert( pgnoRoot>=3 );
  53393. /* Allocate a page. The page that currently resides at pgnoRoot will
  53394. ** be moved to the allocated page (unless the allocated page happens
  53395. ** to reside at pgnoRoot).
  53396. */
  53397. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  53398. if( rc!=SQLITE_OK ){
  53399. return rc;
  53400. }
  53401. if( pgnoMove!=pgnoRoot ){
  53402. /* pgnoRoot is the page that will be used for the root-page of
  53403. ** the new table (assuming an error did not occur). But we were
  53404. ** allocated pgnoMove. If required (i.e. if it was not allocated
  53405. ** by extending the file), the current page at position pgnoMove
  53406. ** is already journaled.
  53407. */
  53408. u8 eType = 0;
  53409. Pgno iPtrPage = 0;
  53410. /* Save the positions of any open cursors. This is required in
  53411. ** case they are holding a reference to an xFetch reference
  53412. ** corresponding to page pgnoRoot. */
  53413. rc = saveAllCursors(pBt, 0, 0);
  53414. releasePage(pPageMove);
  53415. if( rc!=SQLITE_OK ){
  53416. return rc;
  53417. }
  53418. /* Move the page currently at pgnoRoot to pgnoMove. */
  53419. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  53420. if( rc!=SQLITE_OK ){
  53421. return rc;
  53422. }
  53423. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  53424. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  53425. rc = SQLITE_CORRUPT_BKPT;
  53426. }
  53427. if( rc!=SQLITE_OK ){
  53428. releasePage(pRoot);
  53429. return rc;
  53430. }
  53431. assert( eType!=PTRMAP_ROOTPAGE );
  53432. assert( eType!=PTRMAP_FREEPAGE );
  53433. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  53434. releasePage(pRoot);
  53435. /* Obtain the page at pgnoRoot */
  53436. if( rc!=SQLITE_OK ){
  53437. return rc;
  53438. }
  53439. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  53440. if( rc!=SQLITE_OK ){
  53441. return rc;
  53442. }
  53443. rc = sqlite3PagerWrite(pRoot->pDbPage);
  53444. if( rc!=SQLITE_OK ){
  53445. releasePage(pRoot);
  53446. return rc;
  53447. }
  53448. }else{
  53449. pRoot = pPageMove;
  53450. }
  53451. /* Update the pointer-map and meta-data with the new root-page number. */
  53452. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  53453. if( rc ){
  53454. releasePage(pRoot);
  53455. return rc;
  53456. }
  53457. /* When the new root page was allocated, page 1 was made writable in
  53458. ** order either to increase the database filesize, or to decrement the
  53459. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  53460. */
  53461. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  53462. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  53463. if( NEVER(rc) ){
  53464. releasePage(pRoot);
  53465. return rc;
  53466. }
  53467. }else{
  53468. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  53469. if( rc ) return rc;
  53470. }
  53471. #endif
  53472. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  53473. if( createTabFlags & BTREE_INTKEY ){
  53474. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  53475. }else{
  53476. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  53477. }
  53478. zeroPage(pRoot, ptfFlags);
  53479. sqlite3PagerUnref(pRoot->pDbPage);
  53480. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  53481. *piTable = (int)pgnoRoot;
  53482. return SQLITE_OK;
  53483. }
  53484. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  53485. int rc;
  53486. sqlite3BtreeEnter(p);
  53487. rc = btreeCreateTable(p, piTable, flags);
  53488. sqlite3BtreeLeave(p);
  53489. return rc;
  53490. }
  53491. /*
  53492. ** Erase the given database page and all its children. Return
  53493. ** the page to the freelist.
  53494. */
  53495. static int clearDatabasePage(
  53496. BtShared *pBt, /* The BTree that contains the table */
  53497. Pgno pgno, /* Page number to clear */
  53498. int freePageFlag, /* Deallocate page if true */
  53499. int *pnChange /* Add number of Cells freed to this counter */
  53500. ){
  53501. MemPage *pPage;
  53502. int rc;
  53503. unsigned char *pCell;
  53504. int i;
  53505. assert( sqlite3_mutex_held(pBt->mutex) );
  53506. if( pgno>btreePagecount(pBt) ){
  53507. return SQLITE_CORRUPT_BKPT;
  53508. }
  53509. rc = getAndInitPage(pBt, pgno, &pPage, 0);
  53510. if( rc ) return rc;
  53511. for(i=0; i<pPage->nCell; i++){
  53512. pCell = findCell(pPage, i);
  53513. if( !pPage->leaf ){
  53514. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  53515. if( rc ) goto cleardatabasepage_out;
  53516. }
  53517. rc = clearCell(pPage, pCell);
  53518. if( rc ) goto cleardatabasepage_out;
  53519. }
  53520. if( !pPage->leaf ){
  53521. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
  53522. if( rc ) goto cleardatabasepage_out;
  53523. }else if( pnChange ){
  53524. assert( pPage->intKey );
  53525. *pnChange += pPage->nCell;
  53526. }
  53527. if( freePageFlag ){
  53528. freePage(pPage, &rc);
  53529. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  53530. zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
  53531. }
  53532. cleardatabasepage_out:
  53533. releasePage(pPage);
  53534. return rc;
  53535. }
  53536. /*
  53537. ** Delete all information from a single table in the database. iTable is
  53538. ** the page number of the root of the table. After this routine returns,
  53539. ** the root page is empty, but still exists.
  53540. **
  53541. ** This routine will fail with SQLITE_LOCKED if there are any open
  53542. ** read cursors on the table. Open write cursors are moved to the
  53543. ** root of the table.
  53544. **
  53545. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  53546. ** integer value pointed to by pnChange is incremented by the number of
  53547. ** entries in the table.
  53548. */
  53549. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  53550. int rc;
  53551. BtShared *pBt = p->pBt;
  53552. sqlite3BtreeEnter(p);
  53553. assert( p->inTrans==TRANS_WRITE );
  53554. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  53555. if( SQLITE_OK==rc ){
  53556. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  53557. ** is the root of a table b-tree - if it is not, the following call is
  53558. ** a no-op). */
  53559. invalidateIncrblobCursors(p, 0, 1);
  53560. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  53561. }
  53562. sqlite3BtreeLeave(p);
  53563. return rc;
  53564. }
  53565. /*
  53566. ** Erase all information in a table and add the root of the table to
  53567. ** the freelist. Except, the root of the principle table (the one on
  53568. ** page 1) is never added to the freelist.
  53569. **
  53570. ** This routine will fail with SQLITE_LOCKED if there are any open
  53571. ** cursors on the table.
  53572. **
  53573. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  53574. ** root page in the database file, then the last root page
  53575. ** in the database file is moved into the slot formerly occupied by
  53576. ** iTable and that last slot formerly occupied by the last root page
  53577. ** is added to the freelist instead of iTable. In this say, all
  53578. ** root pages are kept at the beginning of the database file, which
  53579. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  53580. ** page number that used to be the last root page in the file before
  53581. ** the move. If no page gets moved, *piMoved is set to 0.
  53582. ** The last root page is recorded in meta[3] and the value of
  53583. ** meta[3] is updated by this procedure.
  53584. */
  53585. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  53586. int rc;
  53587. MemPage *pPage = 0;
  53588. BtShared *pBt = p->pBt;
  53589. assert( sqlite3BtreeHoldsMutex(p) );
  53590. assert( p->inTrans==TRANS_WRITE );
  53591. /* It is illegal to drop a table if any cursors are open on the
  53592. ** database. This is because in auto-vacuum mode the backend may
  53593. ** need to move another root-page to fill a gap left by the deleted
  53594. ** root page. If an open cursor was using this page a problem would
  53595. ** occur.
  53596. **
  53597. ** This error is caught long before control reaches this point.
  53598. */
  53599. if( NEVER(pBt->pCursor) ){
  53600. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  53601. return SQLITE_LOCKED_SHAREDCACHE;
  53602. }
  53603. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  53604. if( rc ) return rc;
  53605. rc = sqlite3BtreeClearTable(p, iTable, 0);
  53606. if( rc ){
  53607. releasePage(pPage);
  53608. return rc;
  53609. }
  53610. *piMoved = 0;
  53611. if( iTable>1 ){
  53612. #ifdef SQLITE_OMIT_AUTOVACUUM
  53613. freePage(pPage, &rc);
  53614. releasePage(pPage);
  53615. #else
  53616. if( pBt->autoVacuum ){
  53617. Pgno maxRootPgno;
  53618. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  53619. if( iTable==maxRootPgno ){
  53620. /* If the table being dropped is the table with the largest root-page
  53621. ** number in the database, put the root page on the free list.
  53622. */
  53623. freePage(pPage, &rc);
  53624. releasePage(pPage);
  53625. if( rc!=SQLITE_OK ){
  53626. return rc;
  53627. }
  53628. }else{
  53629. /* The table being dropped does not have the largest root-page
  53630. ** number in the database. So move the page that does into the
  53631. ** gap left by the deleted root-page.
  53632. */
  53633. MemPage *pMove;
  53634. releasePage(pPage);
  53635. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  53636. if( rc!=SQLITE_OK ){
  53637. return rc;
  53638. }
  53639. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  53640. releasePage(pMove);
  53641. if( rc!=SQLITE_OK ){
  53642. return rc;
  53643. }
  53644. pMove = 0;
  53645. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  53646. freePage(pMove, &rc);
  53647. releasePage(pMove);
  53648. if( rc!=SQLITE_OK ){
  53649. return rc;
  53650. }
  53651. *piMoved = maxRootPgno;
  53652. }
  53653. /* Set the new 'max-root-page' value in the database header. This
  53654. ** is the old value less one, less one more if that happens to
  53655. ** be a root-page number, less one again if that is the
  53656. ** PENDING_BYTE_PAGE.
  53657. */
  53658. maxRootPgno--;
  53659. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  53660. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  53661. maxRootPgno--;
  53662. }
  53663. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  53664. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  53665. }else{
  53666. freePage(pPage, &rc);
  53667. releasePage(pPage);
  53668. }
  53669. #endif
  53670. }else{
  53671. /* If sqlite3BtreeDropTable was called on page 1.
  53672. ** This really never should happen except in a corrupt
  53673. ** database.
  53674. */
  53675. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  53676. releasePage(pPage);
  53677. }
  53678. return rc;
  53679. }
  53680. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  53681. int rc;
  53682. sqlite3BtreeEnter(p);
  53683. rc = btreeDropTable(p, iTable, piMoved);
  53684. sqlite3BtreeLeave(p);
  53685. return rc;
  53686. }
  53687. /*
  53688. ** This function may only be called if the b-tree connection already
  53689. ** has a read or write transaction open on the database.
  53690. **
  53691. ** Read the meta-information out of a database file. Meta[0]
  53692. ** is the number of free pages currently in the database. Meta[1]
  53693. ** through meta[15] are available for use by higher layers. Meta[0]
  53694. ** is read-only, the others are read/write.
  53695. **
  53696. ** The schema layer numbers meta values differently. At the schema
  53697. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  53698. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  53699. */
  53700. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  53701. BtShared *pBt = p->pBt;
  53702. sqlite3BtreeEnter(p);
  53703. assert( p->inTrans>TRANS_NONE );
  53704. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  53705. assert( pBt->pPage1 );
  53706. assert( idx>=0 && idx<=15 );
  53707. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  53708. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  53709. ** database, mark the database as read-only. */
  53710. #ifdef SQLITE_OMIT_AUTOVACUUM
  53711. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  53712. pBt->btsFlags |= BTS_READ_ONLY;
  53713. }
  53714. #endif
  53715. sqlite3BtreeLeave(p);
  53716. }
  53717. /*
  53718. ** Write meta-information back into the database. Meta[0] is
  53719. ** read-only and may not be written.
  53720. */
  53721. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  53722. BtShared *pBt = p->pBt;
  53723. unsigned char *pP1;
  53724. int rc;
  53725. assert( idx>=1 && idx<=15 );
  53726. sqlite3BtreeEnter(p);
  53727. assert( p->inTrans==TRANS_WRITE );
  53728. assert( pBt->pPage1!=0 );
  53729. pP1 = pBt->pPage1->aData;
  53730. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  53731. if( rc==SQLITE_OK ){
  53732. put4byte(&pP1[36 + idx*4], iMeta);
  53733. #ifndef SQLITE_OMIT_AUTOVACUUM
  53734. if( idx==BTREE_INCR_VACUUM ){
  53735. assert( pBt->autoVacuum || iMeta==0 );
  53736. assert( iMeta==0 || iMeta==1 );
  53737. pBt->incrVacuum = (u8)iMeta;
  53738. }
  53739. #endif
  53740. }
  53741. sqlite3BtreeLeave(p);
  53742. return rc;
  53743. }
  53744. #ifndef SQLITE_OMIT_BTREECOUNT
  53745. /*
  53746. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  53747. ** number of entries in the b-tree and write the result to *pnEntry.
  53748. **
  53749. ** SQLITE_OK is returned if the operation is successfully executed.
  53750. ** Otherwise, if an error is encountered (i.e. an IO error or database
  53751. ** corruption) an SQLite error code is returned.
  53752. */
  53753. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  53754. i64 nEntry = 0; /* Value to return in *pnEntry */
  53755. int rc; /* Return code */
  53756. if( pCur->pgnoRoot==0 ){
  53757. *pnEntry = 0;
  53758. return SQLITE_OK;
  53759. }
  53760. rc = moveToRoot(pCur);
  53761. /* Unless an error occurs, the following loop runs one iteration for each
  53762. ** page in the B-Tree structure (not including overflow pages).
  53763. */
  53764. while( rc==SQLITE_OK ){
  53765. int iIdx; /* Index of child node in parent */
  53766. MemPage *pPage; /* Current page of the b-tree */
  53767. /* If this is a leaf page or the tree is not an int-key tree, then
  53768. ** this page contains countable entries. Increment the entry counter
  53769. ** accordingly.
  53770. */
  53771. pPage = pCur->apPage[pCur->iPage];
  53772. if( pPage->leaf || !pPage->intKey ){
  53773. nEntry += pPage->nCell;
  53774. }
  53775. /* pPage is a leaf node. This loop navigates the cursor so that it
  53776. ** points to the first interior cell that it points to the parent of
  53777. ** the next page in the tree that has not yet been visited. The
  53778. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  53779. ** of the page, or to the number of cells in the page if the next page
  53780. ** to visit is the right-child of its parent.
  53781. **
  53782. ** If all pages in the tree have been visited, return SQLITE_OK to the
  53783. ** caller.
  53784. */
  53785. if( pPage->leaf ){
  53786. do {
  53787. if( pCur->iPage==0 ){
  53788. /* All pages of the b-tree have been visited. Return successfully. */
  53789. *pnEntry = nEntry;
  53790. return SQLITE_OK;
  53791. }
  53792. moveToParent(pCur);
  53793. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  53794. pCur->aiIdx[pCur->iPage]++;
  53795. pPage = pCur->apPage[pCur->iPage];
  53796. }
  53797. /* Descend to the child node of the cell that the cursor currently
  53798. ** points at. This is the right-child if (iIdx==pPage->nCell).
  53799. */
  53800. iIdx = pCur->aiIdx[pCur->iPage];
  53801. if( iIdx==pPage->nCell ){
  53802. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  53803. }else{
  53804. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  53805. }
  53806. }
  53807. /* An error has occurred. Return an error code. */
  53808. return rc;
  53809. }
  53810. #endif
  53811. /*
  53812. ** Return the pager associated with a BTree. This routine is used for
  53813. ** testing and debugging only.
  53814. */
  53815. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  53816. return p->pBt->pPager;
  53817. }
  53818. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  53819. /*
  53820. ** Append a message to the error message string.
  53821. */
  53822. static void checkAppendMsg(
  53823. IntegrityCk *pCheck,
  53824. char *zMsg1,
  53825. const char *zFormat,
  53826. ...
  53827. ){
  53828. va_list ap;
  53829. if( !pCheck->mxErr ) return;
  53830. pCheck->mxErr--;
  53831. pCheck->nErr++;
  53832. va_start(ap, zFormat);
  53833. if( pCheck->errMsg.nChar ){
  53834. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  53835. }
  53836. if( zMsg1 ){
  53837. sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
  53838. }
  53839. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  53840. va_end(ap);
  53841. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  53842. pCheck->mallocFailed = 1;
  53843. }
  53844. }
  53845. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  53846. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  53847. /*
  53848. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  53849. ** corresponds to page iPg is already set.
  53850. */
  53851. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  53852. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  53853. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  53854. }
  53855. /*
  53856. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  53857. */
  53858. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  53859. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  53860. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  53861. }
  53862. /*
  53863. ** Add 1 to the reference count for page iPage. If this is the second
  53864. ** reference to the page, add an error message to pCheck->zErrMsg.
  53865. ** Return 1 if there are 2 ore more references to the page and 0 if
  53866. ** if this is the first reference to the page.
  53867. **
  53868. ** Also check that the page number is in bounds.
  53869. */
  53870. static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
  53871. if( iPage==0 ) return 1;
  53872. if( iPage>pCheck->nPage ){
  53873. checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
  53874. return 1;
  53875. }
  53876. if( getPageReferenced(pCheck, iPage) ){
  53877. checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
  53878. return 1;
  53879. }
  53880. setPageReferenced(pCheck, iPage);
  53881. return 0;
  53882. }
  53883. #ifndef SQLITE_OMIT_AUTOVACUUM
  53884. /*
  53885. ** Check that the entry in the pointer-map for page iChild maps to
  53886. ** page iParent, pointer type ptrType. If not, append an error message
  53887. ** to pCheck.
  53888. */
  53889. static void checkPtrmap(
  53890. IntegrityCk *pCheck, /* Integrity check context */
  53891. Pgno iChild, /* Child page number */
  53892. u8 eType, /* Expected pointer map type */
  53893. Pgno iParent, /* Expected pointer map parent page number */
  53894. char *zContext /* Context description (used for error msg) */
  53895. ){
  53896. int rc;
  53897. u8 ePtrmapType;
  53898. Pgno iPtrmapParent;
  53899. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  53900. if( rc!=SQLITE_OK ){
  53901. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  53902. checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
  53903. return;
  53904. }
  53905. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  53906. checkAppendMsg(pCheck, zContext,
  53907. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  53908. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  53909. }
  53910. }
  53911. #endif
  53912. /*
  53913. ** Check the integrity of the freelist or of an overflow page list.
  53914. ** Verify that the number of pages on the list is N.
  53915. */
  53916. static void checkList(
  53917. IntegrityCk *pCheck, /* Integrity checking context */
  53918. int isFreeList, /* True for a freelist. False for overflow page list */
  53919. int iPage, /* Page number for first page in the list */
  53920. int N, /* Expected number of pages in the list */
  53921. char *zContext /* Context for error messages */
  53922. ){
  53923. int i;
  53924. int expected = N;
  53925. int iFirst = iPage;
  53926. while( N-- > 0 && pCheck->mxErr ){
  53927. DbPage *pOvflPage;
  53928. unsigned char *pOvflData;
  53929. if( iPage<1 ){
  53930. checkAppendMsg(pCheck, zContext,
  53931. "%d of %d pages missing from overflow list starting at %d",
  53932. N+1, expected, iFirst);
  53933. break;
  53934. }
  53935. if( checkRef(pCheck, iPage, zContext) ) break;
  53936. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  53937. checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
  53938. break;
  53939. }
  53940. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  53941. if( isFreeList ){
  53942. int n = get4byte(&pOvflData[4]);
  53943. #ifndef SQLITE_OMIT_AUTOVACUUM
  53944. if( pCheck->pBt->autoVacuum ){
  53945. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
  53946. }
  53947. #endif
  53948. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  53949. checkAppendMsg(pCheck, zContext,
  53950. "freelist leaf count too big on page %d", iPage);
  53951. N--;
  53952. }else{
  53953. for(i=0; i<n; i++){
  53954. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  53955. #ifndef SQLITE_OMIT_AUTOVACUUM
  53956. if( pCheck->pBt->autoVacuum ){
  53957. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
  53958. }
  53959. #endif
  53960. checkRef(pCheck, iFreePage, zContext);
  53961. }
  53962. N -= n;
  53963. }
  53964. }
  53965. #ifndef SQLITE_OMIT_AUTOVACUUM
  53966. else{
  53967. /* If this database supports auto-vacuum and iPage is not the last
  53968. ** page in this overflow list, check that the pointer-map entry for
  53969. ** the following page matches iPage.
  53970. */
  53971. if( pCheck->pBt->autoVacuum && N>0 ){
  53972. i = get4byte(pOvflData);
  53973. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
  53974. }
  53975. }
  53976. #endif
  53977. iPage = get4byte(pOvflData);
  53978. sqlite3PagerUnref(pOvflPage);
  53979. }
  53980. }
  53981. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  53982. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  53983. /*
  53984. ** Do various sanity checks on a single page of a tree. Return
  53985. ** the tree depth. Root pages return 0. Parents of root pages
  53986. ** return 1, and so forth.
  53987. **
  53988. ** These checks are done:
  53989. **
  53990. ** 1. Make sure that cells and freeblocks do not overlap
  53991. ** but combine to completely cover the page.
  53992. ** NO 2. Make sure cell keys are in order.
  53993. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  53994. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  53995. ** 5. Check the integrity of overflow pages.
  53996. ** 6. Recursively call checkTreePage on all children.
  53997. ** 7. Verify that the depth of all children is the same.
  53998. ** 8. Make sure this page is at least 33% full or else it is
  53999. ** the root of the tree.
  54000. */
  54001. static int checkTreePage(
  54002. IntegrityCk *pCheck, /* Context for the sanity check */
  54003. int iPage, /* Page number of the page to check */
  54004. char *zParentContext, /* Parent context */
  54005. i64 *pnParentMinKey,
  54006. i64 *pnParentMaxKey
  54007. ){
  54008. MemPage *pPage;
  54009. int i, rc, depth, d2, pgno, cnt;
  54010. int hdr, cellStart;
  54011. int nCell;
  54012. u8 *data;
  54013. BtShared *pBt;
  54014. int usableSize;
  54015. char zContext[100];
  54016. char *hit = 0;
  54017. i64 nMinKey = 0;
  54018. i64 nMaxKey = 0;
  54019. sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
  54020. /* Check that the page exists
  54021. */
  54022. pBt = pCheck->pBt;
  54023. usableSize = pBt->usableSize;
  54024. if( iPage==0 ) return 0;
  54025. if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  54026. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  54027. checkAppendMsg(pCheck, zContext,
  54028. "unable to get the page. error code=%d", rc);
  54029. return 0;
  54030. }
  54031. /* Clear MemPage.isInit to make sure the corruption detection code in
  54032. ** btreeInitPage() is executed. */
  54033. pPage->isInit = 0;
  54034. if( (rc = btreeInitPage(pPage))!=0 ){
  54035. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  54036. checkAppendMsg(pCheck, zContext,
  54037. "btreeInitPage() returns error code %d", rc);
  54038. releasePage(pPage);
  54039. return 0;
  54040. }
  54041. /* Check out all the cells.
  54042. */
  54043. depth = 0;
  54044. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  54045. u8 *pCell;
  54046. u32 sz;
  54047. CellInfo info;
  54048. /* Check payload overflow pages
  54049. */
  54050. sqlite3_snprintf(sizeof(zContext), zContext,
  54051. "On tree page %d cell %d: ", iPage, i);
  54052. pCell = findCell(pPage,i);
  54053. btreeParseCellPtr(pPage, pCell, &info);
  54054. sz = info.nData;
  54055. if( !pPage->intKey ) sz += (int)info.nKey;
  54056. /* For intKey pages, check that the keys are in order.
  54057. */
  54058. else if( i==0 ) nMinKey = nMaxKey = info.nKey;
  54059. else{
  54060. if( info.nKey <= nMaxKey ){
  54061. checkAppendMsg(pCheck, zContext,
  54062. "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  54063. }
  54064. nMaxKey = info.nKey;
  54065. }
  54066. assert( sz==info.nPayload );
  54067. if( (sz>info.nLocal)
  54068. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  54069. ){
  54070. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  54071. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  54072. #ifndef SQLITE_OMIT_AUTOVACUUM
  54073. if( pBt->autoVacuum ){
  54074. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
  54075. }
  54076. #endif
  54077. checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
  54078. }
  54079. /* Check sanity of left child page.
  54080. */
  54081. if( !pPage->leaf ){
  54082. pgno = get4byte(pCell);
  54083. #ifndef SQLITE_OMIT_AUTOVACUUM
  54084. if( pBt->autoVacuum ){
  54085. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  54086. }
  54087. #endif
  54088. d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
  54089. if( i>0 && d2!=depth ){
  54090. checkAppendMsg(pCheck, zContext, "Child page depth differs");
  54091. }
  54092. depth = d2;
  54093. }
  54094. }
  54095. if( !pPage->leaf ){
  54096. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  54097. sqlite3_snprintf(sizeof(zContext), zContext,
  54098. "On page %d at right child: ", iPage);
  54099. #ifndef SQLITE_OMIT_AUTOVACUUM
  54100. if( pBt->autoVacuum ){
  54101. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  54102. }
  54103. #endif
  54104. checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
  54105. }
  54106. /* For intKey leaf pages, check that the min/max keys are in order
  54107. ** with any left/parent/right pages.
  54108. */
  54109. if( pPage->leaf && pPage->intKey ){
  54110. /* if we are a left child page */
  54111. if( pnParentMinKey ){
  54112. /* if we are the left most child page */
  54113. if( !pnParentMaxKey ){
  54114. if( nMaxKey > *pnParentMinKey ){
  54115. checkAppendMsg(pCheck, zContext,
  54116. "Rowid %lld out of order (max larger than parent min of %lld)",
  54117. nMaxKey, *pnParentMinKey);
  54118. }
  54119. }else{
  54120. if( nMinKey <= *pnParentMinKey ){
  54121. checkAppendMsg(pCheck, zContext,
  54122. "Rowid %lld out of order (min less than parent min of %lld)",
  54123. nMinKey, *pnParentMinKey);
  54124. }
  54125. if( nMaxKey > *pnParentMaxKey ){
  54126. checkAppendMsg(pCheck, zContext,
  54127. "Rowid %lld out of order (max larger than parent max of %lld)",
  54128. nMaxKey, *pnParentMaxKey);
  54129. }
  54130. *pnParentMinKey = nMaxKey;
  54131. }
  54132. /* else if we're a right child page */
  54133. } else if( pnParentMaxKey ){
  54134. if( nMinKey <= *pnParentMaxKey ){
  54135. checkAppendMsg(pCheck, zContext,
  54136. "Rowid %lld out of order (min less than parent max of %lld)",
  54137. nMinKey, *pnParentMaxKey);
  54138. }
  54139. }
  54140. }
  54141. /* Check for complete coverage of the page
  54142. */
  54143. data = pPage->aData;
  54144. hdr = pPage->hdrOffset;
  54145. hit = sqlite3PageMalloc( pBt->pageSize );
  54146. if( hit==0 ){
  54147. pCheck->mallocFailed = 1;
  54148. }else{
  54149. int contentOffset = get2byteNotZero(&data[hdr+5]);
  54150. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  54151. memset(hit+contentOffset, 0, usableSize-contentOffset);
  54152. memset(hit, 1, contentOffset);
  54153. nCell = get2byte(&data[hdr+3]);
  54154. cellStart = hdr + 12 - 4*pPage->leaf;
  54155. for(i=0; i<nCell; i++){
  54156. int pc = get2byte(&data[cellStart+i*2]);
  54157. u32 size = 65536;
  54158. int j;
  54159. if( pc<=usableSize-4 ){
  54160. size = cellSizePtr(pPage, &data[pc]);
  54161. }
  54162. if( (int)(pc+size-1)>=usableSize ){
  54163. checkAppendMsg(pCheck, 0,
  54164. "Corruption detected in cell %d on page %d",i,iPage);
  54165. }else{
  54166. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  54167. }
  54168. }
  54169. i = get2byte(&data[hdr+1]);
  54170. while( i>0 ){
  54171. int size, j;
  54172. assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  54173. size = get2byte(&data[i+2]);
  54174. assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
  54175. for(j=i+size-1; j>=i; j--) hit[j]++;
  54176. j = get2byte(&data[i]);
  54177. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  54178. assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  54179. i = j;
  54180. }
  54181. for(i=cnt=0; i<usableSize; i++){
  54182. if( hit[i]==0 ){
  54183. cnt++;
  54184. }else if( hit[i]>1 ){
  54185. checkAppendMsg(pCheck, 0,
  54186. "Multiple uses for byte %d of page %d", i, iPage);
  54187. break;
  54188. }
  54189. }
  54190. if( cnt!=data[hdr+7] ){
  54191. checkAppendMsg(pCheck, 0,
  54192. "Fragmentation of %d bytes reported as %d on page %d",
  54193. cnt, data[hdr+7], iPage);
  54194. }
  54195. }
  54196. sqlite3PageFree(hit);
  54197. releasePage(pPage);
  54198. return depth+1;
  54199. }
  54200. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  54201. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  54202. /*
  54203. ** This routine does a complete check of the given BTree file. aRoot[] is
  54204. ** an array of pages numbers were each page number is the root page of
  54205. ** a table. nRoot is the number of entries in aRoot.
  54206. **
  54207. ** A read-only or read-write transaction must be opened before calling
  54208. ** this function.
  54209. **
  54210. ** Write the number of error seen in *pnErr. Except for some memory
  54211. ** allocation errors, an error message held in memory obtained from
  54212. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  54213. ** returned. If a memory allocation error occurs, NULL is returned.
  54214. */
  54215. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  54216. Btree *p, /* The btree to be checked */
  54217. int *aRoot, /* An array of root pages numbers for individual trees */
  54218. int nRoot, /* Number of entries in aRoot[] */
  54219. int mxErr, /* Stop reporting errors after this many */
  54220. int *pnErr /* Write number of errors seen to this variable */
  54221. ){
  54222. Pgno i;
  54223. int nRef;
  54224. IntegrityCk sCheck;
  54225. BtShared *pBt = p->pBt;
  54226. char zErr[100];
  54227. sqlite3BtreeEnter(p);
  54228. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  54229. nRef = sqlite3PagerRefcount(pBt->pPager);
  54230. sCheck.pBt = pBt;
  54231. sCheck.pPager = pBt->pPager;
  54232. sCheck.nPage = btreePagecount(sCheck.pBt);
  54233. sCheck.mxErr = mxErr;
  54234. sCheck.nErr = 0;
  54235. sCheck.mallocFailed = 0;
  54236. *pnErr = 0;
  54237. if( sCheck.nPage==0 ){
  54238. sqlite3BtreeLeave(p);
  54239. return 0;
  54240. }
  54241. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  54242. if( !sCheck.aPgRef ){
  54243. *pnErr = 1;
  54244. sqlite3BtreeLeave(p);
  54245. return 0;
  54246. }
  54247. i = PENDING_BYTE_PAGE(pBt);
  54248. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  54249. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  54250. sCheck.errMsg.useMalloc = 2;
  54251. /* Check the integrity of the freelist
  54252. */
  54253. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  54254. get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
  54255. /* Check all the tables.
  54256. */
  54257. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  54258. if( aRoot[i]==0 ) continue;
  54259. #ifndef SQLITE_OMIT_AUTOVACUUM
  54260. if( pBt->autoVacuum && aRoot[i]>1 ){
  54261. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
  54262. }
  54263. #endif
  54264. checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
  54265. }
  54266. /* Make sure every page in the file is referenced
  54267. */
  54268. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  54269. #ifdef SQLITE_OMIT_AUTOVACUUM
  54270. if( getPageReferenced(&sCheck, i)==0 ){
  54271. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  54272. }
  54273. #else
  54274. /* If the database supports auto-vacuum, make sure no tables contain
  54275. ** references to pointer-map pages.
  54276. */
  54277. if( getPageReferenced(&sCheck, i)==0 &&
  54278. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  54279. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  54280. }
  54281. if( getPageReferenced(&sCheck, i)!=0 &&
  54282. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  54283. checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
  54284. }
  54285. #endif
  54286. }
  54287. /* Make sure this analysis did not leave any unref() pages.
  54288. ** This is an internal consistency check; an integrity check
  54289. ** of the integrity check.
  54290. */
  54291. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  54292. checkAppendMsg(&sCheck, 0,
  54293. "Outstanding page count goes from %d to %d during this analysis",
  54294. nRef, sqlite3PagerRefcount(pBt->pPager)
  54295. );
  54296. }
  54297. /* Clean up and report errors.
  54298. */
  54299. sqlite3BtreeLeave(p);
  54300. sqlite3_free(sCheck.aPgRef);
  54301. if( sCheck.mallocFailed ){
  54302. sqlite3StrAccumReset(&sCheck.errMsg);
  54303. *pnErr = sCheck.nErr+1;
  54304. return 0;
  54305. }
  54306. *pnErr = sCheck.nErr;
  54307. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  54308. return sqlite3StrAccumFinish(&sCheck.errMsg);
  54309. }
  54310. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  54311. /*
  54312. ** Return the full pathname of the underlying database file. Return
  54313. ** an empty string if the database is in-memory or a TEMP database.
  54314. **
  54315. ** The pager filename is invariant as long as the pager is
  54316. ** open so it is safe to access without the BtShared mutex.
  54317. */
  54318. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  54319. assert( p->pBt->pPager!=0 );
  54320. return sqlite3PagerFilename(p->pBt->pPager, 1);
  54321. }
  54322. /*
  54323. ** Return the pathname of the journal file for this database. The return
  54324. ** value of this routine is the same regardless of whether the journal file
  54325. ** has been created or not.
  54326. **
  54327. ** The pager journal filename is invariant as long as the pager is
  54328. ** open so it is safe to access without the BtShared mutex.
  54329. */
  54330. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  54331. assert( p->pBt->pPager!=0 );
  54332. return sqlite3PagerJournalname(p->pBt->pPager);
  54333. }
  54334. /*
  54335. ** Return non-zero if a transaction is active.
  54336. */
  54337. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  54338. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  54339. return (p && (p->inTrans==TRANS_WRITE));
  54340. }
  54341. #ifndef SQLITE_OMIT_WAL
  54342. /*
  54343. ** Run a checkpoint on the Btree passed as the first argument.
  54344. **
  54345. ** Return SQLITE_LOCKED if this or any other connection has an open
  54346. ** transaction on the shared-cache the argument Btree is connected to.
  54347. **
  54348. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  54349. */
  54350. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  54351. int rc = SQLITE_OK;
  54352. if( p ){
  54353. BtShared *pBt = p->pBt;
  54354. sqlite3BtreeEnter(p);
  54355. if( pBt->inTransaction!=TRANS_NONE ){
  54356. rc = SQLITE_LOCKED;
  54357. }else{
  54358. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  54359. }
  54360. sqlite3BtreeLeave(p);
  54361. }
  54362. return rc;
  54363. }
  54364. #endif
  54365. /*
  54366. ** Return non-zero if a read (or write) transaction is active.
  54367. */
  54368. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  54369. assert( p );
  54370. assert( sqlite3_mutex_held(p->db->mutex) );
  54371. return p->inTrans!=TRANS_NONE;
  54372. }
  54373. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  54374. assert( p );
  54375. assert( sqlite3_mutex_held(p->db->mutex) );
  54376. return p->nBackup!=0;
  54377. }
  54378. /*
  54379. ** This function returns a pointer to a blob of memory associated with
  54380. ** a single shared-btree. The memory is used by client code for its own
  54381. ** purposes (for example, to store a high-level schema associated with
  54382. ** the shared-btree). The btree layer manages reference counting issues.
  54383. **
  54384. ** The first time this is called on a shared-btree, nBytes bytes of memory
  54385. ** are allocated, zeroed, and returned to the caller. For each subsequent
  54386. ** call the nBytes parameter is ignored and a pointer to the same blob
  54387. ** of memory returned.
  54388. **
  54389. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  54390. ** allocated, a null pointer is returned. If the blob has already been
  54391. ** allocated, it is returned as normal.
  54392. **
  54393. ** Just before the shared-btree is closed, the function passed as the
  54394. ** xFree argument when the memory allocation was made is invoked on the
  54395. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  54396. ** on the memory, the btree layer does that.
  54397. */
  54398. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  54399. BtShared *pBt = p->pBt;
  54400. sqlite3BtreeEnter(p);
  54401. if( !pBt->pSchema && nBytes ){
  54402. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  54403. pBt->xFreeSchema = xFree;
  54404. }
  54405. sqlite3BtreeLeave(p);
  54406. return pBt->pSchema;
  54407. }
  54408. /*
  54409. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  54410. ** btree as the argument handle holds an exclusive lock on the
  54411. ** sqlite_master table. Otherwise SQLITE_OK.
  54412. */
  54413. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  54414. int rc;
  54415. assert( sqlite3_mutex_held(p->db->mutex) );
  54416. sqlite3BtreeEnter(p);
  54417. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  54418. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  54419. sqlite3BtreeLeave(p);
  54420. return rc;
  54421. }
  54422. #ifndef SQLITE_OMIT_SHARED_CACHE
  54423. /*
  54424. ** Obtain a lock on the table whose root page is iTab. The
  54425. ** lock is a write lock if isWritelock is true or a read lock
  54426. ** if it is false.
  54427. */
  54428. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  54429. int rc = SQLITE_OK;
  54430. assert( p->inTrans!=TRANS_NONE );
  54431. if( p->sharable ){
  54432. u8 lockType = READ_LOCK + isWriteLock;
  54433. assert( READ_LOCK+1==WRITE_LOCK );
  54434. assert( isWriteLock==0 || isWriteLock==1 );
  54435. sqlite3BtreeEnter(p);
  54436. rc = querySharedCacheTableLock(p, iTab, lockType);
  54437. if( rc==SQLITE_OK ){
  54438. rc = setSharedCacheTableLock(p, iTab, lockType);
  54439. }
  54440. sqlite3BtreeLeave(p);
  54441. }
  54442. return rc;
  54443. }
  54444. #endif
  54445. #ifndef SQLITE_OMIT_INCRBLOB
  54446. /*
  54447. ** Argument pCsr must be a cursor opened for writing on an
  54448. ** INTKEY table currently pointing at a valid table entry.
  54449. ** This function modifies the data stored as part of that entry.
  54450. **
  54451. ** Only the data content may only be modified, it is not possible to
  54452. ** change the length of the data stored. If this function is called with
  54453. ** parameters that attempt to write past the end of the existing data,
  54454. ** no modifications are made and SQLITE_CORRUPT is returned.
  54455. */
  54456. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  54457. int rc;
  54458. assert( cursorHoldsMutex(pCsr) );
  54459. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  54460. assert( pCsr->isIncrblobHandle );
  54461. rc = restoreCursorPosition(pCsr);
  54462. if( rc!=SQLITE_OK ){
  54463. return rc;
  54464. }
  54465. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  54466. if( pCsr->eState!=CURSOR_VALID ){
  54467. return SQLITE_ABORT;
  54468. }
  54469. /* Save the positions of all other cursors open on this table. This is
  54470. ** required in case any of them are holding references to an xFetch
  54471. ** version of the b-tree page modified by the accessPayload call below.
  54472. **
  54473. ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
  54474. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  54475. ** saveAllCursors can only return SQLITE_OK.
  54476. */
  54477. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  54478. assert( rc==SQLITE_OK );
  54479. /* Check some assumptions:
  54480. ** (a) the cursor is open for writing,
  54481. ** (b) there is a read/write transaction open,
  54482. ** (c) the connection holds a write-lock on the table (if required),
  54483. ** (d) there are no conflicting read-locks, and
  54484. ** (e) the cursor points at a valid row of an intKey table.
  54485. */
  54486. if( !pCsr->wrFlag ){
  54487. return SQLITE_READONLY;
  54488. }
  54489. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  54490. && pCsr->pBt->inTransaction==TRANS_WRITE );
  54491. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  54492. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  54493. assert( pCsr->apPage[pCsr->iPage]->intKey );
  54494. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  54495. }
  54496. /*
  54497. ** Set a flag on this cursor to cache the locations of pages from the
  54498. ** overflow list for the current row. This is used by cursors opened
  54499. ** for incremental blob IO only.
  54500. **
  54501. ** This function sets a flag only. The actual page location cache
  54502. ** (stored in BtCursor.aOverflow[]) is allocated and used by function
  54503. ** accessPayload() (the worker function for sqlite3BtreeData() and
  54504. ** sqlite3BtreePutData()).
  54505. */
  54506. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  54507. assert( cursorHoldsMutex(pCur) );
  54508. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  54509. invalidateOverflowCache(pCur);
  54510. pCur->isIncrblobHandle = 1;
  54511. }
  54512. #endif
  54513. /*
  54514. ** Set both the "read version" (single byte at byte offset 18) and
  54515. ** "write version" (single byte at byte offset 19) fields in the database
  54516. ** header to iVersion.
  54517. */
  54518. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  54519. BtShared *pBt = pBtree->pBt;
  54520. int rc; /* Return code */
  54521. assert( iVersion==1 || iVersion==2 );
  54522. /* If setting the version fields to 1, do not automatically open the
  54523. ** WAL connection, even if the version fields are currently set to 2.
  54524. */
  54525. pBt->btsFlags &= ~BTS_NO_WAL;
  54526. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  54527. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  54528. if( rc==SQLITE_OK ){
  54529. u8 *aData = pBt->pPage1->aData;
  54530. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  54531. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  54532. if( rc==SQLITE_OK ){
  54533. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  54534. if( rc==SQLITE_OK ){
  54535. aData[18] = (u8)iVersion;
  54536. aData[19] = (u8)iVersion;
  54537. }
  54538. }
  54539. }
  54540. }
  54541. pBt->btsFlags &= ~BTS_NO_WAL;
  54542. return rc;
  54543. }
  54544. /*
  54545. ** set the mask of hint flags for cursor pCsr. Currently the only valid
  54546. ** values are 0 and BTREE_BULKLOAD.
  54547. */
  54548. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  54549. assert( mask==BTREE_BULKLOAD || mask==0 );
  54550. pCsr->hints = mask;
  54551. }
  54552. /************** End of btree.c ***********************************************/
  54553. /************** Begin file backup.c ******************************************/
  54554. /*
  54555. ** 2009 January 28
  54556. **
  54557. ** The author disclaims copyright to this source code. In place of
  54558. ** a legal notice, here is a blessing:
  54559. **
  54560. ** May you do good and not evil.
  54561. ** May you find forgiveness for yourself and forgive others.
  54562. ** May you share freely, never taking more than you give.
  54563. **
  54564. *************************************************************************
  54565. ** This file contains the implementation of the sqlite3_backup_XXX()
  54566. ** API functions and the related features.
  54567. */
  54568. /*
  54569. ** Structure allocated for each backup operation.
  54570. */
  54571. struct sqlite3_backup {
  54572. sqlite3* pDestDb; /* Destination database handle */
  54573. Btree *pDest; /* Destination b-tree file */
  54574. u32 iDestSchema; /* Original schema cookie in destination */
  54575. int bDestLocked; /* True once a write-transaction is open on pDest */
  54576. Pgno iNext; /* Page number of the next source page to copy */
  54577. sqlite3* pSrcDb; /* Source database handle */
  54578. Btree *pSrc; /* Source b-tree file */
  54579. int rc; /* Backup process error code */
  54580. /* These two variables are set by every call to backup_step(). They are
  54581. ** read by calls to backup_remaining() and backup_pagecount().
  54582. */
  54583. Pgno nRemaining; /* Number of pages left to copy */
  54584. Pgno nPagecount; /* Total number of pages to copy */
  54585. int isAttached; /* True once backup has been registered with pager */
  54586. sqlite3_backup *pNext; /* Next backup associated with source pager */
  54587. };
  54588. /*
  54589. ** THREAD SAFETY NOTES:
  54590. **
  54591. ** Once it has been created using backup_init(), a single sqlite3_backup
  54592. ** structure may be accessed via two groups of thread-safe entry points:
  54593. **
  54594. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  54595. ** backup_finish(). Both these functions obtain the source database
  54596. ** handle mutex and the mutex associated with the source BtShared
  54597. ** structure, in that order.
  54598. **
  54599. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  54600. ** invoked by the pager layer to report various state changes in
  54601. ** the page cache associated with the source database. The mutex
  54602. ** associated with the source database BtShared structure will always
  54603. ** be held when either of these functions are invoked.
  54604. **
  54605. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  54606. ** backup_pagecount() are not thread-safe functions. If they are called
  54607. ** while some other thread is calling backup_step() or backup_finish(),
  54608. ** the values returned may be invalid. There is no way for a call to
  54609. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  54610. ** or backup_pagecount().
  54611. **
  54612. ** Depending on the SQLite configuration, the database handles and/or
  54613. ** the Btree objects may have their own mutexes that require locking.
  54614. ** Non-sharable Btrees (in-memory databases for example), do not have
  54615. ** associated mutexes.
  54616. */
  54617. /*
  54618. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  54619. ** in connection handle pDb. If such a database cannot be found, return
  54620. ** a NULL pointer and write an error message to pErrorDb.
  54621. **
  54622. ** If the "temp" database is requested, it may need to be opened by this
  54623. ** function. If an error occurs while doing so, return 0 and write an
  54624. ** error message to pErrorDb.
  54625. */
  54626. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  54627. int i = sqlite3FindDbName(pDb, zDb);
  54628. if( i==1 ){
  54629. Parse *pParse;
  54630. int rc = 0;
  54631. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  54632. if( pParse==0 ){
  54633. sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
  54634. rc = SQLITE_NOMEM;
  54635. }else{
  54636. pParse->db = pDb;
  54637. if( sqlite3OpenTempDatabase(pParse) ){
  54638. sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  54639. rc = SQLITE_ERROR;
  54640. }
  54641. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  54642. sqlite3StackFree(pErrorDb, pParse);
  54643. }
  54644. if( rc ){
  54645. return 0;
  54646. }
  54647. }
  54648. if( i<0 ){
  54649. sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  54650. return 0;
  54651. }
  54652. return pDb->aDb[i].pBt;
  54653. }
  54654. /*
  54655. ** Attempt to set the page size of the destination to match the page size
  54656. ** of the source.
  54657. */
  54658. static int setDestPgsz(sqlite3_backup *p){
  54659. int rc;
  54660. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  54661. return rc;
  54662. }
  54663. /*
  54664. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  54665. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  54666. ** a pointer to the new sqlite3_backup object.
  54667. **
  54668. ** If an error occurs, NULL is returned and an error code and error message
  54669. ** stored in database handle pDestDb.
  54670. */
  54671. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  54672. sqlite3* pDestDb, /* Database to write to */
  54673. const char *zDestDb, /* Name of database within pDestDb */
  54674. sqlite3* pSrcDb, /* Database connection to read from */
  54675. const char *zSrcDb /* Name of database within pSrcDb */
  54676. ){
  54677. sqlite3_backup *p; /* Value to return */
  54678. /* Lock the source database handle. The destination database
  54679. ** handle is not locked in this routine, but it is locked in
  54680. ** sqlite3_backup_step(). The user is required to ensure that no
  54681. ** other thread accesses the destination handle for the duration
  54682. ** of the backup operation. Any attempt to use the destination
  54683. ** database connection while a backup is in progress may cause
  54684. ** a malfunction or a deadlock.
  54685. */
  54686. sqlite3_mutex_enter(pSrcDb->mutex);
  54687. sqlite3_mutex_enter(pDestDb->mutex);
  54688. if( pSrcDb==pDestDb ){
  54689. sqlite3Error(
  54690. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  54691. );
  54692. p = 0;
  54693. }else {
  54694. /* Allocate space for a new sqlite3_backup object...
  54695. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  54696. ** call to sqlite3_backup_init() and is destroyed by a call to
  54697. ** sqlite3_backup_finish(). */
  54698. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  54699. if( !p ){
  54700. sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
  54701. }
  54702. }
  54703. /* If the allocation succeeded, populate the new object. */
  54704. if( p ){
  54705. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  54706. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  54707. p->pDestDb = pDestDb;
  54708. p->pSrcDb = pSrcDb;
  54709. p->iNext = 1;
  54710. p->isAttached = 0;
  54711. if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
  54712. /* One (or both) of the named databases did not exist or an OOM
  54713. ** error was hit. The error has already been written into the
  54714. ** pDestDb handle. All that is left to do here is free the
  54715. ** sqlite3_backup structure.
  54716. */
  54717. sqlite3_free(p);
  54718. p = 0;
  54719. }
  54720. }
  54721. if( p ){
  54722. p->pSrc->nBackup++;
  54723. }
  54724. sqlite3_mutex_leave(pDestDb->mutex);
  54725. sqlite3_mutex_leave(pSrcDb->mutex);
  54726. return p;
  54727. }
  54728. /*
  54729. ** Argument rc is an SQLite error code. Return true if this error is
  54730. ** considered fatal if encountered during a backup operation. All errors
  54731. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  54732. */
  54733. static int isFatalError(int rc){
  54734. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  54735. }
  54736. /*
  54737. ** Parameter zSrcData points to a buffer containing the data for
  54738. ** page iSrcPg from the source database. Copy this data into the
  54739. ** destination database.
  54740. */
  54741. static int backupOnePage(
  54742. sqlite3_backup *p, /* Backup handle */
  54743. Pgno iSrcPg, /* Source database page to backup */
  54744. const u8 *zSrcData, /* Source database page data */
  54745. int bUpdate /* True for an update, false otherwise */
  54746. ){
  54747. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  54748. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  54749. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  54750. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  54751. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  54752. #ifdef SQLITE_HAS_CODEC
  54753. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  54754. ** guaranteed that the shared-mutex is held by this thread, handle
  54755. ** p->pSrc may not actually be the owner. */
  54756. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  54757. int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
  54758. #endif
  54759. int rc = SQLITE_OK;
  54760. i64 iOff;
  54761. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  54762. assert( p->bDestLocked );
  54763. assert( !isFatalError(p->rc) );
  54764. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  54765. assert( zSrcData );
  54766. /* Catch the case where the destination is an in-memory database and the
  54767. ** page sizes of the source and destination differ.
  54768. */
  54769. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  54770. rc = SQLITE_READONLY;
  54771. }
  54772. #ifdef SQLITE_HAS_CODEC
  54773. /* Backup is not possible if the page size of the destination is changing
  54774. ** and a codec is in use.
  54775. */
  54776. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  54777. rc = SQLITE_READONLY;
  54778. }
  54779. /* Backup is not possible if the number of bytes of reserve space differ
  54780. ** between source and destination. If there is a difference, try to
  54781. ** fix the destination to agree with the source. If that is not possible,
  54782. ** then the backup cannot proceed.
  54783. */
  54784. if( nSrcReserve!=nDestReserve ){
  54785. u32 newPgsz = nSrcPgsz;
  54786. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  54787. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  54788. }
  54789. #endif
  54790. /* This loop runs once for each destination page spanned by the source
  54791. ** page. For each iteration, variable iOff is set to the byte offset
  54792. ** of the destination page.
  54793. */
  54794. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  54795. DbPage *pDestPg = 0;
  54796. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  54797. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  54798. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  54799. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  54800. ){
  54801. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  54802. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  54803. u8 *zOut = &zDestData[iOff%nDestPgsz];
  54804. /* Copy the data from the source page into the destination page.
  54805. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  54806. ** and the pager code use this trick (clearing the first byte
  54807. ** of the page 'extra' space to invalidate the Btree layers
  54808. ** cached parse of the page). MemPage.isInit is marked
  54809. ** "MUST BE FIRST" for this purpose.
  54810. */
  54811. memcpy(zOut, zIn, nCopy);
  54812. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  54813. if( iOff==0 && bUpdate==0 ){
  54814. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  54815. }
  54816. }
  54817. sqlite3PagerUnref(pDestPg);
  54818. }
  54819. return rc;
  54820. }
  54821. /*
  54822. ** If pFile is currently larger than iSize bytes, then truncate it to
  54823. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  54824. ** this function is a no-op.
  54825. **
  54826. ** Return SQLITE_OK if everything is successful, or an SQLite error
  54827. ** code if an error occurs.
  54828. */
  54829. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  54830. i64 iCurrent;
  54831. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  54832. if( rc==SQLITE_OK && iCurrent>iSize ){
  54833. rc = sqlite3OsTruncate(pFile, iSize);
  54834. }
  54835. return rc;
  54836. }
  54837. /*
  54838. ** Register this backup object with the associated source pager for
  54839. ** callbacks when pages are changed or the cache invalidated.
  54840. */
  54841. static void attachBackupObject(sqlite3_backup *p){
  54842. sqlite3_backup **pp;
  54843. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  54844. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  54845. p->pNext = *pp;
  54846. *pp = p;
  54847. p->isAttached = 1;
  54848. }
  54849. /*
  54850. ** Copy nPage pages from the source b-tree to the destination.
  54851. */
  54852. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  54853. int rc;
  54854. int destMode; /* Destination journal mode */
  54855. int pgszSrc = 0; /* Source page size */
  54856. int pgszDest = 0; /* Destination page size */
  54857. sqlite3_mutex_enter(p->pSrcDb->mutex);
  54858. sqlite3BtreeEnter(p->pSrc);
  54859. if( p->pDestDb ){
  54860. sqlite3_mutex_enter(p->pDestDb->mutex);
  54861. }
  54862. rc = p->rc;
  54863. if( !isFatalError(rc) ){
  54864. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  54865. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  54866. int ii; /* Iterator variable */
  54867. int nSrcPage = -1; /* Size of source db in pages */
  54868. int bCloseTrans = 0; /* True if src db requires unlocking */
  54869. /* If the source pager is currently in a write-transaction, return
  54870. ** SQLITE_BUSY immediately.
  54871. */
  54872. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  54873. rc = SQLITE_BUSY;
  54874. }else{
  54875. rc = SQLITE_OK;
  54876. }
  54877. /* Lock the destination database, if it is not locked already. */
  54878. if( SQLITE_OK==rc && p->bDestLocked==0
  54879. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  54880. ){
  54881. p->bDestLocked = 1;
  54882. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  54883. }
  54884. /* If there is no open read-transaction on the source database, open
  54885. ** one now. If a transaction is opened here, then it will be closed
  54886. ** before this function exits.
  54887. */
  54888. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  54889. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  54890. bCloseTrans = 1;
  54891. }
  54892. /* Do not allow backup if the destination database is in WAL mode
  54893. ** and the page sizes are different between source and destination */
  54894. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  54895. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  54896. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  54897. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  54898. rc = SQLITE_READONLY;
  54899. }
  54900. /* Now that there is a read-lock on the source database, query the
  54901. ** source pager for the number of pages in the database.
  54902. */
  54903. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  54904. assert( nSrcPage>=0 );
  54905. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  54906. const Pgno iSrcPg = p->iNext; /* Source page number */
  54907. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  54908. DbPage *pSrcPg; /* Source page object */
  54909. rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
  54910. PAGER_GET_READONLY);
  54911. if( rc==SQLITE_OK ){
  54912. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  54913. sqlite3PagerUnref(pSrcPg);
  54914. }
  54915. }
  54916. p->iNext++;
  54917. }
  54918. if( rc==SQLITE_OK ){
  54919. p->nPagecount = nSrcPage;
  54920. p->nRemaining = nSrcPage+1-p->iNext;
  54921. if( p->iNext>(Pgno)nSrcPage ){
  54922. rc = SQLITE_DONE;
  54923. }else if( !p->isAttached ){
  54924. attachBackupObject(p);
  54925. }
  54926. }
  54927. /* Update the schema version field in the destination database. This
  54928. ** is to make sure that the schema-version really does change in
  54929. ** the case where the source and destination databases have the
  54930. ** same schema version.
  54931. */
  54932. if( rc==SQLITE_DONE ){
  54933. if( nSrcPage==0 ){
  54934. rc = sqlite3BtreeNewDb(p->pDest);
  54935. nSrcPage = 1;
  54936. }
  54937. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  54938. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  54939. }
  54940. if( rc==SQLITE_OK ){
  54941. if( p->pDestDb ){
  54942. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  54943. }
  54944. if( destMode==PAGER_JOURNALMODE_WAL ){
  54945. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  54946. }
  54947. }
  54948. if( rc==SQLITE_OK ){
  54949. int nDestTruncate;
  54950. /* Set nDestTruncate to the final number of pages in the destination
  54951. ** database. The complication here is that the destination page
  54952. ** size may be different to the source page size.
  54953. **
  54954. ** If the source page size is smaller than the destination page size,
  54955. ** round up. In this case the call to sqlite3OsTruncate() below will
  54956. ** fix the size of the file. However it is important to call
  54957. ** sqlite3PagerTruncateImage() here so that any pages in the
  54958. ** destination file that lie beyond the nDestTruncate page mark are
  54959. ** journalled by PagerCommitPhaseOne() before they are destroyed
  54960. ** by the file truncation.
  54961. */
  54962. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  54963. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  54964. if( pgszSrc<pgszDest ){
  54965. int ratio = pgszDest/pgszSrc;
  54966. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  54967. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  54968. nDestTruncate--;
  54969. }
  54970. }else{
  54971. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  54972. }
  54973. assert( nDestTruncate>0 );
  54974. if( pgszSrc<pgszDest ){
  54975. /* If the source page-size is smaller than the destination page-size,
  54976. ** two extra things may need to happen:
  54977. **
  54978. ** * The destination may need to be truncated, and
  54979. **
  54980. ** * Data stored on the pages immediately following the
  54981. ** pending-byte page in the source database may need to be
  54982. ** copied into the destination database.
  54983. */
  54984. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  54985. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  54986. Pgno iPg;
  54987. int nDstPage;
  54988. i64 iOff;
  54989. i64 iEnd;
  54990. assert( pFile );
  54991. assert( nDestTruncate==0
  54992. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  54993. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  54994. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  54995. ));
  54996. /* This block ensures that all data required to recreate the original
  54997. ** database has been stored in the journal for pDestPager and the
  54998. ** journal synced to disk. So at this point we may safely modify
  54999. ** the database file in any way, knowing that if a power failure
  55000. ** occurs, the original database will be reconstructed from the
  55001. ** journal file. */
  55002. sqlite3PagerPagecount(pDestPager, &nDstPage);
  55003. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  55004. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  55005. DbPage *pPg;
  55006. rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
  55007. if( rc==SQLITE_OK ){
  55008. rc = sqlite3PagerWrite(pPg);
  55009. sqlite3PagerUnref(pPg);
  55010. }
  55011. }
  55012. }
  55013. if( rc==SQLITE_OK ){
  55014. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  55015. }
  55016. /* Write the extra pages and truncate the database file as required */
  55017. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  55018. for(
  55019. iOff=PENDING_BYTE+pgszSrc;
  55020. rc==SQLITE_OK && iOff<iEnd;
  55021. iOff+=pgszSrc
  55022. ){
  55023. PgHdr *pSrcPg = 0;
  55024. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  55025. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  55026. if( rc==SQLITE_OK ){
  55027. u8 *zData = sqlite3PagerGetData(pSrcPg);
  55028. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  55029. }
  55030. sqlite3PagerUnref(pSrcPg);
  55031. }
  55032. if( rc==SQLITE_OK ){
  55033. rc = backupTruncateFile(pFile, iSize);
  55034. }
  55035. /* Sync the database file to disk. */
  55036. if( rc==SQLITE_OK ){
  55037. rc = sqlite3PagerSync(pDestPager);
  55038. }
  55039. }else{
  55040. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  55041. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  55042. }
  55043. /* Finish committing the transaction to the destination database. */
  55044. if( SQLITE_OK==rc
  55045. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  55046. ){
  55047. rc = SQLITE_DONE;
  55048. }
  55049. }
  55050. }
  55051. /* If bCloseTrans is true, then this function opened a read transaction
  55052. ** on the source database. Close the read transaction here. There is
  55053. ** no need to check the return values of the btree methods here, as
  55054. ** "committing" a read-only transaction cannot fail.
  55055. */
  55056. if( bCloseTrans ){
  55057. TESTONLY( int rc2 );
  55058. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  55059. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  55060. assert( rc2==SQLITE_OK );
  55061. }
  55062. if( rc==SQLITE_IOERR_NOMEM ){
  55063. rc = SQLITE_NOMEM;
  55064. }
  55065. p->rc = rc;
  55066. }
  55067. if( p->pDestDb ){
  55068. sqlite3_mutex_leave(p->pDestDb->mutex);
  55069. }
  55070. sqlite3BtreeLeave(p->pSrc);
  55071. sqlite3_mutex_leave(p->pSrcDb->mutex);
  55072. return rc;
  55073. }
  55074. /*
  55075. ** Release all resources associated with an sqlite3_backup* handle.
  55076. */
  55077. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  55078. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  55079. sqlite3 *pSrcDb; /* Source database connection */
  55080. int rc; /* Value to return */
  55081. /* Enter the mutexes */
  55082. if( p==0 ) return SQLITE_OK;
  55083. pSrcDb = p->pSrcDb;
  55084. sqlite3_mutex_enter(pSrcDb->mutex);
  55085. sqlite3BtreeEnter(p->pSrc);
  55086. if( p->pDestDb ){
  55087. sqlite3_mutex_enter(p->pDestDb->mutex);
  55088. }
  55089. /* Detach this backup from the source pager. */
  55090. if( p->pDestDb ){
  55091. p->pSrc->nBackup--;
  55092. }
  55093. if( p->isAttached ){
  55094. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  55095. while( *pp!=p ){
  55096. pp = &(*pp)->pNext;
  55097. }
  55098. *pp = p->pNext;
  55099. }
  55100. /* If a transaction is still open on the Btree, roll it back. */
  55101. sqlite3BtreeRollback(p->pDest, SQLITE_OK);
  55102. /* Set the error code of the destination database handle. */
  55103. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  55104. sqlite3Error(p->pDestDb, rc, 0);
  55105. /* Exit the mutexes and free the backup context structure. */
  55106. if( p->pDestDb ){
  55107. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  55108. }
  55109. sqlite3BtreeLeave(p->pSrc);
  55110. if( p->pDestDb ){
  55111. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  55112. ** call to sqlite3_backup_init() and is destroyed by a call to
  55113. ** sqlite3_backup_finish(). */
  55114. sqlite3_free(p);
  55115. }
  55116. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  55117. return rc;
  55118. }
  55119. /*
  55120. ** Return the number of pages still to be backed up as of the most recent
  55121. ** call to sqlite3_backup_step().
  55122. */
  55123. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  55124. return p->nRemaining;
  55125. }
  55126. /*
  55127. ** Return the total number of pages in the source database as of the most
  55128. ** recent call to sqlite3_backup_step().
  55129. */
  55130. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  55131. return p->nPagecount;
  55132. }
  55133. /*
  55134. ** This function is called after the contents of page iPage of the
  55135. ** source database have been modified. If page iPage has already been
  55136. ** copied into the destination database, then the data written to the
  55137. ** destination is now invalidated. The destination copy of iPage needs
  55138. ** to be updated with the new data before the backup operation is
  55139. ** complete.
  55140. **
  55141. ** It is assumed that the mutex associated with the BtShared object
  55142. ** corresponding to the source database is held when this function is
  55143. ** called.
  55144. */
  55145. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  55146. sqlite3_backup *p; /* Iterator variable */
  55147. for(p=pBackup; p; p=p->pNext){
  55148. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  55149. if( !isFatalError(p->rc) && iPage<p->iNext ){
  55150. /* The backup process p has already copied page iPage. But now it
  55151. ** has been modified by a transaction on the source pager. Copy
  55152. ** the new data into the backup.
  55153. */
  55154. int rc;
  55155. assert( p->pDestDb );
  55156. sqlite3_mutex_enter(p->pDestDb->mutex);
  55157. rc = backupOnePage(p, iPage, aData, 1);
  55158. sqlite3_mutex_leave(p->pDestDb->mutex);
  55159. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  55160. if( rc!=SQLITE_OK ){
  55161. p->rc = rc;
  55162. }
  55163. }
  55164. }
  55165. }
  55166. /*
  55167. ** Restart the backup process. This is called when the pager layer
  55168. ** detects that the database has been modified by an external database
  55169. ** connection. In this case there is no way of knowing which of the
  55170. ** pages that have been copied into the destination database are still
  55171. ** valid and which are not, so the entire process needs to be restarted.
  55172. **
  55173. ** It is assumed that the mutex associated with the BtShared object
  55174. ** corresponding to the source database is held when this function is
  55175. ** called.
  55176. */
  55177. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  55178. sqlite3_backup *p; /* Iterator variable */
  55179. for(p=pBackup; p; p=p->pNext){
  55180. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  55181. p->iNext = 1;
  55182. }
  55183. }
  55184. #ifndef SQLITE_OMIT_VACUUM
  55185. /*
  55186. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  55187. ** must be active for both files.
  55188. **
  55189. ** The size of file pTo may be reduced by this operation. If anything
  55190. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  55191. ** transaction is committed before returning.
  55192. */
  55193. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  55194. int rc;
  55195. sqlite3_file *pFd; /* File descriptor for database pTo */
  55196. sqlite3_backup b;
  55197. sqlite3BtreeEnter(pTo);
  55198. sqlite3BtreeEnter(pFrom);
  55199. assert( sqlite3BtreeIsInTrans(pTo) );
  55200. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  55201. if( pFd->pMethods ){
  55202. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  55203. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  55204. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  55205. if( rc ) goto copy_finished;
  55206. }
  55207. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  55208. ** to 0. This is used by the implementations of sqlite3_backup_step()
  55209. ** and sqlite3_backup_finish() to detect that they are being called
  55210. ** from this function, not directly by the user.
  55211. */
  55212. memset(&b, 0, sizeof(b));
  55213. b.pSrcDb = pFrom->db;
  55214. b.pSrc = pFrom;
  55215. b.pDest = pTo;
  55216. b.iNext = 1;
  55217. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  55218. ** file. By passing this as the number of pages to copy to
  55219. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  55220. ** within a single call (unless an error occurs). The assert() statement
  55221. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  55222. ** or an error code.
  55223. */
  55224. sqlite3_backup_step(&b, 0x7FFFFFFF);
  55225. assert( b.rc!=SQLITE_OK );
  55226. rc = sqlite3_backup_finish(&b);
  55227. if( rc==SQLITE_OK ){
  55228. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  55229. }else{
  55230. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  55231. }
  55232. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  55233. copy_finished:
  55234. sqlite3BtreeLeave(pFrom);
  55235. sqlite3BtreeLeave(pTo);
  55236. return rc;
  55237. }
  55238. #endif /* SQLITE_OMIT_VACUUM */
  55239. /************** End of backup.c **********************************************/
  55240. /************** Begin file vdbemem.c *****************************************/
  55241. /*
  55242. ** 2004 May 26
  55243. **
  55244. ** The author disclaims copyright to this source code. In place of
  55245. ** a legal notice, here is a blessing:
  55246. **
  55247. ** May you do good and not evil.
  55248. ** May you find forgiveness for yourself and forgive others.
  55249. ** May you share freely, never taking more than you give.
  55250. **
  55251. *************************************************************************
  55252. **
  55253. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  55254. ** stores a single value in the VDBE. Mem is an opaque structure visible
  55255. ** only within the VDBE. Interface routines refer to a Mem using the
  55256. ** name sqlite_value
  55257. */
  55258. /*
  55259. ** If pMem is an object with a valid string representation, this routine
  55260. ** ensures the internal encoding for the string representation is
  55261. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  55262. **
  55263. ** If pMem is not a string object, or the encoding of the string
  55264. ** representation is already stored using the requested encoding, then this
  55265. ** routine is a no-op.
  55266. **
  55267. ** SQLITE_OK is returned if the conversion is successful (or not required).
  55268. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  55269. ** between formats.
  55270. */
  55271. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  55272. #ifndef SQLITE_OMIT_UTF16
  55273. int rc;
  55274. #endif
  55275. assert( (pMem->flags&MEM_RowSet)==0 );
  55276. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  55277. || desiredEnc==SQLITE_UTF16BE );
  55278. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  55279. return SQLITE_OK;
  55280. }
  55281. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55282. #ifdef SQLITE_OMIT_UTF16
  55283. return SQLITE_ERROR;
  55284. #else
  55285. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  55286. ** then the encoding of the value may not have changed.
  55287. */
  55288. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  55289. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  55290. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  55291. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  55292. return rc;
  55293. #endif
  55294. }
  55295. /*
  55296. ** Make sure pMem->z points to a writable allocation of at least
  55297. ** n bytes.
  55298. **
  55299. ** If the third argument passed to this function is true, then memory
  55300. ** cell pMem must contain a string or blob. In this case the content is
  55301. ** preserved. Otherwise, if the third parameter to this function is false,
  55302. ** any current string or blob value may be discarded.
  55303. **
  55304. ** This function sets the MEM_Dyn flag and clears any xDel callback.
  55305. ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
  55306. ** not set, Mem.n is zeroed.
  55307. */
  55308. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
  55309. assert( 1 >=
  55310. ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
  55311. (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
  55312. ((pMem->flags&MEM_Ephem) ? 1 : 0) +
  55313. ((pMem->flags&MEM_Static) ? 1 : 0)
  55314. );
  55315. assert( (pMem->flags&MEM_RowSet)==0 );
  55316. /* If the preserve flag is set to true, then the memory cell must already
  55317. ** contain a valid string or blob value. */
  55318. assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  55319. if( n<32 ) n = 32;
  55320. if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
  55321. if( preserve && pMem->z==pMem->zMalloc ){
  55322. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  55323. preserve = 0;
  55324. }else{
  55325. sqlite3DbFree(pMem->db, pMem->zMalloc);
  55326. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  55327. }
  55328. }
  55329. if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
  55330. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  55331. }
  55332. if( pMem->flags&MEM_Dyn && pMem->xDel ){
  55333. assert( pMem->xDel!=SQLITE_DYNAMIC );
  55334. pMem->xDel((void *)(pMem->z));
  55335. }
  55336. pMem->z = pMem->zMalloc;
  55337. if( pMem->z==0 ){
  55338. pMem->flags = MEM_Null;
  55339. }else{
  55340. pMem->flags &= ~(MEM_Ephem|MEM_Static);
  55341. }
  55342. pMem->xDel = 0;
  55343. return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
  55344. }
  55345. /*
  55346. ** Make the given Mem object MEM_Dyn. In other words, make it so
  55347. ** that any TEXT or BLOB content is stored in memory obtained from
  55348. ** malloc(). In this way, we know that the memory is safe to be
  55349. ** overwritten or altered.
  55350. **
  55351. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  55352. */
  55353. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  55354. int f;
  55355. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55356. assert( (pMem->flags&MEM_RowSet)==0 );
  55357. ExpandBlob(pMem);
  55358. f = pMem->flags;
  55359. if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
  55360. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  55361. return SQLITE_NOMEM;
  55362. }
  55363. pMem->z[pMem->n] = 0;
  55364. pMem->z[pMem->n+1] = 0;
  55365. pMem->flags |= MEM_Term;
  55366. #ifdef SQLITE_DEBUG
  55367. pMem->pScopyFrom = 0;
  55368. #endif
  55369. }
  55370. return SQLITE_OK;
  55371. }
  55372. /*
  55373. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  55374. ** blob stored in dynamically allocated space.
  55375. */
  55376. #ifndef SQLITE_OMIT_INCRBLOB
  55377. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  55378. if( pMem->flags & MEM_Zero ){
  55379. int nByte;
  55380. assert( pMem->flags&MEM_Blob );
  55381. assert( (pMem->flags&MEM_RowSet)==0 );
  55382. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55383. /* Set nByte to the number of bytes required to store the expanded blob. */
  55384. nByte = pMem->n + pMem->u.nZero;
  55385. if( nByte<=0 ){
  55386. nByte = 1;
  55387. }
  55388. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  55389. return SQLITE_NOMEM;
  55390. }
  55391. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  55392. pMem->n += pMem->u.nZero;
  55393. pMem->flags &= ~(MEM_Zero|MEM_Term);
  55394. }
  55395. return SQLITE_OK;
  55396. }
  55397. #endif
  55398. /*
  55399. ** Make sure the given Mem is \u0000 terminated.
  55400. */
  55401. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  55402. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55403. if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
  55404. return SQLITE_OK; /* Nothing to do */
  55405. }
  55406. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  55407. return SQLITE_NOMEM;
  55408. }
  55409. pMem->z[pMem->n] = 0;
  55410. pMem->z[pMem->n+1] = 0;
  55411. pMem->flags |= MEM_Term;
  55412. return SQLITE_OK;
  55413. }
  55414. /*
  55415. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  55416. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  55417. ** is a no-op.
  55418. **
  55419. ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
  55420. **
  55421. ** A MEM_Null value will never be passed to this function. This function is
  55422. ** used for converting values to text for returning to the user (i.e. via
  55423. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  55424. ** keys are strings. In the former case a NULL pointer is returned the
  55425. ** user and the later is an internal programming error.
  55426. */
  55427. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  55428. int rc = SQLITE_OK;
  55429. int fg = pMem->flags;
  55430. const int nByte = 32;
  55431. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55432. assert( !(fg&MEM_Zero) );
  55433. assert( !(fg&(MEM_Str|MEM_Blob)) );
  55434. assert( fg&(MEM_Int|MEM_Real) );
  55435. assert( (pMem->flags&MEM_RowSet)==0 );
  55436. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55437. if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  55438. return SQLITE_NOMEM;
  55439. }
  55440. /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
  55441. ** string representation of the value. Then, if the required encoding
  55442. ** is UTF-16le or UTF-16be do a translation.
  55443. **
  55444. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  55445. */
  55446. if( fg & MEM_Int ){
  55447. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  55448. }else{
  55449. assert( fg & MEM_Real );
  55450. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  55451. }
  55452. pMem->n = sqlite3Strlen30(pMem->z);
  55453. pMem->enc = SQLITE_UTF8;
  55454. pMem->flags |= MEM_Str|MEM_Term;
  55455. sqlite3VdbeChangeEncoding(pMem, enc);
  55456. return rc;
  55457. }
  55458. /*
  55459. ** Memory cell pMem contains the context of an aggregate function.
  55460. ** This routine calls the finalize method for that function. The
  55461. ** result of the aggregate is stored back into pMem.
  55462. **
  55463. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  55464. ** otherwise.
  55465. */
  55466. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  55467. int rc = SQLITE_OK;
  55468. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  55469. sqlite3_context ctx;
  55470. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  55471. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55472. memset(&ctx, 0, sizeof(ctx));
  55473. ctx.s.flags = MEM_Null;
  55474. ctx.s.db = pMem->db;
  55475. ctx.pMem = pMem;
  55476. ctx.pFunc = pFunc;
  55477. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  55478. assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
  55479. sqlite3DbFree(pMem->db, pMem->zMalloc);
  55480. memcpy(pMem, &ctx.s, sizeof(ctx.s));
  55481. rc = ctx.isError;
  55482. }
  55483. return rc;
  55484. }
  55485. /*
  55486. ** If the memory cell contains a string value that must be freed by
  55487. ** invoking an external callback, free it now. Calling this function
  55488. ** does not free any Mem.zMalloc buffer.
  55489. */
  55490. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
  55491. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  55492. if( p->flags&MEM_Agg ){
  55493. sqlite3VdbeMemFinalize(p, p->u.pDef);
  55494. assert( (p->flags & MEM_Agg)==0 );
  55495. sqlite3VdbeMemRelease(p);
  55496. }else if( p->flags&MEM_Dyn && p->xDel ){
  55497. assert( (p->flags&MEM_RowSet)==0 );
  55498. assert( p->xDel!=SQLITE_DYNAMIC );
  55499. p->xDel((void *)p->z);
  55500. p->xDel = 0;
  55501. }else if( p->flags&MEM_RowSet ){
  55502. sqlite3RowSetClear(p->u.pRowSet);
  55503. }else if( p->flags&MEM_Frame ){
  55504. sqlite3VdbeMemSetNull(p);
  55505. }
  55506. }
  55507. /*
  55508. ** Release any memory held by the Mem. This may leave the Mem in an
  55509. ** inconsistent state, for example with (Mem.z==0) and
  55510. ** (Mem.type==SQLITE_TEXT).
  55511. */
  55512. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  55513. VdbeMemRelease(p);
  55514. sqlite3DbFree(p->db, p->zMalloc);
  55515. p->z = 0;
  55516. p->zMalloc = 0;
  55517. p->xDel = 0;
  55518. }
  55519. /*
  55520. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  55521. ** If the double is too large, return 0x8000000000000000.
  55522. **
  55523. ** Most systems appear to do this simply by assigning
  55524. ** variables and without the extra range tests. But
  55525. ** there are reports that windows throws an expection
  55526. ** if the floating point value is out of range. (See ticket #2880.)
  55527. ** Because we do not completely understand the problem, we will
  55528. ** take the conservative approach and always do range tests
  55529. ** before attempting the conversion.
  55530. */
  55531. static i64 doubleToInt64(double r){
  55532. #ifdef SQLITE_OMIT_FLOATING_POINT
  55533. /* When floating-point is omitted, double and int64 are the same thing */
  55534. return r;
  55535. #else
  55536. /*
  55537. ** Many compilers we encounter do not define constants for the
  55538. ** minimum and maximum 64-bit integers, or they define them
  55539. ** inconsistently. And many do not understand the "LL" notation.
  55540. ** So we define our own static constants here using nothing
  55541. ** larger than a 32-bit integer constant.
  55542. */
  55543. static const i64 maxInt = LARGEST_INT64;
  55544. static const i64 minInt = SMALLEST_INT64;
  55545. if( r<(double)minInt ){
  55546. return minInt;
  55547. }else if( r>(double)maxInt ){
  55548. /* minInt is correct here - not maxInt. It turns out that assigning
  55549. ** a very large positive number to an integer results in a very large
  55550. ** negative integer. This makes no sense, but it is what x86 hardware
  55551. ** does so for compatibility we will do the same in software. */
  55552. return minInt;
  55553. }else{
  55554. return (i64)r;
  55555. }
  55556. #endif
  55557. }
  55558. /*
  55559. ** Return some kind of integer value which is the best we can do
  55560. ** at representing the value that *pMem describes as an integer.
  55561. ** If pMem is an integer, then the value is exact. If pMem is
  55562. ** a floating-point then the value returned is the integer part.
  55563. ** If pMem is a string or blob, then we make an attempt to convert
  55564. ** it into a integer and return that. If pMem represents an
  55565. ** an SQL-NULL value, return 0.
  55566. **
  55567. ** If pMem represents a string value, its encoding might be changed.
  55568. */
  55569. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  55570. int flags;
  55571. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55572. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55573. flags = pMem->flags;
  55574. if( flags & MEM_Int ){
  55575. return pMem->u.i;
  55576. }else if( flags & MEM_Real ){
  55577. return doubleToInt64(pMem->r);
  55578. }else if( flags & (MEM_Str|MEM_Blob) ){
  55579. i64 value = 0;
  55580. assert( pMem->z || pMem->n==0 );
  55581. testcase( pMem->z==0 );
  55582. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  55583. return value;
  55584. }else{
  55585. return 0;
  55586. }
  55587. }
  55588. /*
  55589. ** Return the best representation of pMem that we can get into a
  55590. ** double. If pMem is already a double or an integer, return its
  55591. ** value. If it is a string or blob, try to convert it to a double.
  55592. ** If it is a NULL, return 0.0.
  55593. */
  55594. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  55595. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55596. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55597. if( pMem->flags & MEM_Real ){
  55598. return pMem->r;
  55599. }else if( pMem->flags & MEM_Int ){
  55600. return (double)pMem->u.i;
  55601. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  55602. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  55603. double val = (double)0;
  55604. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  55605. return val;
  55606. }else{
  55607. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  55608. return (double)0;
  55609. }
  55610. }
  55611. /*
  55612. ** The MEM structure is already a MEM_Real. Try to also make it a
  55613. ** MEM_Int if we can.
  55614. */
  55615. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  55616. assert( pMem->flags & MEM_Real );
  55617. assert( (pMem->flags & MEM_RowSet)==0 );
  55618. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55619. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55620. pMem->u.i = doubleToInt64(pMem->r);
  55621. /* Only mark the value as an integer if
  55622. **
  55623. ** (1) the round-trip conversion real->int->real is a no-op, and
  55624. ** (2) The integer is neither the largest nor the smallest
  55625. ** possible integer (ticket #3922)
  55626. **
  55627. ** The second and third terms in the following conditional enforces
  55628. ** the second condition under the assumption that addition overflow causes
  55629. ** values to wrap around. On x86 hardware, the third term is always
  55630. ** true and could be omitted. But we leave it in because other
  55631. ** architectures might behave differently.
  55632. */
  55633. if( pMem->r==(double)pMem->u.i
  55634. && pMem->u.i>SMALLEST_INT64
  55635. #if defined(__i486__) || defined(__x86_64__)
  55636. && ALWAYS(pMem->u.i<LARGEST_INT64)
  55637. #else
  55638. && pMem->u.i<LARGEST_INT64
  55639. #endif
  55640. ){
  55641. pMem->flags |= MEM_Int;
  55642. }
  55643. }
  55644. /*
  55645. ** Convert pMem to type integer. Invalidate any prior representations.
  55646. */
  55647. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  55648. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55649. assert( (pMem->flags & MEM_RowSet)==0 );
  55650. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55651. pMem->u.i = sqlite3VdbeIntValue(pMem);
  55652. MemSetTypeFlag(pMem, MEM_Int);
  55653. return SQLITE_OK;
  55654. }
  55655. /*
  55656. ** Convert pMem so that it is of type MEM_Real.
  55657. ** Invalidate any prior representations.
  55658. */
  55659. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  55660. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55661. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55662. pMem->r = sqlite3VdbeRealValue(pMem);
  55663. MemSetTypeFlag(pMem, MEM_Real);
  55664. return SQLITE_OK;
  55665. }
  55666. /*
  55667. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  55668. ** Invalidate any prior representations.
  55669. **
  55670. ** Every effort is made to force the conversion, even if the input
  55671. ** is a string that does not look completely like a number. Convert
  55672. ** as much of the string as we can and ignore the rest.
  55673. */
  55674. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  55675. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  55676. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  55677. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55678. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  55679. MemSetTypeFlag(pMem, MEM_Int);
  55680. }else{
  55681. pMem->r = sqlite3VdbeRealValue(pMem);
  55682. MemSetTypeFlag(pMem, MEM_Real);
  55683. sqlite3VdbeIntegerAffinity(pMem);
  55684. }
  55685. }
  55686. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  55687. pMem->flags &= ~(MEM_Str|MEM_Blob);
  55688. return SQLITE_OK;
  55689. }
  55690. /*
  55691. ** Delete any previous value and set the value stored in *pMem to NULL.
  55692. */
  55693. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  55694. if( pMem->flags & MEM_Frame ){
  55695. VdbeFrame *pFrame = pMem->u.pFrame;
  55696. pFrame->pParent = pFrame->v->pDelFrame;
  55697. pFrame->v->pDelFrame = pFrame;
  55698. }
  55699. if( pMem->flags & MEM_RowSet ){
  55700. sqlite3RowSetClear(pMem->u.pRowSet);
  55701. }
  55702. MemSetTypeFlag(pMem, MEM_Null);
  55703. pMem->type = SQLITE_NULL;
  55704. }
  55705. /*
  55706. ** Delete any previous value and set the value to be a BLOB of length
  55707. ** n containing all zeros.
  55708. */
  55709. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  55710. sqlite3VdbeMemRelease(pMem);
  55711. pMem->flags = MEM_Blob|MEM_Zero;
  55712. pMem->type = SQLITE_BLOB;
  55713. pMem->n = 0;
  55714. if( n<0 ) n = 0;
  55715. pMem->u.nZero = n;
  55716. pMem->enc = SQLITE_UTF8;
  55717. #ifdef SQLITE_OMIT_INCRBLOB
  55718. sqlite3VdbeMemGrow(pMem, n, 0);
  55719. if( pMem->z ){
  55720. pMem->n = n;
  55721. memset(pMem->z, 0, n);
  55722. }
  55723. #endif
  55724. }
  55725. /*
  55726. ** Delete any previous value and set the value stored in *pMem to val,
  55727. ** manifest type INTEGER.
  55728. */
  55729. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  55730. sqlite3VdbeMemRelease(pMem);
  55731. pMem->u.i = val;
  55732. pMem->flags = MEM_Int;
  55733. pMem->type = SQLITE_INTEGER;
  55734. }
  55735. #ifndef SQLITE_OMIT_FLOATING_POINT
  55736. /*
  55737. ** Delete any previous value and set the value stored in *pMem to val,
  55738. ** manifest type REAL.
  55739. */
  55740. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  55741. if( sqlite3IsNaN(val) ){
  55742. sqlite3VdbeMemSetNull(pMem);
  55743. }else{
  55744. sqlite3VdbeMemRelease(pMem);
  55745. pMem->r = val;
  55746. pMem->flags = MEM_Real;
  55747. pMem->type = SQLITE_FLOAT;
  55748. }
  55749. }
  55750. #endif
  55751. /*
  55752. ** Delete any previous value and set the value of pMem to be an
  55753. ** empty boolean index.
  55754. */
  55755. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  55756. sqlite3 *db = pMem->db;
  55757. assert( db!=0 );
  55758. assert( (pMem->flags & MEM_RowSet)==0 );
  55759. sqlite3VdbeMemRelease(pMem);
  55760. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  55761. if( db->mallocFailed ){
  55762. pMem->flags = MEM_Null;
  55763. }else{
  55764. assert( pMem->zMalloc );
  55765. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
  55766. sqlite3DbMallocSize(db, pMem->zMalloc));
  55767. assert( pMem->u.pRowSet!=0 );
  55768. pMem->flags = MEM_RowSet;
  55769. }
  55770. }
  55771. /*
  55772. ** Return true if the Mem object contains a TEXT or BLOB that is
  55773. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  55774. */
  55775. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  55776. assert( p->db!=0 );
  55777. if( p->flags & (MEM_Str|MEM_Blob) ){
  55778. int n = p->n;
  55779. if( p->flags & MEM_Zero ){
  55780. n += p->u.nZero;
  55781. }
  55782. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  55783. }
  55784. return 0;
  55785. }
  55786. #ifdef SQLITE_DEBUG
  55787. /*
  55788. ** This routine prepares a memory cell for modication by breaking
  55789. ** its link to a shallow copy and by marking any current shallow
  55790. ** copies of this cell as invalid.
  55791. **
  55792. ** This is used for testing and debugging only - to make sure shallow
  55793. ** copies are not misused.
  55794. */
  55795. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  55796. int i;
  55797. Mem *pX;
  55798. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  55799. if( pX->pScopyFrom==pMem ){
  55800. pX->flags |= MEM_Invalid;
  55801. pX->pScopyFrom = 0;
  55802. }
  55803. }
  55804. pMem->pScopyFrom = 0;
  55805. }
  55806. #endif /* SQLITE_DEBUG */
  55807. /*
  55808. ** Size of struct Mem not including the Mem.zMalloc member.
  55809. */
  55810. #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
  55811. /*
  55812. ** Make an shallow copy of pFrom into pTo. Prior contents of
  55813. ** pTo are freed. The pFrom->z field is not duplicated. If
  55814. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  55815. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  55816. */
  55817. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  55818. assert( (pFrom->flags & MEM_RowSet)==0 );
  55819. VdbeMemRelease(pTo);
  55820. memcpy(pTo, pFrom, MEMCELLSIZE);
  55821. pTo->xDel = 0;
  55822. if( (pFrom->flags&MEM_Static)==0 ){
  55823. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  55824. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  55825. pTo->flags |= srcType;
  55826. }
  55827. }
  55828. /*
  55829. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  55830. ** freed before the copy is made.
  55831. */
  55832. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  55833. int rc = SQLITE_OK;
  55834. assert( (pFrom->flags & MEM_RowSet)==0 );
  55835. VdbeMemRelease(pTo);
  55836. memcpy(pTo, pFrom, MEMCELLSIZE);
  55837. pTo->flags &= ~MEM_Dyn;
  55838. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  55839. if( 0==(pFrom->flags&MEM_Static) ){
  55840. pTo->flags |= MEM_Ephem;
  55841. rc = sqlite3VdbeMemMakeWriteable(pTo);
  55842. }
  55843. }
  55844. return rc;
  55845. }
  55846. /*
  55847. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  55848. ** freed. If pFrom contains ephemeral data, a copy is made.
  55849. **
  55850. ** pFrom contains an SQL NULL when this routine returns.
  55851. */
  55852. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  55853. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  55854. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  55855. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  55856. sqlite3VdbeMemRelease(pTo);
  55857. memcpy(pTo, pFrom, sizeof(Mem));
  55858. pFrom->flags = MEM_Null;
  55859. pFrom->xDel = 0;
  55860. pFrom->zMalloc = 0;
  55861. }
  55862. /*
  55863. ** Change the value of a Mem to be a string or a BLOB.
  55864. **
  55865. ** The memory management strategy depends on the value of the xDel
  55866. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  55867. ** string is copied into a (possibly existing) buffer managed by the
  55868. ** Mem structure. Otherwise, any existing buffer is freed and the
  55869. ** pointer copied.
  55870. **
  55871. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  55872. ** size limit) then no memory allocation occurs. If the string can be
  55873. ** stored without allocating memory, then it is. If a memory allocation
  55874. ** is required to store the string, then value of pMem is unchanged. In
  55875. ** either case, SQLITE_TOOBIG is returned.
  55876. */
  55877. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  55878. Mem *pMem, /* Memory cell to set to string value */
  55879. const char *z, /* String pointer */
  55880. int n, /* Bytes in string, or negative */
  55881. u8 enc, /* Encoding of z. 0 for BLOBs */
  55882. void (*xDel)(void*) /* Destructor function */
  55883. ){
  55884. int nByte = n; /* New value for pMem->n */
  55885. int iLimit; /* Maximum allowed string or blob size */
  55886. u16 flags = 0; /* New value for pMem->flags */
  55887. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55888. assert( (pMem->flags & MEM_RowSet)==0 );
  55889. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  55890. if( !z ){
  55891. sqlite3VdbeMemSetNull(pMem);
  55892. return SQLITE_OK;
  55893. }
  55894. if( pMem->db ){
  55895. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  55896. }else{
  55897. iLimit = SQLITE_MAX_LENGTH;
  55898. }
  55899. flags = (enc==0?MEM_Blob:MEM_Str);
  55900. if( nByte<0 ){
  55901. assert( enc!=0 );
  55902. if( enc==SQLITE_UTF8 ){
  55903. for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
  55904. }else{
  55905. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  55906. }
  55907. flags |= MEM_Term;
  55908. }
  55909. /* The following block sets the new values of Mem.z and Mem.xDel. It
  55910. ** also sets a flag in local variable "flags" to indicate the memory
  55911. ** management (one of MEM_Dyn or MEM_Static).
  55912. */
  55913. if( xDel==SQLITE_TRANSIENT ){
  55914. int nAlloc = nByte;
  55915. if( flags&MEM_Term ){
  55916. nAlloc += (enc==SQLITE_UTF8?1:2);
  55917. }
  55918. if( nByte>iLimit ){
  55919. return SQLITE_TOOBIG;
  55920. }
  55921. if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
  55922. return SQLITE_NOMEM;
  55923. }
  55924. memcpy(pMem->z, z, nAlloc);
  55925. }else if( xDel==SQLITE_DYNAMIC ){
  55926. sqlite3VdbeMemRelease(pMem);
  55927. pMem->zMalloc = pMem->z = (char *)z;
  55928. pMem->xDel = 0;
  55929. }else{
  55930. sqlite3VdbeMemRelease(pMem);
  55931. pMem->z = (char *)z;
  55932. pMem->xDel = xDel;
  55933. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  55934. }
  55935. pMem->n = nByte;
  55936. pMem->flags = flags;
  55937. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  55938. pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
  55939. #ifndef SQLITE_OMIT_UTF16
  55940. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  55941. return SQLITE_NOMEM;
  55942. }
  55943. #endif
  55944. if( nByte>iLimit ){
  55945. return SQLITE_TOOBIG;
  55946. }
  55947. return SQLITE_OK;
  55948. }
  55949. /*
  55950. ** Compare the values contained by the two memory cells, returning
  55951. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  55952. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  55953. ** and reals) sorted numerically, followed by text ordered by the collating
  55954. ** sequence pColl and finally blob's ordered by memcmp().
  55955. **
  55956. ** Two NULL values are considered equal by this function.
  55957. */
  55958. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  55959. int rc;
  55960. int f1, f2;
  55961. int combined_flags;
  55962. f1 = pMem1->flags;
  55963. f2 = pMem2->flags;
  55964. combined_flags = f1|f2;
  55965. assert( (combined_flags & MEM_RowSet)==0 );
  55966. /* If one value is NULL, it is less than the other. If both values
  55967. ** are NULL, return 0.
  55968. */
  55969. if( combined_flags&MEM_Null ){
  55970. return (f2&MEM_Null) - (f1&MEM_Null);
  55971. }
  55972. /* If one value is a number and the other is not, the number is less.
  55973. ** If both are numbers, compare as reals if one is a real, or as integers
  55974. ** if both values are integers.
  55975. */
  55976. if( combined_flags&(MEM_Int|MEM_Real) ){
  55977. double r1, r2;
  55978. if( (f1 & f2 & MEM_Int)!=0 ){
  55979. if( pMem1->u.i < pMem2->u.i ) return -1;
  55980. if( pMem1->u.i > pMem2->u.i ) return 1;
  55981. return 0;
  55982. }
  55983. if( (f1&MEM_Real)!=0 ){
  55984. r1 = pMem1->r;
  55985. }else if( (f1&MEM_Int)!=0 ){
  55986. r1 = (double)pMem1->u.i;
  55987. }else{
  55988. return 1;
  55989. }
  55990. if( (f2&MEM_Real)!=0 ){
  55991. r2 = pMem2->r;
  55992. }else if( (f2&MEM_Int)!=0 ){
  55993. r2 = (double)pMem2->u.i;
  55994. }else{
  55995. return -1;
  55996. }
  55997. if( r1<r2 ) return -1;
  55998. if( r1>r2 ) return 1;
  55999. return 0;
  56000. }
  56001. /* If one value is a string and the other is a blob, the string is less.
  56002. ** If both are strings, compare using the collating functions.
  56003. */
  56004. if( combined_flags&MEM_Str ){
  56005. if( (f1 & MEM_Str)==0 ){
  56006. return 1;
  56007. }
  56008. if( (f2 & MEM_Str)==0 ){
  56009. return -1;
  56010. }
  56011. assert( pMem1->enc==pMem2->enc );
  56012. assert( pMem1->enc==SQLITE_UTF8 ||
  56013. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  56014. /* The collation sequence must be defined at this point, even if
  56015. ** the user deletes the collation sequence after the vdbe program is
  56016. ** compiled (this was not always the case).
  56017. */
  56018. assert( !pColl || pColl->xCmp );
  56019. if( pColl ){
  56020. if( pMem1->enc==pColl->enc ){
  56021. /* The strings are already in the correct encoding. Call the
  56022. ** comparison function directly */
  56023. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  56024. }else{
  56025. const void *v1, *v2;
  56026. int n1, n2;
  56027. Mem c1;
  56028. Mem c2;
  56029. memset(&c1, 0, sizeof(c1));
  56030. memset(&c2, 0, sizeof(c2));
  56031. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  56032. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  56033. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  56034. n1 = v1==0 ? 0 : c1.n;
  56035. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  56036. n2 = v2==0 ? 0 : c2.n;
  56037. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  56038. sqlite3VdbeMemRelease(&c1);
  56039. sqlite3VdbeMemRelease(&c2);
  56040. return rc;
  56041. }
  56042. }
  56043. /* If a NULL pointer was passed as the collate function, fall through
  56044. ** to the blob case and use memcmp(). */
  56045. }
  56046. /* Both values must be blobs. Compare using memcmp(). */
  56047. rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  56048. if( rc==0 ){
  56049. rc = pMem1->n - pMem2->n;
  56050. }
  56051. return rc;
  56052. }
  56053. /*
  56054. ** Move data out of a btree key or data field and into a Mem structure.
  56055. ** The data or key is taken from the entry that pCur is currently pointing
  56056. ** to. offset and amt determine what portion of the data or key to retrieve.
  56057. ** key is true to get the key or false to get data. The result is written
  56058. ** into the pMem element.
  56059. **
  56060. ** The pMem structure is assumed to be uninitialized. Any prior content
  56061. ** is overwritten without being freed.
  56062. **
  56063. ** If this routine fails for any reason (malloc returns NULL or unable
  56064. ** to read from the disk) then the pMem is left in an inconsistent state.
  56065. */
  56066. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  56067. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  56068. int offset, /* Offset from the start of data to return bytes from. */
  56069. int amt, /* Number of bytes to return. */
  56070. int key, /* If true, retrieve from the btree key, not data. */
  56071. Mem *pMem /* OUT: Return data in this Mem structure. */
  56072. ){
  56073. char *zData; /* Data from the btree layer */
  56074. int available = 0; /* Number of bytes available on the local btree page */
  56075. int rc = SQLITE_OK; /* Return code */
  56076. assert( sqlite3BtreeCursorIsValid(pCur) );
  56077. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  56078. ** that both the BtShared and database handle mutexes are held. */
  56079. assert( (pMem->flags & MEM_RowSet)==0 );
  56080. if( key ){
  56081. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  56082. }else{
  56083. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  56084. }
  56085. assert( zData!=0 );
  56086. if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
  56087. sqlite3VdbeMemRelease(pMem);
  56088. pMem->z = &zData[offset];
  56089. pMem->flags = MEM_Blob|MEM_Ephem;
  56090. }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
  56091. pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
  56092. pMem->enc = 0;
  56093. pMem->type = SQLITE_BLOB;
  56094. if( key ){
  56095. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  56096. }else{
  56097. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  56098. }
  56099. pMem->z[amt] = 0;
  56100. pMem->z[amt+1] = 0;
  56101. if( rc!=SQLITE_OK ){
  56102. sqlite3VdbeMemRelease(pMem);
  56103. }
  56104. }
  56105. pMem->n = amt;
  56106. return rc;
  56107. }
  56108. /* This function is only available internally, it is not part of the
  56109. ** external API. It works in a similar way to sqlite3_value_text(),
  56110. ** except the data returned is in the encoding specified by the second
  56111. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  56112. ** SQLITE_UTF8.
  56113. **
  56114. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  56115. ** If that is the case, then the result must be aligned on an even byte
  56116. ** boundary.
  56117. */
  56118. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  56119. if( !pVal ) return 0;
  56120. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  56121. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  56122. assert( (pVal->flags & MEM_RowSet)==0 );
  56123. if( pVal->flags&MEM_Null ){
  56124. return 0;
  56125. }
  56126. assert( (MEM_Blob>>3) == MEM_Str );
  56127. pVal->flags |= (pVal->flags & MEM_Blob)>>3;
  56128. ExpandBlob(pVal);
  56129. if( pVal->flags&MEM_Str ){
  56130. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  56131. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  56132. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  56133. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  56134. return 0;
  56135. }
  56136. }
  56137. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  56138. }else{
  56139. assert( (pVal->flags&MEM_Blob)==0 );
  56140. sqlite3VdbeMemStringify(pVal, enc);
  56141. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  56142. }
  56143. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  56144. || pVal->db->mallocFailed );
  56145. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  56146. return pVal->z;
  56147. }else{
  56148. return 0;
  56149. }
  56150. }
  56151. /*
  56152. ** Create a new sqlite3_value object.
  56153. */
  56154. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  56155. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  56156. if( p ){
  56157. p->flags = MEM_Null;
  56158. p->type = SQLITE_NULL;
  56159. p->db = db;
  56160. }
  56161. return p;
  56162. }
  56163. /*
  56164. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  56165. ** valueNew(). See comments above valueNew() for details.
  56166. */
  56167. struct ValueNewStat4Ctx {
  56168. Parse *pParse;
  56169. Index *pIdx;
  56170. UnpackedRecord **ppRec;
  56171. int iVal;
  56172. };
  56173. /*
  56174. ** Allocate and return a pointer to a new sqlite3_value object. If
  56175. ** the second argument to this function is NULL, the object is allocated
  56176. ** by calling sqlite3ValueNew().
  56177. **
  56178. ** Otherwise, if the second argument is non-zero, then this function is
  56179. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  56180. ** already been allocated, allocate the UnpackedRecord structure that
  56181. ** that function will return to its caller here. Then return a pointer
  56182. ** an sqlite3_value within the UnpackedRecord.a[] array.
  56183. */
  56184. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  56185. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  56186. if( p ){
  56187. UnpackedRecord *pRec = p->ppRec[0];
  56188. if( pRec==0 ){
  56189. Index *pIdx = p->pIdx; /* Index being probed */
  56190. int nByte; /* Bytes of space to allocate */
  56191. int i; /* Counter variable */
  56192. int nCol = pIdx->nColumn+1; /* Number of index columns including rowid */
  56193. nByte = sizeof(Mem) * nCol + sizeof(UnpackedRecord);
  56194. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  56195. if( pRec ){
  56196. pRec->pKeyInfo = sqlite3IndexKeyinfo(p->pParse, pIdx);
  56197. if( pRec->pKeyInfo ){
  56198. assert( pRec->pKeyInfo->nField+1==nCol );
  56199. pRec->pKeyInfo->enc = ENC(db);
  56200. pRec->flags = UNPACKED_PREFIX_MATCH;
  56201. pRec->aMem = (Mem *)&pRec[1];
  56202. for(i=0; i<nCol; i++){
  56203. pRec->aMem[i].flags = MEM_Null;
  56204. pRec->aMem[i].type = SQLITE_NULL;
  56205. pRec->aMem[i].db = db;
  56206. }
  56207. }else{
  56208. sqlite3DbFree(db, pRec);
  56209. pRec = 0;
  56210. }
  56211. }
  56212. if( pRec==0 ) return 0;
  56213. p->ppRec[0] = pRec;
  56214. }
  56215. pRec->nField = p->iVal+1;
  56216. return &pRec->aMem[p->iVal];
  56217. }
  56218. #else
  56219. UNUSED_PARAMETER(p);
  56220. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  56221. return sqlite3ValueNew(db);
  56222. }
  56223. /*
  56224. ** Extract a value from the supplied expression in the manner described
  56225. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  56226. ** using valueNew().
  56227. **
  56228. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  56229. ** has been allocated, it is freed before returning. Or, if pCtx is not
  56230. ** NULL, it is assumed that the caller will free any allocated object
  56231. ** in all cases.
  56232. */
  56233. static int valueFromExpr(
  56234. sqlite3 *db, /* The database connection */
  56235. Expr *pExpr, /* The expression to evaluate */
  56236. u8 enc, /* Encoding to use */
  56237. u8 affinity, /* Affinity to use */
  56238. sqlite3_value **ppVal, /* Write the new value here */
  56239. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  56240. ){
  56241. int op;
  56242. char *zVal = 0;
  56243. sqlite3_value *pVal = 0;
  56244. int negInt = 1;
  56245. const char *zNeg = "";
  56246. int rc = SQLITE_OK;
  56247. if( !pExpr ){
  56248. *ppVal = 0;
  56249. return SQLITE_OK;
  56250. }
  56251. op = pExpr->op;
  56252. /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT4.
  56253. ** The ifdef here is to enable us to achieve 100% branch test coverage even
  56254. ** when SQLITE_ENABLE_STAT4 is omitted.
  56255. */
  56256. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  56257. if( op==TK_REGISTER ) op = pExpr->op2;
  56258. #else
  56259. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  56260. #endif
  56261. /* Handle negative integers in a single step. This is needed in the
  56262. ** case when the value is -9223372036854775808.
  56263. */
  56264. if( op==TK_UMINUS
  56265. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  56266. pExpr = pExpr->pLeft;
  56267. op = pExpr->op;
  56268. negInt = -1;
  56269. zNeg = "-";
  56270. }
  56271. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  56272. pVal = valueNew(db, pCtx);
  56273. if( pVal==0 ) goto no_mem;
  56274. if( ExprHasProperty(pExpr, EP_IntValue) ){
  56275. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  56276. }else{
  56277. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  56278. if( zVal==0 ) goto no_mem;
  56279. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  56280. if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
  56281. }
  56282. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  56283. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  56284. }else{
  56285. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  56286. }
  56287. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  56288. if( enc!=SQLITE_UTF8 ){
  56289. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  56290. }
  56291. }else if( op==TK_UMINUS ) {
  56292. /* This branch happens for multiple negative signs. Ex: -(-5) */
  56293. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  56294. && pVal!=0
  56295. ){
  56296. sqlite3VdbeMemNumerify(pVal);
  56297. if( pVal->u.i==SMALLEST_INT64 ){
  56298. pVal->flags &= MEM_Int;
  56299. pVal->flags |= MEM_Real;
  56300. pVal->r = (double)LARGEST_INT64;
  56301. }else{
  56302. pVal->u.i = -pVal->u.i;
  56303. }
  56304. pVal->r = -pVal->r;
  56305. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  56306. }
  56307. }else if( op==TK_NULL ){
  56308. pVal = valueNew(db, pCtx);
  56309. if( pVal==0 ) goto no_mem;
  56310. }
  56311. #ifndef SQLITE_OMIT_BLOB_LITERAL
  56312. else if( op==TK_BLOB ){
  56313. int nVal;
  56314. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  56315. assert( pExpr->u.zToken[1]=='\'' );
  56316. pVal = valueNew(db, pCtx);
  56317. if( !pVal ) goto no_mem;
  56318. zVal = &pExpr->u.zToken[2];
  56319. nVal = sqlite3Strlen30(zVal)-1;
  56320. assert( zVal[nVal]=='\'' );
  56321. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  56322. 0, SQLITE_DYNAMIC);
  56323. }
  56324. #endif
  56325. if( pVal ){
  56326. sqlite3VdbeMemStoreType(pVal);
  56327. }
  56328. *ppVal = pVal;
  56329. return rc;
  56330. no_mem:
  56331. db->mallocFailed = 1;
  56332. sqlite3DbFree(db, zVal);
  56333. assert( *ppVal==0 );
  56334. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  56335. if( pCtx==0 ) sqlite3ValueFree(pVal);
  56336. #else
  56337. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  56338. #endif
  56339. return SQLITE_NOMEM;
  56340. }
  56341. /*
  56342. ** Create a new sqlite3_value object, containing the value of pExpr.
  56343. **
  56344. ** This only works for very simple expressions that consist of one constant
  56345. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  56346. ** be converted directly into a value, then the value is allocated and
  56347. ** a pointer written to *ppVal. The caller is responsible for deallocating
  56348. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  56349. ** cannot be converted to a value, then *ppVal is set to NULL.
  56350. */
  56351. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  56352. sqlite3 *db, /* The database connection */
  56353. Expr *pExpr, /* The expression to evaluate */
  56354. u8 enc, /* Encoding to use */
  56355. u8 affinity, /* Affinity to use */
  56356. sqlite3_value **ppVal /* Write the new value here */
  56357. ){
  56358. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  56359. }
  56360. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  56361. /*
  56362. ** The implementation of the sqlite_record() function. This function accepts
  56363. ** a single argument of any type. The return value is a formatted database
  56364. ** record (a blob) containing the argument value.
  56365. **
  56366. ** This is used to convert the value stored in the 'sample' column of the
  56367. ** sqlite_stat3 table to the record format SQLite uses internally.
  56368. */
  56369. static void recordFunc(
  56370. sqlite3_context *context,
  56371. int argc,
  56372. sqlite3_value **argv
  56373. ){
  56374. const int file_format = 1;
  56375. int iSerial; /* Serial type */
  56376. int nSerial; /* Bytes of space for iSerial as varint */
  56377. int nVal; /* Bytes of space required for argv[0] */
  56378. int nRet;
  56379. sqlite3 *db;
  56380. u8 *aRet;
  56381. UNUSED_PARAMETER( argc );
  56382. iSerial = sqlite3VdbeSerialType(argv[0], file_format);
  56383. nSerial = sqlite3VarintLen(iSerial);
  56384. nVal = sqlite3VdbeSerialTypeLen(iSerial);
  56385. db = sqlite3_context_db_handle(context);
  56386. nRet = 1 + nSerial + nVal;
  56387. aRet = sqlite3DbMallocRaw(db, nRet);
  56388. if( aRet==0 ){
  56389. sqlite3_result_error_nomem(context);
  56390. }else{
  56391. aRet[0] = nSerial+1;
  56392. sqlite3PutVarint(&aRet[1], iSerial);
  56393. sqlite3VdbeSerialPut(&aRet[1+nSerial], nVal, argv[0], file_format);
  56394. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  56395. sqlite3DbFree(db, aRet);
  56396. }
  56397. }
  56398. /*
  56399. ** Register built-in functions used to help read ANALYZE data.
  56400. */
  56401. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  56402. static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
  56403. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  56404. };
  56405. int i;
  56406. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  56407. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
  56408. for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
  56409. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  56410. }
  56411. }
  56412. /*
  56413. ** This function is used to allocate and populate UnpackedRecord
  56414. ** structures intended to be compared against sample index keys stored
  56415. ** in the sqlite_stat4 table.
  56416. **
  56417. ** A single call to this function attempts to populates field iVal (leftmost
  56418. ** is 0 etc.) of the unpacked record with a value extracted from expression
  56419. ** pExpr. Extraction of values is possible if:
  56420. **
  56421. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  56422. **
  56423. ** * The expression is a bound variable, and this is a reprepare, or
  56424. **
  56425. ** * The sqlite3ValueFromExpr() function is able to extract a value
  56426. ** from the expression (i.e. the expression is a literal value).
  56427. **
  56428. ** If a value can be extracted, the affinity passed as the 5th argument
  56429. ** is applied to it before it is copied into the UnpackedRecord. Output
  56430. ** parameter *pbOk is set to true if a value is extracted, or false
  56431. ** otherwise.
  56432. **
  56433. ** When this function is called, *ppRec must either point to an object
  56434. ** allocated by an earlier call to this function, or must be NULL. If it
  56435. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  56436. ** is allocated (and *ppRec set to point to it) before returning.
  56437. **
  56438. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  56439. ** error if a value cannot be extracted from pExpr. If an error does
  56440. ** occur, an SQLite error code is returned.
  56441. */
  56442. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  56443. Parse *pParse, /* Parse context */
  56444. Index *pIdx, /* Index being probed */
  56445. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  56446. Expr *pExpr, /* The expression to extract a value from */
  56447. u8 affinity, /* Affinity to use */
  56448. int iVal, /* Array element to populate */
  56449. int *pbOk /* OUT: True if value was extracted */
  56450. ){
  56451. int rc = SQLITE_OK;
  56452. sqlite3_value *pVal = 0;
  56453. sqlite3 *db = pParse->db;
  56454. struct ValueNewStat4Ctx alloc;
  56455. alloc.pParse = pParse;
  56456. alloc.pIdx = pIdx;
  56457. alloc.ppRec = ppRec;
  56458. alloc.iVal = iVal;
  56459. /* Skip over any TK_COLLATE nodes */
  56460. pExpr = sqlite3ExprSkipCollate(pExpr);
  56461. if( !pExpr ){
  56462. pVal = valueNew(db, &alloc);
  56463. if( pVal ){
  56464. sqlite3VdbeMemSetNull((Mem*)pVal);
  56465. *pbOk = 1;
  56466. }
  56467. }else if( pExpr->op==TK_VARIABLE
  56468. || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  56469. ){
  56470. Vdbe *v;
  56471. int iBindVar = pExpr->iColumn;
  56472. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  56473. if( (v = pParse->pReprepare)!=0 ){
  56474. pVal = valueNew(db, &alloc);
  56475. if( pVal ){
  56476. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  56477. if( rc==SQLITE_OK ){
  56478. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  56479. }
  56480. pVal->db = pParse->db;
  56481. *pbOk = 1;
  56482. sqlite3VdbeMemStoreType((Mem*)pVal);
  56483. }
  56484. }else{
  56485. *pbOk = 0;
  56486. }
  56487. }else{
  56488. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, &alloc);
  56489. *pbOk = (pVal!=0);
  56490. }
  56491. assert( pVal==0 || pVal->db==db );
  56492. return rc;
  56493. }
  56494. /*
  56495. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  56496. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  56497. ** the object.
  56498. */
  56499. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  56500. if( pRec ){
  56501. int i;
  56502. int nCol = pRec->pKeyInfo->nField+1;
  56503. Mem *aMem = pRec->aMem;
  56504. sqlite3 *db = aMem[0].db;
  56505. for(i=0; i<nCol; i++){
  56506. sqlite3DbFree(db, aMem[i].zMalloc);
  56507. }
  56508. sqlite3DbFree(db, pRec->pKeyInfo);
  56509. sqlite3DbFree(db, pRec);
  56510. }
  56511. }
  56512. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  56513. /*
  56514. ** Change the string value of an sqlite3_value object
  56515. */
  56516. SQLITE_PRIVATE void sqlite3ValueSetStr(
  56517. sqlite3_value *v, /* Value to be set */
  56518. int n, /* Length of string z */
  56519. const void *z, /* Text of the new string */
  56520. u8 enc, /* Encoding to use */
  56521. void (*xDel)(void*) /* Destructor for the string */
  56522. ){
  56523. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  56524. }
  56525. /*
  56526. ** Free an sqlite3_value object
  56527. */
  56528. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  56529. if( !v ) return;
  56530. sqlite3VdbeMemRelease((Mem *)v);
  56531. sqlite3DbFree(((Mem*)v)->db, v);
  56532. }
  56533. /*
  56534. ** Return the number of bytes in the sqlite3_value object assuming
  56535. ** that it uses the encoding "enc"
  56536. */
  56537. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  56538. Mem *p = (Mem*)pVal;
  56539. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  56540. if( p->flags & MEM_Zero ){
  56541. return p->n + p->u.nZero;
  56542. }else{
  56543. return p->n;
  56544. }
  56545. }
  56546. return 0;
  56547. }
  56548. /************** End of vdbemem.c *********************************************/
  56549. /************** Begin file vdbeaux.c *****************************************/
  56550. /*
  56551. ** 2003 September 6
  56552. **
  56553. ** The author disclaims copyright to this source code. In place of
  56554. ** a legal notice, here is a blessing:
  56555. **
  56556. ** May you do good and not evil.
  56557. ** May you find forgiveness for yourself and forgive others.
  56558. ** May you share freely, never taking more than you give.
  56559. **
  56560. *************************************************************************
  56561. ** This file contains code used for creating, destroying, and populating
  56562. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
  56563. ** to version 2.8.7, all this code was combined into the vdbe.c source file.
  56564. ** But that file was getting too big so this subroutines were split out.
  56565. */
  56566. /*
  56567. ** Create a new virtual database engine.
  56568. */
  56569. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  56570. Vdbe *p;
  56571. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  56572. if( p==0 ) return 0;
  56573. p->db = db;
  56574. if( db->pVdbe ){
  56575. db->pVdbe->pPrev = p;
  56576. }
  56577. p->pNext = db->pVdbe;
  56578. p->pPrev = 0;
  56579. db->pVdbe = p;
  56580. p->magic = VDBE_MAGIC_INIT;
  56581. return p;
  56582. }
  56583. /*
  56584. ** Remember the SQL string for a prepared statement.
  56585. */
  56586. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  56587. assert( isPrepareV2==1 || isPrepareV2==0 );
  56588. if( p==0 ) return;
  56589. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  56590. if( !isPrepareV2 ) return;
  56591. #endif
  56592. assert( p->zSql==0 );
  56593. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  56594. p->isPrepareV2 = (u8)isPrepareV2;
  56595. }
  56596. /*
  56597. ** Return the SQL associated with a prepared statement
  56598. */
  56599. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  56600. Vdbe *p = (Vdbe *)pStmt;
  56601. return (p && p->isPrepareV2) ? p->zSql : 0;
  56602. }
  56603. /*
  56604. ** Swap all content between two VDBE structures.
  56605. */
  56606. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  56607. Vdbe tmp, *pTmp;
  56608. char *zTmp;
  56609. tmp = *pA;
  56610. *pA = *pB;
  56611. *pB = tmp;
  56612. pTmp = pA->pNext;
  56613. pA->pNext = pB->pNext;
  56614. pB->pNext = pTmp;
  56615. pTmp = pA->pPrev;
  56616. pA->pPrev = pB->pPrev;
  56617. pB->pPrev = pTmp;
  56618. zTmp = pA->zSql;
  56619. pA->zSql = pB->zSql;
  56620. pB->zSql = zTmp;
  56621. pB->isPrepareV2 = pA->isPrepareV2;
  56622. }
  56623. #ifdef SQLITE_DEBUG
  56624. /*
  56625. ** Turn tracing on or off
  56626. */
  56627. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  56628. p->trace = trace;
  56629. }
  56630. #endif
  56631. /*
  56632. ** Resize the Vdbe.aOp array so that it is at least one op larger than
  56633. ** it was.
  56634. **
  56635. ** If an out-of-memory error occurs while resizing the array, return
  56636. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  56637. ** unchanged (this is so that any opcodes already allocated can be
  56638. ** correctly deallocated along with the rest of the Vdbe).
  56639. */
  56640. static int growOpArray(Vdbe *p){
  56641. VdbeOp *pNew;
  56642. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  56643. pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
  56644. if( pNew ){
  56645. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  56646. p->aOp = pNew;
  56647. }
  56648. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  56649. }
  56650. /*
  56651. ** Add a new instruction to the list of instructions current in the
  56652. ** VDBE. Return the address of the new instruction.
  56653. **
  56654. ** Parameters:
  56655. **
  56656. ** p Pointer to the VDBE
  56657. **
  56658. ** op The opcode for this instruction
  56659. **
  56660. ** p1, p2, p3 Operands
  56661. **
  56662. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  56663. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  56664. ** operand.
  56665. */
  56666. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  56667. int i;
  56668. VdbeOp *pOp;
  56669. i = p->nOp;
  56670. assert( p->magic==VDBE_MAGIC_INIT );
  56671. assert( op>0 && op<0xff );
  56672. if( p->nOpAlloc<=i ){
  56673. if( growOpArray(p) ){
  56674. return 1;
  56675. }
  56676. }
  56677. p->nOp++;
  56678. pOp = &p->aOp[i];
  56679. pOp->opcode = (u8)op;
  56680. pOp->p5 = 0;
  56681. pOp->p1 = p1;
  56682. pOp->p2 = p2;
  56683. pOp->p3 = p3;
  56684. pOp->p4.p = 0;
  56685. pOp->p4type = P4_NOTUSED;
  56686. #ifdef SQLITE_DEBUG
  56687. pOp->zComment = 0;
  56688. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  56689. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  56690. }
  56691. #endif
  56692. #ifdef VDBE_PROFILE
  56693. pOp->cycles = 0;
  56694. pOp->cnt = 0;
  56695. #endif
  56696. return i;
  56697. }
  56698. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  56699. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  56700. }
  56701. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  56702. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  56703. }
  56704. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  56705. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  56706. }
  56707. /*
  56708. ** Add an opcode that includes the p4 value as a pointer.
  56709. */
  56710. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  56711. Vdbe *p, /* Add the opcode to this VM */
  56712. int op, /* The new opcode */
  56713. int p1, /* The P1 operand */
  56714. int p2, /* The P2 operand */
  56715. int p3, /* The P3 operand */
  56716. const char *zP4, /* The P4 operand */
  56717. int p4type /* P4 operand type */
  56718. ){
  56719. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  56720. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  56721. return addr;
  56722. }
  56723. /*
  56724. ** Add an OP_ParseSchema opcode. This routine is broken out from
  56725. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  56726. ** as having been used.
  56727. **
  56728. ** The zWhere string must have been obtained from sqlite3_malloc().
  56729. ** This routine will take ownership of the allocated memory.
  56730. */
  56731. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  56732. int j;
  56733. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  56734. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  56735. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  56736. }
  56737. /*
  56738. ** Add an opcode that includes the p4 value as an integer.
  56739. */
  56740. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  56741. Vdbe *p, /* Add the opcode to this VM */
  56742. int op, /* The new opcode */
  56743. int p1, /* The P1 operand */
  56744. int p2, /* The P2 operand */
  56745. int p3, /* The P3 operand */
  56746. int p4 /* The P4 operand as an integer */
  56747. ){
  56748. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  56749. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  56750. return addr;
  56751. }
  56752. /*
  56753. ** Create a new symbolic label for an instruction that has yet to be
  56754. ** coded. The symbolic label is really just a negative number. The
  56755. ** label can be used as the P2 value of an operation. Later, when
  56756. ** the label is resolved to a specific address, the VDBE will scan
  56757. ** through its operation list and change all values of P2 which match
  56758. ** the label into the resolved address.
  56759. **
  56760. ** The VDBE knows that a P2 value is a label because labels are
  56761. ** always negative and P2 values are suppose to be non-negative.
  56762. ** Hence, a negative P2 value is a label that has yet to be resolved.
  56763. **
  56764. ** Zero is returned if a malloc() fails.
  56765. */
  56766. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
  56767. int i = p->nLabel++;
  56768. assert( p->magic==VDBE_MAGIC_INIT );
  56769. if( (i & (i-1))==0 ){
  56770. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  56771. (i*2+1)*sizeof(p->aLabel[0]));
  56772. }
  56773. if( p->aLabel ){
  56774. p->aLabel[i] = -1;
  56775. }
  56776. return -1-i;
  56777. }
  56778. /*
  56779. ** Resolve label "x" to be the address of the next instruction to
  56780. ** be inserted. The parameter "x" must have been obtained from
  56781. ** a prior call to sqlite3VdbeMakeLabel().
  56782. */
  56783. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  56784. int j = -1-x;
  56785. assert( p->magic==VDBE_MAGIC_INIT );
  56786. assert( j<p->nLabel );
  56787. if( j>=0 && p->aLabel ){
  56788. p->aLabel[j] = p->nOp;
  56789. }
  56790. }
  56791. /*
  56792. ** Mark the VDBE as one that can only be run one time.
  56793. */
  56794. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  56795. p->runOnlyOnce = 1;
  56796. }
  56797. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  56798. /*
  56799. ** The following type and function are used to iterate through all opcodes
  56800. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  56801. ** invoke directly or indirectly. It should be used as follows:
  56802. **
  56803. ** Op *pOp;
  56804. ** VdbeOpIter sIter;
  56805. **
  56806. ** memset(&sIter, 0, sizeof(sIter));
  56807. ** sIter.v = v; // v is of type Vdbe*
  56808. ** while( (pOp = opIterNext(&sIter)) ){
  56809. ** // Do something with pOp
  56810. ** }
  56811. ** sqlite3DbFree(v->db, sIter.apSub);
  56812. **
  56813. */
  56814. typedef struct VdbeOpIter VdbeOpIter;
  56815. struct VdbeOpIter {
  56816. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  56817. SubProgram **apSub; /* Array of subprograms */
  56818. int nSub; /* Number of entries in apSub */
  56819. int iAddr; /* Address of next instruction to return */
  56820. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  56821. };
  56822. static Op *opIterNext(VdbeOpIter *p){
  56823. Vdbe *v = p->v;
  56824. Op *pRet = 0;
  56825. Op *aOp;
  56826. int nOp;
  56827. if( p->iSub<=p->nSub ){
  56828. if( p->iSub==0 ){
  56829. aOp = v->aOp;
  56830. nOp = v->nOp;
  56831. }else{
  56832. aOp = p->apSub[p->iSub-1]->aOp;
  56833. nOp = p->apSub[p->iSub-1]->nOp;
  56834. }
  56835. assert( p->iAddr<nOp );
  56836. pRet = &aOp[p->iAddr];
  56837. p->iAddr++;
  56838. if( p->iAddr==nOp ){
  56839. p->iSub++;
  56840. p->iAddr = 0;
  56841. }
  56842. if( pRet->p4type==P4_SUBPROGRAM ){
  56843. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  56844. int j;
  56845. for(j=0; j<p->nSub; j++){
  56846. if( p->apSub[j]==pRet->p4.pProgram ) break;
  56847. }
  56848. if( j==p->nSub ){
  56849. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  56850. if( !p->apSub ){
  56851. pRet = 0;
  56852. }else{
  56853. p->apSub[p->nSub++] = pRet->p4.pProgram;
  56854. }
  56855. }
  56856. }
  56857. }
  56858. return pRet;
  56859. }
  56860. /*
  56861. ** Check if the program stored in the VM associated with pParse may
  56862. ** throw an ABORT exception (causing the statement, but not entire transaction
  56863. ** to be rolled back). This condition is true if the main program or any
  56864. ** sub-programs contains any of the following:
  56865. **
  56866. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  56867. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  56868. ** * OP_Destroy
  56869. ** * OP_VUpdate
  56870. ** * OP_VRename
  56871. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  56872. **
  56873. ** Then check that the value of Parse.mayAbort is true if an
  56874. ** ABORT may be thrown, or false otherwise. Return true if it does
  56875. ** match, or false otherwise. This function is intended to be used as
  56876. ** part of an assert statement in the compiler. Similar to:
  56877. **
  56878. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  56879. */
  56880. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  56881. int hasAbort = 0;
  56882. Op *pOp;
  56883. VdbeOpIter sIter;
  56884. memset(&sIter, 0, sizeof(sIter));
  56885. sIter.v = v;
  56886. while( (pOp = opIterNext(&sIter))!=0 ){
  56887. int opcode = pOp->opcode;
  56888. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  56889. #ifndef SQLITE_OMIT_FOREIGN_KEY
  56890. || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
  56891. #endif
  56892. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  56893. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  56894. ){
  56895. hasAbort = 1;
  56896. break;
  56897. }
  56898. }
  56899. sqlite3DbFree(v->db, sIter.apSub);
  56900. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  56901. ** If malloc failed, then the while() loop above may not have iterated
  56902. ** through all opcodes and hasAbort may be set incorrectly. Return
  56903. ** true for this case to prevent the assert() in the callers frame
  56904. ** from failing. */
  56905. return ( v->db->mallocFailed || hasAbort==mayAbort );
  56906. }
  56907. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  56908. /*
  56909. ** Loop through the program looking for P2 values that are negative
  56910. ** on jump instructions. Each such value is a label. Resolve the
  56911. ** label by setting the P2 value to its correct non-zero value.
  56912. **
  56913. ** This routine is called once after all opcodes have been inserted.
  56914. **
  56915. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  56916. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  56917. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  56918. **
  56919. ** The Op.opflags field is set on all opcodes.
  56920. */
  56921. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  56922. int i;
  56923. int nMaxArgs = *pMaxFuncArgs;
  56924. Op *pOp;
  56925. int *aLabel = p->aLabel;
  56926. p->readOnly = 1;
  56927. p->bIsReader = 0;
  56928. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  56929. u8 opcode = pOp->opcode;
  56930. /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
  56931. ** cases from this switch! */
  56932. switch( opcode ){
  56933. case OP_Function:
  56934. case OP_AggStep: {
  56935. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  56936. break;
  56937. }
  56938. case OP_Transaction: {
  56939. if( pOp->p2!=0 ) p->readOnly = 0;
  56940. /* fall thru */
  56941. }
  56942. case OP_AutoCommit:
  56943. case OP_Savepoint: {
  56944. p->bIsReader = 1;
  56945. break;
  56946. }
  56947. #ifndef SQLITE_OMIT_WAL
  56948. case OP_Checkpoint:
  56949. #endif
  56950. case OP_Vacuum:
  56951. case OP_JournalMode: {
  56952. p->readOnly = 0;
  56953. p->bIsReader = 1;
  56954. break;
  56955. }
  56956. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56957. case OP_VUpdate: {
  56958. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  56959. break;
  56960. }
  56961. case OP_VFilter: {
  56962. int n;
  56963. assert( p->nOp - i >= 3 );
  56964. assert( pOp[-1].opcode==OP_Integer );
  56965. n = pOp[-1].p1;
  56966. if( n>nMaxArgs ) nMaxArgs = n;
  56967. break;
  56968. }
  56969. #endif
  56970. case OP_Next:
  56971. case OP_SorterNext: {
  56972. pOp->p4.xAdvance = sqlite3BtreeNext;
  56973. pOp->p4type = P4_ADVANCE;
  56974. break;
  56975. }
  56976. case OP_Prev: {
  56977. pOp->p4.xAdvance = sqlite3BtreePrevious;
  56978. pOp->p4type = P4_ADVANCE;
  56979. break;
  56980. }
  56981. }
  56982. pOp->opflags = sqlite3OpcodeProperty[opcode];
  56983. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  56984. assert( -1-pOp->p2<p->nLabel );
  56985. pOp->p2 = aLabel[-1-pOp->p2];
  56986. }
  56987. }
  56988. sqlite3DbFree(p->db, p->aLabel);
  56989. p->aLabel = 0;
  56990. *pMaxFuncArgs = nMaxArgs;
  56991. assert( p->bIsReader!=0 || p->btreeMask==0 );
  56992. }
  56993. /*
  56994. ** Return the address of the next instruction to be inserted.
  56995. */
  56996. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  56997. assert( p->magic==VDBE_MAGIC_INIT );
  56998. return p->nOp;
  56999. }
  57000. /*
  57001. ** This function returns a pointer to the array of opcodes associated with
  57002. ** the Vdbe passed as the first argument. It is the callers responsibility
  57003. ** to arrange for the returned array to be eventually freed using the
  57004. ** vdbeFreeOpArray() function.
  57005. **
  57006. ** Before returning, *pnOp is set to the number of entries in the returned
  57007. ** array. Also, *pnMaxArg is set to the larger of its current value and
  57008. ** the number of entries in the Vdbe.apArg[] array required to execute the
  57009. ** returned program.
  57010. */
  57011. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  57012. VdbeOp *aOp = p->aOp;
  57013. assert( aOp && !p->db->mallocFailed );
  57014. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  57015. assert( p->btreeMask==0 );
  57016. resolveP2Values(p, pnMaxArg);
  57017. *pnOp = p->nOp;
  57018. p->aOp = 0;
  57019. return aOp;
  57020. }
  57021. /*
  57022. ** Add a whole list of operations to the operation stack. Return the
  57023. ** address of the first operation added.
  57024. */
  57025. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  57026. int addr;
  57027. assert( p->magic==VDBE_MAGIC_INIT );
  57028. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
  57029. return 0;
  57030. }
  57031. addr = p->nOp;
  57032. if( ALWAYS(nOp>0) ){
  57033. int i;
  57034. VdbeOpList const *pIn = aOp;
  57035. for(i=0; i<nOp; i++, pIn++){
  57036. int p2 = pIn->p2;
  57037. VdbeOp *pOut = &p->aOp[i+addr];
  57038. pOut->opcode = pIn->opcode;
  57039. pOut->p1 = pIn->p1;
  57040. if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
  57041. pOut->p2 = addr + ADDR(p2);
  57042. }else{
  57043. pOut->p2 = p2;
  57044. }
  57045. pOut->p3 = pIn->p3;
  57046. pOut->p4type = P4_NOTUSED;
  57047. pOut->p4.p = 0;
  57048. pOut->p5 = 0;
  57049. #ifdef SQLITE_DEBUG
  57050. pOut->zComment = 0;
  57051. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  57052. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  57053. }
  57054. #endif
  57055. }
  57056. p->nOp += nOp;
  57057. }
  57058. return addr;
  57059. }
  57060. /*
  57061. ** Change the value of the P1 operand for a specific instruction.
  57062. ** This routine is useful when a large program is loaded from a
  57063. ** static array using sqlite3VdbeAddOpList but we want to make a
  57064. ** few minor changes to the program.
  57065. */
  57066. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  57067. assert( p!=0 );
  57068. if( ((u32)p->nOp)>addr ){
  57069. p->aOp[addr].p1 = val;
  57070. }
  57071. }
  57072. /*
  57073. ** Change the value of the P2 operand for a specific instruction.
  57074. ** This routine is useful for setting a jump destination.
  57075. */
  57076. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  57077. assert( p!=0 );
  57078. if( ((u32)p->nOp)>addr ){
  57079. p->aOp[addr].p2 = val;
  57080. }
  57081. }
  57082. /*
  57083. ** Change the value of the P3 operand for a specific instruction.
  57084. */
  57085. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  57086. assert( p!=0 );
  57087. if( ((u32)p->nOp)>addr ){
  57088. p->aOp[addr].p3 = val;
  57089. }
  57090. }
  57091. /*
  57092. ** Change the value of the P5 operand for the most recently
  57093. ** added operation.
  57094. */
  57095. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  57096. assert( p!=0 );
  57097. if( p->aOp ){
  57098. assert( p->nOp>0 );
  57099. p->aOp[p->nOp-1].p5 = val;
  57100. }
  57101. }
  57102. /*
  57103. ** Change the P2 operand of instruction addr so that it points to
  57104. ** the address of the next instruction to be coded.
  57105. */
  57106. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  57107. if( ALWAYS(addr>=0) ) sqlite3VdbeChangeP2(p, addr, p->nOp);
  57108. }
  57109. /*
  57110. ** If the input FuncDef structure is ephemeral, then free it. If
  57111. ** the FuncDef is not ephermal, then do nothing.
  57112. */
  57113. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  57114. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  57115. sqlite3DbFree(db, pDef);
  57116. }
  57117. }
  57118. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  57119. /*
  57120. ** Delete a P4 value if necessary.
  57121. */
  57122. static void freeP4(sqlite3 *db, int p4type, void *p4){
  57123. if( p4 ){
  57124. assert( db );
  57125. switch( p4type ){
  57126. case P4_REAL:
  57127. case P4_INT64:
  57128. case P4_DYNAMIC:
  57129. case P4_KEYINFO:
  57130. case P4_INTARRAY:
  57131. case P4_KEYINFO_HANDOFF: {
  57132. sqlite3DbFree(db, p4);
  57133. break;
  57134. }
  57135. case P4_MPRINTF: {
  57136. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  57137. break;
  57138. }
  57139. case P4_FUNCDEF: {
  57140. freeEphemeralFunction(db, (FuncDef*)p4);
  57141. break;
  57142. }
  57143. case P4_MEM: {
  57144. if( db->pnBytesFreed==0 ){
  57145. sqlite3ValueFree((sqlite3_value*)p4);
  57146. }else{
  57147. Mem *p = (Mem*)p4;
  57148. sqlite3DbFree(db, p->zMalloc);
  57149. sqlite3DbFree(db, p);
  57150. }
  57151. break;
  57152. }
  57153. case P4_VTAB : {
  57154. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  57155. break;
  57156. }
  57157. }
  57158. }
  57159. }
  57160. /*
  57161. ** Free the space allocated for aOp and any p4 values allocated for the
  57162. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  57163. ** nOp entries.
  57164. */
  57165. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  57166. if( aOp ){
  57167. Op *pOp;
  57168. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  57169. freeP4(db, pOp->p4type, pOp->p4.p);
  57170. #ifdef SQLITE_DEBUG
  57171. sqlite3DbFree(db, pOp->zComment);
  57172. #endif
  57173. }
  57174. }
  57175. sqlite3DbFree(db, aOp);
  57176. }
  57177. /*
  57178. ** Link the SubProgram object passed as the second argument into the linked
  57179. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  57180. ** objects when the VM is no longer required.
  57181. */
  57182. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  57183. p->pNext = pVdbe->pProgram;
  57184. pVdbe->pProgram = p;
  57185. }
  57186. /*
  57187. ** Change the opcode at addr into OP_Noop
  57188. */
  57189. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  57190. if( p->aOp ){
  57191. VdbeOp *pOp = &p->aOp[addr];
  57192. sqlite3 *db = p->db;
  57193. freeP4(db, pOp->p4type, pOp->p4.p);
  57194. memset(pOp, 0, sizeof(pOp[0]));
  57195. pOp->opcode = OP_Noop;
  57196. }
  57197. }
  57198. /*
  57199. ** Change the value of the P4 operand for a specific instruction.
  57200. ** This routine is useful when a large program is loaded from a
  57201. ** static array using sqlite3VdbeAddOpList but we want to make a
  57202. ** few minor changes to the program.
  57203. **
  57204. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  57205. ** the string is made into memory obtained from sqlite3_malloc().
  57206. ** A value of n==0 means copy bytes of zP4 up to and including the
  57207. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  57208. **
  57209. ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
  57210. ** A copy is made of the KeyInfo structure into memory obtained from
  57211. ** sqlite3_malloc, to be freed when the Vdbe is finalized.
  57212. ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
  57213. ** stored in memory that the caller has obtained from sqlite3_malloc. The
  57214. ** caller should not free the allocation, it will be freed when the Vdbe is
  57215. ** finalized.
  57216. **
  57217. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  57218. ** to a string or structure that is guaranteed to exist for the lifetime of
  57219. ** the Vdbe. In these cases we can just copy the pointer.
  57220. **
  57221. ** If addr<0 then change P4 on the most recently inserted instruction.
  57222. */
  57223. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  57224. Op *pOp;
  57225. sqlite3 *db;
  57226. assert( p!=0 );
  57227. db = p->db;
  57228. assert( p->magic==VDBE_MAGIC_INIT );
  57229. if( p->aOp==0 || db->mallocFailed ){
  57230. if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
  57231. freeP4(db, n, (void*)*(char**)&zP4);
  57232. }
  57233. return;
  57234. }
  57235. assert( p->nOp>0 );
  57236. assert( addr<p->nOp );
  57237. if( addr<0 ){
  57238. addr = p->nOp - 1;
  57239. }
  57240. pOp = &p->aOp[addr];
  57241. assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
  57242. freeP4(db, pOp->p4type, pOp->p4.p);
  57243. pOp->p4.p = 0;
  57244. if( n==P4_INT32 ){
  57245. /* Note: this cast is safe, because the origin data point was an int
  57246. ** that was cast to a (const char *). */
  57247. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  57248. pOp->p4type = P4_INT32;
  57249. }else if( zP4==0 ){
  57250. pOp->p4.p = 0;
  57251. pOp->p4type = P4_NOTUSED;
  57252. }else if( n==P4_KEYINFO ){
  57253. KeyInfo *pOrig, *pNew;
  57254. pOrig = (KeyInfo*)zP4;
  57255. pOp->p4.pKeyInfo = pNew = sqlite3KeyInfoAlloc(db, pOrig->nField);
  57256. if( pNew ){
  57257. memcpy(pNew->aColl, pOrig->aColl, pOrig->nField*sizeof(pNew->aColl[0]));
  57258. memcpy(pNew->aSortOrder, pOrig->aSortOrder, pOrig->nField);
  57259. pOp->p4type = P4_KEYINFO;
  57260. }else{
  57261. p->db->mallocFailed = 1;
  57262. pOp->p4type = P4_NOTUSED;
  57263. }
  57264. }else if( n==P4_KEYINFO_HANDOFF ){
  57265. pOp->p4.p = (void*)zP4;
  57266. pOp->p4type = P4_KEYINFO;
  57267. }else if( n==P4_VTAB ){
  57268. pOp->p4.p = (void*)zP4;
  57269. pOp->p4type = P4_VTAB;
  57270. sqlite3VtabLock((VTable *)zP4);
  57271. assert( ((VTable *)zP4)->db==p->db );
  57272. }else if( n<0 ){
  57273. pOp->p4.p = (void*)zP4;
  57274. pOp->p4type = (signed char)n;
  57275. }else{
  57276. if( n==0 ) n = sqlite3Strlen30(zP4);
  57277. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  57278. pOp->p4type = P4_DYNAMIC;
  57279. }
  57280. }
  57281. #ifndef NDEBUG
  57282. /*
  57283. ** Change the comment on the most recently coded instruction. Or
  57284. ** insert a No-op and add the comment to that new instruction. This
  57285. ** makes the code easier to read during debugging. None of this happens
  57286. ** in a production build.
  57287. */
  57288. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  57289. assert( p->nOp>0 || p->aOp==0 );
  57290. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  57291. if( p->nOp ){
  57292. assert( p->aOp );
  57293. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  57294. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  57295. }
  57296. }
  57297. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  57298. va_list ap;
  57299. if( p ){
  57300. va_start(ap, zFormat);
  57301. vdbeVComment(p, zFormat, ap);
  57302. va_end(ap);
  57303. }
  57304. }
  57305. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  57306. va_list ap;
  57307. if( p ){
  57308. sqlite3VdbeAddOp0(p, OP_Noop);
  57309. va_start(ap, zFormat);
  57310. vdbeVComment(p, zFormat, ap);
  57311. va_end(ap);
  57312. }
  57313. }
  57314. #endif /* NDEBUG */
  57315. /*
  57316. ** Return the opcode for a given address. If the address is -1, then
  57317. ** return the most recently inserted opcode.
  57318. **
  57319. ** If a memory allocation error has occurred prior to the calling of this
  57320. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  57321. ** is readable but not writable, though it is cast to a writable value.
  57322. ** The return of a dummy opcode allows the call to continue functioning
  57323. ** after a OOM fault without having to check to see if the return from
  57324. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  57325. ** dummy will never be written to. This is verified by code inspection and
  57326. ** by running with Valgrind.
  57327. **
  57328. ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
  57329. ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
  57330. ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
  57331. ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
  57332. ** having to double-check to make sure that the result is non-negative. But
  57333. ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
  57334. ** check the value of p->nOp-1 before continuing.
  57335. */
  57336. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  57337. /* C89 specifies that the constant "dummy" will be initialized to all
  57338. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  57339. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  57340. assert( p->magic==VDBE_MAGIC_INIT );
  57341. if( addr<0 ){
  57342. #ifdef SQLITE_OMIT_TRACE
  57343. if( p->nOp==0 ) return (VdbeOp*)&dummy;
  57344. #endif
  57345. addr = p->nOp - 1;
  57346. }
  57347. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  57348. if( p->db->mallocFailed ){
  57349. return (VdbeOp*)&dummy;
  57350. }else{
  57351. return &p->aOp[addr];
  57352. }
  57353. }
  57354. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  57355. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  57356. /*
  57357. ** Compute a string that describes the P4 parameter for an opcode.
  57358. ** Use zTemp for any required temporary buffer space.
  57359. */
  57360. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  57361. char *zP4 = zTemp;
  57362. assert( nTemp>=20 );
  57363. switch( pOp->p4type ){
  57364. case P4_KEYINFO_STATIC:
  57365. case P4_KEYINFO: {
  57366. int i, j;
  57367. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  57368. assert( pKeyInfo->aSortOrder!=0 );
  57369. sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
  57370. i = sqlite3Strlen30(zTemp);
  57371. for(j=0; j<pKeyInfo->nField; j++){
  57372. CollSeq *pColl = pKeyInfo->aColl[j];
  57373. const char *zColl = pColl ? pColl->zName : "nil";
  57374. int n = sqlite3Strlen30(zColl);
  57375. if( i+n>nTemp-6 ){
  57376. memcpy(&zTemp[i],",...",4);
  57377. break;
  57378. }
  57379. zTemp[i++] = ',';
  57380. if( pKeyInfo->aSortOrder[j] ){
  57381. zTemp[i++] = '-';
  57382. }
  57383. memcpy(&zTemp[i], zColl, n+1);
  57384. i += n;
  57385. }
  57386. zTemp[i++] = ')';
  57387. zTemp[i] = 0;
  57388. assert( i<nTemp );
  57389. break;
  57390. }
  57391. case P4_COLLSEQ: {
  57392. CollSeq *pColl = pOp->p4.pColl;
  57393. sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
  57394. break;
  57395. }
  57396. case P4_FUNCDEF: {
  57397. FuncDef *pDef = pOp->p4.pFunc;
  57398. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  57399. break;
  57400. }
  57401. case P4_INT64: {
  57402. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  57403. break;
  57404. }
  57405. case P4_INT32: {
  57406. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  57407. break;
  57408. }
  57409. case P4_REAL: {
  57410. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  57411. break;
  57412. }
  57413. case P4_MEM: {
  57414. Mem *pMem = pOp->p4.pMem;
  57415. if( pMem->flags & MEM_Str ){
  57416. zP4 = pMem->z;
  57417. }else if( pMem->flags & MEM_Int ){
  57418. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  57419. }else if( pMem->flags & MEM_Real ){
  57420. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
  57421. }else if( pMem->flags & MEM_Null ){
  57422. sqlite3_snprintf(nTemp, zTemp, "NULL");
  57423. }else{
  57424. assert( pMem->flags & MEM_Blob );
  57425. zP4 = "(blob)";
  57426. }
  57427. break;
  57428. }
  57429. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57430. case P4_VTAB: {
  57431. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  57432. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  57433. break;
  57434. }
  57435. #endif
  57436. case P4_INTARRAY: {
  57437. sqlite3_snprintf(nTemp, zTemp, "intarray");
  57438. break;
  57439. }
  57440. case P4_SUBPROGRAM: {
  57441. sqlite3_snprintf(nTemp, zTemp, "program");
  57442. break;
  57443. }
  57444. case P4_ADVANCE: {
  57445. zTemp[0] = 0;
  57446. break;
  57447. }
  57448. default: {
  57449. zP4 = pOp->p4.z;
  57450. if( zP4==0 ){
  57451. zP4 = zTemp;
  57452. zTemp[0] = 0;
  57453. }
  57454. }
  57455. }
  57456. assert( zP4!=0 );
  57457. return zP4;
  57458. }
  57459. #endif
  57460. /*
  57461. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  57462. **
  57463. ** The prepared statements need to know in advance the complete set of
  57464. ** attached databases that will be use. A mask of these databases
  57465. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  57466. ** p->btreeMask of databases that will require a lock.
  57467. */
  57468. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  57469. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  57470. assert( i<(int)sizeof(p->btreeMask)*8 );
  57471. p->btreeMask |= ((yDbMask)1)<<i;
  57472. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  57473. p->lockMask |= ((yDbMask)1)<<i;
  57474. }
  57475. }
  57476. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  57477. /*
  57478. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  57479. ** this routine obtains the mutex associated with each BtShared structure
  57480. ** that may be accessed by the VM passed as an argument. In doing so it also
  57481. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  57482. ** that the correct busy-handler callback is invoked if required.
  57483. **
  57484. ** If SQLite is not threadsafe but does support shared-cache mode, then
  57485. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  57486. ** of all of BtShared structures accessible via the database handle
  57487. ** associated with the VM.
  57488. **
  57489. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  57490. ** function is a no-op.
  57491. **
  57492. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  57493. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  57494. ** corresponding to btrees that use shared cache. Then the runtime of
  57495. ** this routine is N*N. But as N is rarely more than 1, this should not
  57496. ** be a problem.
  57497. */
  57498. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  57499. int i;
  57500. yDbMask mask;
  57501. sqlite3 *db;
  57502. Db *aDb;
  57503. int nDb;
  57504. if( p->lockMask==0 ) return; /* The common case */
  57505. db = p->db;
  57506. aDb = db->aDb;
  57507. nDb = db->nDb;
  57508. for(i=0, mask=1; i<nDb; i++, mask += mask){
  57509. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  57510. sqlite3BtreeEnter(aDb[i].pBt);
  57511. }
  57512. }
  57513. }
  57514. #endif
  57515. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  57516. /*
  57517. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  57518. */
  57519. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  57520. int i;
  57521. yDbMask mask;
  57522. sqlite3 *db;
  57523. Db *aDb;
  57524. int nDb;
  57525. if( p->lockMask==0 ) return; /* The common case */
  57526. db = p->db;
  57527. aDb = db->aDb;
  57528. nDb = db->nDb;
  57529. for(i=0, mask=1; i<nDb; i++, mask += mask){
  57530. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  57531. sqlite3BtreeLeave(aDb[i].pBt);
  57532. }
  57533. }
  57534. }
  57535. #endif
  57536. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  57537. /*
  57538. ** Print a single opcode. This routine is used for debugging only.
  57539. */
  57540. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  57541. char *zP4;
  57542. char zPtr[50];
  57543. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
  57544. if( pOut==0 ) pOut = stdout;
  57545. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  57546. fprintf(pOut, zFormat1, pc,
  57547. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  57548. #ifdef SQLITE_DEBUG
  57549. pOp->zComment ? pOp->zComment : ""
  57550. #else
  57551. ""
  57552. #endif
  57553. );
  57554. fflush(pOut);
  57555. }
  57556. #endif
  57557. /*
  57558. ** Release an array of N Mem elements
  57559. */
  57560. static void releaseMemArray(Mem *p, int N){
  57561. if( p && N ){
  57562. Mem *pEnd;
  57563. sqlite3 *db = p->db;
  57564. u8 malloc_failed = db->mallocFailed;
  57565. if( db->pnBytesFreed ){
  57566. for(pEnd=&p[N]; p<pEnd; p++){
  57567. sqlite3DbFree(db, p->zMalloc);
  57568. }
  57569. return;
  57570. }
  57571. for(pEnd=&p[N]; p<pEnd; p++){
  57572. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  57573. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  57574. ** that takes advantage of the fact that the memory cell value is
  57575. ** being set to NULL after releasing any dynamic resources.
  57576. **
  57577. ** The justification for duplicating code is that according to
  57578. ** callgrind, this causes a certain test case to hit the CPU 4.7
  57579. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  57580. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  57581. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  57582. ** with no indexes using a single prepared INSERT statement, bind()
  57583. ** and reset(). Inserts are grouped into a transaction.
  57584. */
  57585. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  57586. sqlite3VdbeMemRelease(p);
  57587. }else if( p->zMalloc ){
  57588. sqlite3DbFree(db, p->zMalloc);
  57589. p->zMalloc = 0;
  57590. }
  57591. p->flags = MEM_Invalid;
  57592. }
  57593. db->mallocFailed = malloc_failed;
  57594. }
  57595. }
  57596. /*
  57597. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  57598. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  57599. */
  57600. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  57601. int i;
  57602. Mem *aMem = VdbeFrameMem(p);
  57603. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  57604. for(i=0; i<p->nChildCsr; i++){
  57605. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  57606. }
  57607. releaseMemArray(aMem, p->nChildMem);
  57608. sqlite3DbFree(p->v->db, p);
  57609. }
  57610. #ifndef SQLITE_OMIT_EXPLAIN
  57611. /*
  57612. ** Give a listing of the program in the virtual machine.
  57613. **
  57614. ** The interface is the same as sqlite3VdbeExec(). But instead of
  57615. ** running the code, it invokes the callback once for each instruction.
  57616. ** This feature is used to implement "EXPLAIN".
  57617. **
  57618. ** When p->explain==1, each instruction is listed. When
  57619. ** p->explain==2, only OP_Explain instructions are listed and these
  57620. ** are shown in a different format. p->explain==2 is used to implement
  57621. ** EXPLAIN QUERY PLAN.
  57622. **
  57623. ** When p->explain==1, first the main program is listed, then each of
  57624. ** the trigger subprograms are listed one by one.
  57625. */
  57626. SQLITE_PRIVATE int sqlite3VdbeList(
  57627. Vdbe *p /* The VDBE */
  57628. ){
  57629. int nRow; /* Stop when row count reaches this */
  57630. int nSub = 0; /* Number of sub-vdbes seen so far */
  57631. SubProgram **apSub = 0; /* Array of sub-vdbes */
  57632. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  57633. sqlite3 *db = p->db; /* The database connection */
  57634. int i; /* Loop counter */
  57635. int rc = SQLITE_OK; /* Return code */
  57636. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  57637. assert( p->explain );
  57638. assert( p->magic==VDBE_MAGIC_RUN );
  57639. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  57640. /* Even though this opcode does not use dynamic strings for
  57641. ** the result, result columns may become dynamic if the user calls
  57642. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  57643. */
  57644. releaseMemArray(pMem, 8);
  57645. p->pResultSet = 0;
  57646. if( p->rc==SQLITE_NOMEM ){
  57647. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  57648. ** sqlite3_column_text16() failed. */
  57649. db->mallocFailed = 1;
  57650. return SQLITE_ERROR;
  57651. }
  57652. /* When the number of output rows reaches nRow, that means the
  57653. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  57654. ** nRow is the sum of the number of rows in the main program, plus
  57655. ** the sum of the number of rows in all trigger subprograms encountered
  57656. ** so far. The nRow value will increase as new trigger subprograms are
  57657. ** encountered, but p->pc will eventually catch up to nRow.
  57658. */
  57659. nRow = p->nOp;
  57660. if( p->explain==1 ){
  57661. /* The first 8 memory cells are used for the result set. So we will
  57662. ** commandeer the 9th cell to use as storage for an array of pointers
  57663. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  57664. ** cells. */
  57665. assert( p->nMem>9 );
  57666. pSub = &p->aMem[9];
  57667. if( pSub->flags&MEM_Blob ){
  57668. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  57669. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  57670. nSub = pSub->n/sizeof(Vdbe*);
  57671. apSub = (SubProgram **)pSub->z;
  57672. }
  57673. for(i=0; i<nSub; i++){
  57674. nRow += apSub[i]->nOp;
  57675. }
  57676. }
  57677. do{
  57678. i = p->pc++;
  57679. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  57680. if( i>=nRow ){
  57681. p->rc = SQLITE_OK;
  57682. rc = SQLITE_DONE;
  57683. }else if( db->u1.isInterrupted ){
  57684. p->rc = SQLITE_INTERRUPT;
  57685. rc = SQLITE_ERROR;
  57686. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  57687. }else{
  57688. char *z;
  57689. Op *pOp;
  57690. if( i<p->nOp ){
  57691. /* The output line number is small enough that we are still in the
  57692. ** main program. */
  57693. pOp = &p->aOp[i];
  57694. }else{
  57695. /* We are currently listing subprograms. Figure out which one and
  57696. ** pick up the appropriate opcode. */
  57697. int j;
  57698. i -= p->nOp;
  57699. for(j=0; i>=apSub[j]->nOp; j++){
  57700. i -= apSub[j]->nOp;
  57701. }
  57702. pOp = &apSub[j]->aOp[i];
  57703. }
  57704. if( p->explain==1 ){
  57705. pMem->flags = MEM_Int;
  57706. pMem->type = SQLITE_INTEGER;
  57707. pMem->u.i = i; /* Program counter */
  57708. pMem++;
  57709. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  57710. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  57711. assert( pMem->z!=0 );
  57712. pMem->n = sqlite3Strlen30(pMem->z);
  57713. pMem->type = SQLITE_TEXT;
  57714. pMem->enc = SQLITE_UTF8;
  57715. pMem++;
  57716. /* When an OP_Program opcode is encounter (the only opcode that has
  57717. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  57718. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  57719. ** has not already been seen.
  57720. */
  57721. if( pOp->p4type==P4_SUBPROGRAM ){
  57722. int nByte = (nSub+1)*sizeof(SubProgram*);
  57723. int j;
  57724. for(j=0; j<nSub; j++){
  57725. if( apSub[j]==pOp->p4.pProgram ) break;
  57726. }
  57727. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  57728. apSub = (SubProgram **)pSub->z;
  57729. apSub[nSub++] = pOp->p4.pProgram;
  57730. pSub->flags |= MEM_Blob;
  57731. pSub->n = nSub*sizeof(SubProgram*);
  57732. }
  57733. }
  57734. }
  57735. pMem->flags = MEM_Int;
  57736. pMem->u.i = pOp->p1; /* P1 */
  57737. pMem->type = SQLITE_INTEGER;
  57738. pMem++;
  57739. pMem->flags = MEM_Int;
  57740. pMem->u.i = pOp->p2; /* P2 */
  57741. pMem->type = SQLITE_INTEGER;
  57742. pMem++;
  57743. pMem->flags = MEM_Int;
  57744. pMem->u.i = pOp->p3; /* P3 */
  57745. pMem->type = SQLITE_INTEGER;
  57746. pMem++;
  57747. if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
  57748. assert( p->db->mallocFailed );
  57749. return SQLITE_ERROR;
  57750. }
  57751. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  57752. z = displayP4(pOp, pMem->z, 32);
  57753. if( z!=pMem->z ){
  57754. sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
  57755. }else{
  57756. assert( pMem->z!=0 );
  57757. pMem->n = sqlite3Strlen30(pMem->z);
  57758. pMem->enc = SQLITE_UTF8;
  57759. }
  57760. pMem->type = SQLITE_TEXT;
  57761. pMem++;
  57762. if( p->explain==1 ){
  57763. if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
  57764. assert( p->db->mallocFailed );
  57765. return SQLITE_ERROR;
  57766. }
  57767. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  57768. pMem->n = 2;
  57769. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  57770. pMem->type = SQLITE_TEXT;
  57771. pMem->enc = SQLITE_UTF8;
  57772. pMem++;
  57773. #ifdef SQLITE_DEBUG
  57774. if( pOp->zComment ){
  57775. pMem->flags = MEM_Str|MEM_Term;
  57776. pMem->z = pOp->zComment;
  57777. pMem->n = sqlite3Strlen30(pMem->z);
  57778. pMem->enc = SQLITE_UTF8;
  57779. pMem->type = SQLITE_TEXT;
  57780. }else
  57781. #endif
  57782. {
  57783. pMem->flags = MEM_Null; /* Comment */
  57784. pMem->type = SQLITE_NULL;
  57785. }
  57786. }
  57787. p->nResColumn = 8 - 4*(p->explain-1);
  57788. p->pResultSet = &p->aMem[1];
  57789. p->rc = SQLITE_OK;
  57790. rc = SQLITE_ROW;
  57791. }
  57792. return rc;
  57793. }
  57794. #endif /* SQLITE_OMIT_EXPLAIN */
  57795. #ifdef SQLITE_DEBUG
  57796. /*
  57797. ** Print the SQL that was used to generate a VDBE program.
  57798. */
  57799. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  57800. int nOp = p->nOp;
  57801. VdbeOp *pOp;
  57802. if( nOp<1 ) return;
  57803. pOp = &p->aOp[0];
  57804. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  57805. const char *z = pOp->p4.z;
  57806. while( sqlite3Isspace(*z) ) z++;
  57807. printf("SQL: [%s]\n", z);
  57808. }
  57809. }
  57810. #endif
  57811. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  57812. /*
  57813. ** Print an IOTRACE message showing SQL content.
  57814. */
  57815. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  57816. int nOp = p->nOp;
  57817. VdbeOp *pOp;
  57818. if( sqlite3IoTrace==0 ) return;
  57819. if( nOp<1 ) return;
  57820. pOp = &p->aOp[0];
  57821. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  57822. int i, j;
  57823. char z[1000];
  57824. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  57825. for(i=0; sqlite3Isspace(z[i]); i++){}
  57826. for(j=0; z[i]; i++){
  57827. if( sqlite3Isspace(z[i]) ){
  57828. if( z[i-1]!=' ' ){
  57829. z[j++] = ' ';
  57830. }
  57831. }else{
  57832. z[j++] = z[i];
  57833. }
  57834. }
  57835. z[j] = 0;
  57836. sqlite3IoTrace("SQL %s\n", z);
  57837. }
  57838. }
  57839. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  57840. /*
  57841. ** Allocate space from a fixed size buffer and return a pointer to
  57842. ** that space. If insufficient space is available, return NULL.
  57843. **
  57844. ** The pBuf parameter is the initial value of a pointer which will
  57845. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  57846. ** NULL, it means that memory space has already been allocated and that
  57847. ** this routine should not allocate any new memory. When pBuf is not
  57848. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  57849. ** is NULL.
  57850. **
  57851. ** nByte is the number of bytes of space needed.
  57852. **
  57853. ** *ppFrom points to available space and pEnd points to the end of the
  57854. ** available space. When space is allocated, *ppFrom is advanced past
  57855. ** the end of the allocated space.
  57856. **
  57857. ** *pnByte is a counter of the number of bytes of space that have failed
  57858. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  57859. ** request, then increment *pnByte by the amount of the request.
  57860. */
  57861. static void *allocSpace(
  57862. void *pBuf, /* Where return pointer will be stored */
  57863. int nByte, /* Number of bytes to allocate */
  57864. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  57865. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  57866. int *pnByte /* If allocation cannot be made, increment *pnByte */
  57867. ){
  57868. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  57869. if( pBuf ) return pBuf;
  57870. nByte = ROUND8(nByte);
  57871. if( &(*ppFrom)[nByte] <= pEnd ){
  57872. pBuf = (void*)*ppFrom;
  57873. *ppFrom += nByte;
  57874. }else{
  57875. *pnByte += nByte;
  57876. }
  57877. return pBuf;
  57878. }
  57879. /*
  57880. ** Rewind the VDBE back to the beginning in preparation for
  57881. ** running it.
  57882. */
  57883. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  57884. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  57885. int i;
  57886. #endif
  57887. assert( p!=0 );
  57888. assert( p->magic==VDBE_MAGIC_INIT );
  57889. /* There should be at least one opcode.
  57890. */
  57891. assert( p->nOp>0 );
  57892. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  57893. p->magic = VDBE_MAGIC_RUN;
  57894. #ifdef SQLITE_DEBUG
  57895. for(i=1; i<p->nMem; i++){
  57896. assert( p->aMem[i].db==p->db );
  57897. }
  57898. #endif
  57899. p->pc = -1;
  57900. p->rc = SQLITE_OK;
  57901. p->errorAction = OE_Abort;
  57902. p->magic = VDBE_MAGIC_RUN;
  57903. p->nChange = 0;
  57904. p->cacheCtr = 1;
  57905. p->minWriteFileFormat = 255;
  57906. p->iStatement = 0;
  57907. p->nFkConstraint = 0;
  57908. #ifdef VDBE_PROFILE
  57909. for(i=0; i<p->nOp; i++){
  57910. p->aOp[i].cnt = 0;
  57911. p->aOp[i].cycles = 0;
  57912. }
  57913. #endif
  57914. }
  57915. /*
  57916. ** Prepare a virtual machine for execution for the first time after
  57917. ** creating the virtual machine. This involves things such
  57918. ** as allocating stack space and initializing the program counter.
  57919. ** After the VDBE has be prepped, it can be executed by one or more
  57920. ** calls to sqlite3VdbeExec().
  57921. **
  57922. ** This function may be called exact once on a each virtual machine.
  57923. ** After this routine is called the VM has been "packaged" and is ready
  57924. ** to run. After this routine is called, futher calls to
  57925. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  57926. ** the Vdbe from the Parse object that helped generate it so that the
  57927. ** the Vdbe becomes an independent entity and the Parse object can be
  57928. ** destroyed.
  57929. **
  57930. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  57931. ** to its initial state after it has been run.
  57932. */
  57933. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  57934. Vdbe *p, /* The VDBE */
  57935. Parse *pParse /* Parsing context */
  57936. ){
  57937. sqlite3 *db; /* The database connection */
  57938. int nVar; /* Number of parameters */
  57939. int nMem; /* Number of VM memory registers */
  57940. int nCursor; /* Number of cursors required */
  57941. int nArg; /* Number of arguments in subprograms */
  57942. int nOnce; /* Number of OP_Once instructions */
  57943. int n; /* Loop counter */
  57944. u8 *zCsr; /* Memory available for allocation */
  57945. u8 *zEnd; /* First byte past allocated memory */
  57946. int nByte; /* How much extra memory is needed */
  57947. assert( p!=0 );
  57948. assert( p->nOp>0 );
  57949. assert( pParse!=0 );
  57950. assert( p->magic==VDBE_MAGIC_INIT );
  57951. db = p->db;
  57952. assert( db->mallocFailed==0 );
  57953. nVar = pParse->nVar;
  57954. nMem = pParse->nMem;
  57955. nCursor = pParse->nTab;
  57956. nArg = pParse->nMaxArg;
  57957. nOnce = pParse->nOnce;
  57958. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  57959. /* For each cursor required, also allocate a memory cell. Memory
  57960. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  57961. ** the vdbe program. Instead they are used to allocate space for
  57962. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  57963. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  57964. ** stores the blob of memory associated with cursor 1, etc.
  57965. **
  57966. ** See also: allocateCursor().
  57967. */
  57968. nMem += nCursor;
  57969. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  57970. ** an array to marshal SQL function arguments in.
  57971. */
  57972. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  57973. zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */
  57974. resolveP2Values(p, &nArg);
  57975. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  57976. if( pParse->explain && nMem<10 ){
  57977. nMem = 10;
  57978. }
  57979. memset(zCsr, 0, zEnd-zCsr);
  57980. zCsr += (zCsr - (u8*)0)&7;
  57981. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  57982. p->expired = 0;
  57983. /* Memory for registers, parameters, cursor, etc, is allocated in two
  57984. ** passes. On the first pass, we try to reuse unused space at the
  57985. ** end of the opcode array. If we are unable to satisfy all memory
  57986. ** requirements by reusing the opcode array tail, then the second
  57987. ** pass will fill in the rest using a fresh allocation.
  57988. **
  57989. ** This two-pass approach that reuses as much memory as possible from
  57990. ** the leftover space at the end of the opcode array can significantly
  57991. ** reduce the amount of memory held by a prepared statement.
  57992. */
  57993. do {
  57994. nByte = 0;
  57995. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  57996. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  57997. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  57998. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  57999. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  58000. &zCsr, zEnd, &nByte);
  58001. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  58002. if( nByte ){
  58003. p->pFree = sqlite3DbMallocZero(db, nByte);
  58004. }
  58005. zCsr = p->pFree;
  58006. zEnd = &zCsr[nByte];
  58007. }while( nByte && !db->mallocFailed );
  58008. p->nCursor = nCursor;
  58009. p->nOnceFlag = nOnce;
  58010. if( p->aVar ){
  58011. p->nVar = (ynVar)nVar;
  58012. for(n=0; n<nVar; n++){
  58013. p->aVar[n].flags = MEM_Null;
  58014. p->aVar[n].db = db;
  58015. }
  58016. }
  58017. if( p->azVar ){
  58018. p->nzVar = pParse->nzVar;
  58019. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  58020. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  58021. }
  58022. if( p->aMem ){
  58023. p->aMem--; /* aMem[] goes from 1..nMem */
  58024. p->nMem = nMem; /* not from 0..nMem-1 */
  58025. for(n=1; n<=nMem; n++){
  58026. p->aMem[n].flags = MEM_Invalid;
  58027. p->aMem[n].db = db;
  58028. }
  58029. }
  58030. p->explain = pParse->explain;
  58031. sqlite3VdbeRewind(p);
  58032. }
  58033. /*
  58034. ** Close a VDBE cursor and release all the resources that cursor
  58035. ** happens to hold.
  58036. */
  58037. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  58038. if( pCx==0 ){
  58039. return;
  58040. }
  58041. sqlite3VdbeSorterClose(p->db, pCx);
  58042. if( pCx->pBt ){
  58043. sqlite3BtreeClose(pCx->pBt);
  58044. /* The pCx->pCursor will be close automatically, if it exists, by
  58045. ** the call above. */
  58046. }else if( pCx->pCursor ){
  58047. sqlite3BtreeCloseCursor(pCx->pCursor);
  58048. }
  58049. #ifndef SQLITE_OMIT_VIRTUALTABLE
  58050. if( pCx->pVtabCursor ){
  58051. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  58052. const sqlite3_module *pModule = pCx->pModule;
  58053. p->inVtabMethod = 1;
  58054. pModule->xClose(pVtabCursor);
  58055. p->inVtabMethod = 0;
  58056. }
  58057. #endif
  58058. }
  58059. /*
  58060. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  58061. ** is used, for example, when a trigger sub-program is halted to restore
  58062. ** control to the main program.
  58063. */
  58064. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  58065. Vdbe *v = pFrame->v;
  58066. v->aOnceFlag = pFrame->aOnceFlag;
  58067. v->nOnceFlag = pFrame->nOnceFlag;
  58068. v->aOp = pFrame->aOp;
  58069. v->nOp = pFrame->nOp;
  58070. v->aMem = pFrame->aMem;
  58071. v->nMem = pFrame->nMem;
  58072. v->apCsr = pFrame->apCsr;
  58073. v->nCursor = pFrame->nCursor;
  58074. v->db->lastRowid = pFrame->lastRowid;
  58075. v->nChange = pFrame->nChange;
  58076. return pFrame->pc;
  58077. }
  58078. /*
  58079. ** Close all cursors.
  58080. **
  58081. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  58082. ** cell array. This is necessary as the memory cell array may contain
  58083. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  58084. ** open cursors.
  58085. */
  58086. static void closeAllCursors(Vdbe *p){
  58087. if( p->pFrame ){
  58088. VdbeFrame *pFrame;
  58089. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  58090. sqlite3VdbeFrameRestore(pFrame);
  58091. }
  58092. p->pFrame = 0;
  58093. p->nFrame = 0;
  58094. if( p->apCsr ){
  58095. int i;
  58096. for(i=0; i<p->nCursor; i++){
  58097. VdbeCursor *pC = p->apCsr[i];
  58098. if( pC ){
  58099. sqlite3VdbeFreeCursor(p, pC);
  58100. p->apCsr[i] = 0;
  58101. }
  58102. }
  58103. }
  58104. if( p->aMem ){
  58105. releaseMemArray(&p->aMem[1], p->nMem);
  58106. }
  58107. while( p->pDelFrame ){
  58108. VdbeFrame *pDel = p->pDelFrame;
  58109. p->pDelFrame = pDel->pParent;
  58110. sqlite3VdbeFrameDelete(pDel);
  58111. }
  58112. /* Delete any auxdata allocations made by the VM */
  58113. sqlite3VdbeDeleteAuxData(p, -1, 0);
  58114. assert( p->pAuxData==0 );
  58115. }
  58116. /*
  58117. ** Clean up the VM after execution.
  58118. **
  58119. ** This routine will automatically close any cursors, lists, and/or
  58120. ** sorters that were left open. It also deletes the values of
  58121. ** variables in the aVar[] array.
  58122. */
  58123. static void Cleanup(Vdbe *p){
  58124. sqlite3 *db = p->db;
  58125. #ifdef SQLITE_DEBUG
  58126. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  58127. ** Vdbe.aMem[] arrays have already been cleaned up. */
  58128. int i;
  58129. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  58130. if( p->aMem ){
  58131. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
  58132. }
  58133. #endif
  58134. sqlite3DbFree(db, p->zErrMsg);
  58135. p->zErrMsg = 0;
  58136. p->pResultSet = 0;
  58137. }
  58138. /*
  58139. ** Set the number of result columns that will be returned by this SQL
  58140. ** statement. This is now set at compile time, rather than during
  58141. ** execution of the vdbe program so that sqlite3_column_count() can
  58142. ** be called on an SQL statement before sqlite3_step().
  58143. */
  58144. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  58145. Mem *pColName;
  58146. int n;
  58147. sqlite3 *db = p->db;
  58148. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  58149. sqlite3DbFree(db, p->aColName);
  58150. n = nResColumn*COLNAME_N;
  58151. p->nResColumn = (u16)nResColumn;
  58152. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  58153. if( p->aColName==0 ) return;
  58154. while( n-- > 0 ){
  58155. pColName->flags = MEM_Null;
  58156. pColName->db = p->db;
  58157. pColName++;
  58158. }
  58159. }
  58160. /*
  58161. ** Set the name of the idx'th column to be returned by the SQL statement.
  58162. ** zName must be a pointer to a nul terminated string.
  58163. **
  58164. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  58165. **
  58166. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  58167. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  58168. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  58169. */
  58170. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  58171. Vdbe *p, /* Vdbe being configured */
  58172. int idx, /* Index of column zName applies to */
  58173. int var, /* One of the COLNAME_* constants */
  58174. const char *zName, /* Pointer to buffer containing name */
  58175. void (*xDel)(void*) /* Memory management strategy for zName */
  58176. ){
  58177. int rc;
  58178. Mem *pColName;
  58179. assert( idx<p->nResColumn );
  58180. assert( var<COLNAME_N );
  58181. if( p->db->mallocFailed ){
  58182. assert( !zName || xDel!=SQLITE_DYNAMIC );
  58183. return SQLITE_NOMEM;
  58184. }
  58185. assert( p->aColName!=0 );
  58186. pColName = &(p->aColName[idx+var*p->nResColumn]);
  58187. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  58188. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  58189. return rc;
  58190. }
  58191. /*
  58192. ** A read or write transaction may or may not be active on database handle
  58193. ** db. If a transaction is active, commit it. If there is a
  58194. ** write-transaction spanning more than one database file, this routine
  58195. ** takes care of the master journal trickery.
  58196. */
  58197. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  58198. int i;
  58199. int nTrans = 0; /* Number of databases with an active write-transaction */
  58200. int rc = SQLITE_OK;
  58201. int needXcommit = 0;
  58202. #ifdef SQLITE_OMIT_VIRTUALTABLE
  58203. /* With this option, sqlite3VtabSync() is defined to be simply
  58204. ** SQLITE_OK so p is not used.
  58205. */
  58206. UNUSED_PARAMETER(p);
  58207. #endif
  58208. /* Before doing anything else, call the xSync() callback for any
  58209. ** virtual module tables written in this transaction. This has to
  58210. ** be done before determining whether a master journal file is
  58211. ** required, as an xSync() callback may add an attached database
  58212. ** to the transaction.
  58213. */
  58214. rc = sqlite3VtabSync(db, p);
  58215. /* This loop determines (a) if the commit hook should be invoked and
  58216. ** (b) how many database files have open write transactions, not
  58217. ** including the temp database. (b) is important because if more than
  58218. ** one database file has an open write transaction, a master journal
  58219. ** file is required for an atomic commit.
  58220. */
  58221. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  58222. Btree *pBt = db->aDb[i].pBt;
  58223. if( sqlite3BtreeIsInTrans(pBt) ){
  58224. needXcommit = 1;
  58225. if( i!=1 ) nTrans++;
  58226. sqlite3BtreeEnter(pBt);
  58227. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  58228. sqlite3BtreeLeave(pBt);
  58229. }
  58230. }
  58231. if( rc!=SQLITE_OK ){
  58232. return rc;
  58233. }
  58234. /* If there are any write-transactions at all, invoke the commit hook */
  58235. if( needXcommit && db->xCommitCallback ){
  58236. rc = db->xCommitCallback(db->pCommitArg);
  58237. if( rc ){
  58238. return SQLITE_CONSTRAINT_COMMITHOOK;
  58239. }
  58240. }
  58241. /* The simple case - no more than one database file (not counting the
  58242. ** TEMP database) has a transaction active. There is no need for the
  58243. ** master-journal.
  58244. **
  58245. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  58246. ** string, it means the main database is :memory: or a temp file. In
  58247. ** that case we do not support atomic multi-file commits, so use the
  58248. ** simple case then too.
  58249. */
  58250. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  58251. || nTrans<=1
  58252. ){
  58253. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  58254. Btree *pBt = db->aDb[i].pBt;
  58255. if( pBt ){
  58256. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  58257. }
  58258. }
  58259. /* Do the commit only if all databases successfully complete phase 1.
  58260. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  58261. ** IO error while deleting or truncating a journal file. It is unlikely,
  58262. ** but could happen. In this case abandon processing and return the error.
  58263. */
  58264. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  58265. Btree *pBt = db->aDb[i].pBt;
  58266. if( pBt ){
  58267. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  58268. }
  58269. }
  58270. if( rc==SQLITE_OK ){
  58271. sqlite3VtabCommit(db);
  58272. }
  58273. }
  58274. /* The complex case - There is a multi-file write-transaction active.
  58275. ** This requires a master journal file to ensure the transaction is
  58276. ** committed atomicly.
  58277. */
  58278. #ifndef SQLITE_OMIT_DISKIO
  58279. else{
  58280. sqlite3_vfs *pVfs = db->pVfs;
  58281. int needSync = 0;
  58282. char *zMaster = 0; /* File-name for the master journal */
  58283. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  58284. sqlite3_file *pMaster = 0;
  58285. i64 offset = 0;
  58286. int res;
  58287. int retryCount = 0;
  58288. int nMainFile;
  58289. /* Select a master journal file name */
  58290. nMainFile = sqlite3Strlen30(zMainFile);
  58291. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  58292. if( zMaster==0 ) return SQLITE_NOMEM;
  58293. do {
  58294. u32 iRandom;
  58295. if( retryCount ){
  58296. if( retryCount>100 ){
  58297. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  58298. sqlite3OsDelete(pVfs, zMaster, 0);
  58299. break;
  58300. }else if( retryCount==1 ){
  58301. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  58302. }
  58303. }
  58304. retryCount++;
  58305. sqlite3_randomness(sizeof(iRandom), &iRandom);
  58306. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  58307. (iRandom>>8)&0xffffff, iRandom&0xff);
  58308. /* The antipenultimate character of the master journal name must
  58309. ** be "9" to avoid name collisions when using 8+3 filenames. */
  58310. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  58311. sqlite3FileSuffix3(zMainFile, zMaster);
  58312. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  58313. }while( rc==SQLITE_OK && res );
  58314. if( rc==SQLITE_OK ){
  58315. /* Open the master journal. */
  58316. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  58317. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  58318. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  58319. );
  58320. }
  58321. if( rc!=SQLITE_OK ){
  58322. sqlite3DbFree(db, zMaster);
  58323. return rc;
  58324. }
  58325. /* Write the name of each database file in the transaction into the new
  58326. ** master journal file. If an error occurs at this point close
  58327. ** and delete the master journal file. All the individual journal files
  58328. ** still have 'null' as the master journal pointer, so they will roll
  58329. ** back independently if a failure occurs.
  58330. */
  58331. for(i=0; i<db->nDb; i++){
  58332. Btree *pBt = db->aDb[i].pBt;
  58333. if( sqlite3BtreeIsInTrans(pBt) ){
  58334. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  58335. if( zFile==0 ){
  58336. continue; /* Ignore TEMP and :memory: databases */
  58337. }
  58338. assert( zFile[0]!=0 );
  58339. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  58340. needSync = 1;
  58341. }
  58342. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  58343. offset += sqlite3Strlen30(zFile)+1;
  58344. if( rc!=SQLITE_OK ){
  58345. sqlite3OsCloseFree(pMaster);
  58346. sqlite3OsDelete(pVfs, zMaster, 0);
  58347. sqlite3DbFree(db, zMaster);
  58348. return rc;
  58349. }
  58350. }
  58351. }
  58352. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  58353. ** flag is set this is not required.
  58354. */
  58355. if( needSync
  58356. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  58357. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  58358. ){
  58359. sqlite3OsCloseFree(pMaster);
  58360. sqlite3OsDelete(pVfs, zMaster, 0);
  58361. sqlite3DbFree(db, zMaster);
  58362. return rc;
  58363. }
  58364. /* Sync all the db files involved in the transaction. The same call
  58365. ** sets the master journal pointer in each individual journal. If
  58366. ** an error occurs here, do not delete the master journal file.
  58367. **
  58368. ** If the error occurs during the first call to
  58369. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  58370. ** master journal file will be orphaned. But we cannot delete it,
  58371. ** in case the master journal file name was written into the journal
  58372. ** file before the failure occurred.
  58373. */
  58374. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  58375. Btree *pBt = db->aDb[i].pBt;
  58376. if( pBt ){
  58377. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  58378. }
  58379. }
  58380. sqlite3OsCloseFree(pMaster);
  58381. assert( rc!=SQLITE_BUSY );
  58382. if( rc!=SQLITE_OK ){
  58383. sqlite3DbFree(db, zMaster);
  58384. return rc;
  58385. }
  58386. /* Delete the master journal file. This commits the transaction. After
  58387. ** doing this the directory is synced again before any individual
  58388. ** transaction files are deleted.
  58389. */
  58390. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  58391. sqlite3DbFree(db, zMaster);
  58392. zMaster = 0;
  58393. if( rc ){
  58394. return rc;
  58395. }
  58396. /* All files and directories have already been synced, so the following
  58397. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  58398. ** deleting or truncating journals. If something goes wrong while
  58399. ** this is happening we don't really care. The integrity of the
  58400. ** transaction is already guaranteed, but some stray 'cold' journals
  58401. ** may be lying around. Returning an error code won't help matters.
  58402. */
  58403. disable_simulated_io_errors();
  58404. sqlite3BeginBenignMalloc();
  58405. for(i=0; i<db->nDb; i++){
  58406. Btree *pBt = db->aDb[i].pBt;
  58407. if( pBt ){
  58408. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  58409. }
  58410. }
  58411. sqlite3EndBenignMalloc();
  58412. enable_simulated_io_errors();
  58413. sqlite3VtabCommit(db);
  58414. }
  58415. #endif
  58416. return rc;
  58417. }
  58418. /*
  58419. ** This routine checks that the sqlite3.nVdbeActive count variable
  58420. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  58421. ** currently active. An assertion fails if the two counts do not match.
  58422. ** This is an internal self-check only - it is not an essential processing
  58423. ** step.
  58424. **
  58425. ** This is a no-op if NDEBUG is defined.
  58426. */
  58427. #ifndef NDEBUG
  58428. static void checkActiveVdbeCnt(sqlite3 *db){
  58429. Vdbe *p;
  58430. int cnt = 0;
  58431. int nWrite = 0;
  58432. int nRead = 0;
  58433. p = db->pVdbe;
  58434. while( p ){
  58435. if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
  58436. cnt++;
  58437. if( p->readOnly==0 ) nWrite++;
  58438. if( p->bIsReader ) nRead++;
  58439. }
  58440. p = p->pNext;
  58441. }
  58442. assert( cnt==db->nVdbeActive );
  58443. assert( nWrite==db->nVdbeWrite );
  58444. assert( nRead==db->nVdbeRead );
  58445. }
  58446. #else
  58447. #define checkActiveVdbeCnt(x)
  58448. #endif
  58449. /*
  58450. ** If the Vdbe passed as the first argument opened a statement-transaction,
  58451. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  58452. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  58453. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  58454. ** statement transaction is committed.
  58455. **
  58456. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  58457. ** Otherwise SQLITE_OK.
  58458. */
  58459. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  58460. sqlite3 *const db = p->db;
  58461. int rc = SQLITE_OK;
  58462. /* If p->iStatement is greater than zero, then this Vdbe opened a
  58463. ** statement transaction that should be closed here. The only exception
  58464. ** is that an IO error may have occurred, causing an emergency rollback.
  58465. ** In this case (db->nStatement==0), and there is nothing to do.
  58466. */
  58467. if( db->nStatement && p->iStatement ){
  58468. int i;
  58469. const int iSavepoint = p->iStatement-1;
  58470. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  58471. assert( db->nStatement>0 );
  58472. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  58473. for(i=0; i<db->nDb; i++){
  58474. int rc2 = SQLITE_OK;
  58475. Btree *pBt = db->aDb[i].pBt;
  58476. if( pBt ){
  58477. if( eOp==SAVEPOINT_ROLLBACK ){
  58478. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  58479. }
  58480. if( rc2==SQLITE_OK ){
  58481. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  58482. }
  58483. if( rc==SQLITE_OK ){
  58484. rc = rc2;
  58485. }
  58486. }
  58487. }
  58488. db->nStatement--;
  58489. p->iStatement = 0;
  58490. if( rc==SQLITE_OK ){
  58491. if( eOp==SAVEPOINT_ROLLBACK ){
  58492. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  58493. }
  58494. if( rc==SQLITE_OK ){
  58495. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  58496. }
  58497. }
  58498. /* If the statement transaction is being rolled back, also restore the
  58499. ** database handles deferred constraint counter to the value it had when
  58500. ** the statement transaction was opened. */
  58501. if( eOp==SAVEPOINT_ROLLBACK ){
  58502. db->nDeferredCons = p->nStmtDefCons;
  58503. db->nDeferredImmCons = p->nStmtDefImmCons;
  58504. }
  58505. }
  58506. return rc;
  58507. }
  58508. /*
  58509. ** This function is called when a transaction opened by the database
  58510. ** handle associated with the VM passed as an argument is about to be
  58511. ** committed. If there are outstanding deferred foreign key constraint
  58512. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  58513. **
  58514. ** If there are outstanding FK violations and this function returns
  58515. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  58516. ** and write an error message to it. Then return SQLITE_ERROR.
  58517. */
  58518. #ifndef SQLITE_OMIT_FOREIGN_KEY
  58519. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  58520. sqlite3 *db = p->db;
  58521. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  58522. || (!deferred && p->nFkConstraint>0)
  58523. ){
  58524. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  58525. p->errorAction = OE_Abort;
  58526. sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
  58527. return SQLITE_ERROR;
  58528. }
  58529. return SQLITE_OK;
  58530. }
  58531. #endif
  58532. /*
  58533. ** This routine is called the when a VDBE tries to halt. If the VDBE
  58534. ** has made changes and is in autocommit mode, then commit those
  58535. ** changes. If a rollback is needed, then do the rollback.
  58536. **
  58537. ** This routine is the only way to move the state of a VM from
  58538. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  58539. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  58540. **
  58541. ** Return an error code. If the commit could not complete because of
  58542. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  58543. ** means the close did not happen and needs to be repeated.
  58544. */
  58545. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  58546. int rc; /* Used to store transient return codes */
  58547. sqlite3 *db = p->db;
  58548. /* This function contains the logic that determines if a statement or
  58549. ** transaction will be committed or rolled back as a result of the
  58550. ** execution of this virtual machine.
  58551. **
  58552. ** If any of the following errors occur:
  58553. **
  58554. ** SQLITE_NOMEM
  58555. ** SQLITE_IOERR
  58556. ** SQLITE_FULL
  58557. ** SQLITE_INTERRUPT
  58558. **
  58559. ** Then the internal cache might have been left in an inconsistent
  58560. ** state. We need to rollback the statement transaction, if there is
  58561. ** one, or the complete transaction if there is no statement transaction.
  58562. */
  58563. if( p->db->mallocFailed ){
  58564. p->rc = SQLITE_NOMEM;
  58565. }
  58566. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  58567. closeAllCursors(p);
  58568. if( p->magic!=VDBE_MAGIC_RUN ){
  58569. return SQLITE_OK;
  58570. }
  58571. checkActiveVdbeCnt(db);
  58572. /* No commit or rollback needed if the program never started or if the
  58573. ** SQL statement does not read or write a database file. */
  58574. if( p->pc>=0 && p->bIsReader ){
  58575. int mrc; /* Primary error code from p->rc */
  58576. int eStatementOp = 0;
  58577. int isSpecialError; /* Set to true if a 'special' error */
  58578. /* Lock all btrees used by the statement */
  58579. sqlite3VdbeEnter(p);
  58580. /* Check for one of the special errors */
  58581. mrc = p->rc & 0xff;
  58582. assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
  58583. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  58584. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  58585. if( isSpecialError ){
  58586. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  58587. ** no rollback is necessary. Otherwise, at least a savepoint
  58588. ** transaction must be rolled back to restore the database to a
  58589. ** consistent state.
  58590. **
  58591. ** Even if the statement is read-only, it is important to perform
  58592. ** a statement or transaction rollback operation. If the error
  58593. ** occurred while writing to the journal, sub-journal or database
  58594. ** file as part of an effort to free up cache space (see function
  58595. ** pagerStress() in pager.c), the rollback is required to restore
  58596. ** the pager to a consistent state.
  58597. */
  58598. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  58599. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  58600. eStatementOp = SAVEPOINT_ROLLBACK;
  58601. }else{
  58602. /* We are forced to roll back the active transaction. Before doing
  58603. ** so, abort any other statements this handle currently has active.
  58604. */
  58605. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  58606. sqlite3CloseSavepoints(db);
  58607. db->autoCommit = 1;
  58608. }
  58609. }
  58610. }
  58611. /* Check for immediate foreign key violations. */
  58612. if( p->rc==SQLITE_OK ){
  58613. sqlite3VdbeCheckFk(p, 0);
  58614. }
  58615. /* If the auto-commit flag is set and this is the only active writer
  58616. ** VM, then we do either a commit or rollback of the current transaction.
  58617. **
  58618. ** Note: This block also runs if one of the special errors handled
  58619. ** above has occurred.
  58620. */
  58621. if( !sqlite3VtabInSync(db)
  58622. && db->autoCommit
  58623. && db->nVdbeWrite==(p->readOnly==0)
  58624. ){
  58625. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  58626. rc = sqlite3VdbeCheckFk(p, 1);
  58627. if( rc!=SQLITE_OK ){
  58628. if( NEVER(p->readOnly) ){
  58629. sqlite3VdbeLeave(p);
  58630. return SQLITE_ERROR;
  58631. }
  58632. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  58633. }else{
  58634. /* The auto-commit flag is true, the vdbe program was successful
  58635. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  58636. ** key constraints to hold up the transaction. This means a commit
  58637. ** is required. */
  58638. rc = vdbeCommit(db, p);
  58639. }
  58640. if( rc==SQLITE_BUSY && p->readOnly ){
  58641. sqlite3VdbeLeave(p);
  58642. return SQLITE_BUSY;
  58643. }else if( rc!=SQLITE_OK ){
  58644. p->rc = rc;
  58645. sqlite3RollbackAll(db, SQLITE_OK);
  58646. }else{
  58647. db->nDeferredCons = 0;
  58648. db->nDeferredImmCons = 0;
  58649. db->flags &= ~SQLITE_DeferFKs;
  58650. sqlite3CommitInternalChanges(db);
  58651. }
  58652. }else{
  58653. sqlite3RollbackAll(db, SQLITE_OK);
  58654. }
  58655. db->nStatement = 0;
  58656. }else if( eStatementOp==0 ){
  58657. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  58658. eStatementOp = SAVEPOINT_RELEASE;
  58659. }else if( p->errorAction==OE_Abort ){
  58660. eStatementOp = SAVEPOINT_ROLLBACK;
  58661. }else{
  58662. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  58663. sqlite3CloseSavepoints(db);
  58664. db->autoCommit = 1;
  58665. }
  58666. }
  58667. /* If eStatementOp is non-zero, then a statement transaction needs to
  58668. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  58669. ** do so. If this operation returns an error, and the current statement
  58670. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  58671. ** current statement error code.
  58672. */
  58673. if( eStatementOp ){
  58674. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  58675. if( rc ){
  58676. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  58677. p->rc = rc;
  58678. sqlite3DbFree(db, p->zErrMsg);
  58679. p->zErrMsg = 0;
  58680. }
  58681. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  58682. sqlite3CloseSavepoints(db);
  58683. db->autoCommit = 1;
  58684. }
  58685. }
  58686. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  58687. ** has been rolled back, update the database connection change-counter.
  58688. */
  58689. if( p->changeCntOn ){
  58690. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  58691. sqlite3VdbeSetChanges(db, p->nChange);
  58692. }else{
  58693. sqlite3VdbeSetChanges(db, 0);
  58694. }
  58695. p->nChange = 0;
  58696. }
  58697. /* Release the locks */
  58698. sqlite3VdbeLeave(p);
  58699. }
  58700. /* We have successfully halted and closed the VM. Record this fact. */
  58701. if( p->pc>=0 ){
  58702. db->nVdbeActive--;
  58703. if( !p->readOnly ) db->nVdbeWrite--;
  58704. if( p->bIsReader ) db->nVdbeRead--;
  58705. assert( db->nVdbeActive>=db->nVdbeRead );
  58706. assert( db->nVdbeRead>=db->nVdbeWrite );
  58707. assert( db->nVdbeWrite>=0 );
  58708. }
  58709. p->magic = VDBE_MAGIC_HALT;
  58710. checkActiveVdbeCnt(db);
  58711. if( p->db->mallocFailed ){
  58712. p->rc = SQLITE_NOMEM;
  58713. }
  58714. /* If the auto-commit flag is set to true, then any locks that were held
  58715. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  58716. ** to invoke any required unlock-notify callbacks.
  58717. */
  58718. if( db->autoCommit ){
  58719. sqlite3ConnectionUnlocked(db);
  58720. }
  58721. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  58722. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  58723. }
  58724. /*
  58725. ** Each VDBE holds the result of the most recent sqlite3_step() call
  58726. ** in p->rc. This routine sets that result back to SQLITE_OK.
  58727. */
  58728. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  58729. p->rc = SQLITE_OK;
  58730. }
  58731. /*
  58732. ** Copy the error code and error message belonging to the VDBE passed
  58733. ** as the first argument to its database handle (so that they will be
  58734. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  58735. **
  58736. ** This function does not clear the VDBE error code or message, just
  58737. ** copies them to the database handle.
  58738. */
  58739. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  58740. sqlite3 *db = p->db;
  58741. int rc = p->rc;
  58742. if( p->zErrMsg ){
  58743. u8 mallocFailed = db->mallocFailed;
  58744. sqlite3BeginBenignMalloc();
  58745. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  58746. sqlite3EndBenignMalloc();
  58747. db->mallocFailed = mallocFailed;
  58748. db->errCode = rc;
  58749. }else{
  58750. sqlite3Error(db, rc, 0);
  58751. }
  58752. return rc;
  58753. }
  58754. #ifdef SQLITE_ENABLE_SQLLOG
  58755. /*
  58756. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  58757. ** invoke it.
  58758. */
  58759. static void vdbeInvokeSqllog(Vdbe *v){
  58760. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  58761. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  58762. assert( v->db->init.busy==0 );
  58763. if( zExpanded ){
  58764. sqlite3GlobalConfig.xSqllog(
  58765. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  58766. );
  58767. sqlite3DbFree(v->db, zExpanded);
  58768. }
  58769. }
  58770. }
  58771. #else
  58772. # define vdbeInvokeSqllog(x)
  58773. #endif
  58774. /*
  58775. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  58776. ** Write any error messages into *pzErrMsg. Return the result code.
  58777. **
  58778. ** After this routine is run, the VDBE should be ready to be executed
  58779. ** again.
  58780. **
  58781. ** To look at it another way, this routine resets the state of the
  58782. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  58783. ** VDBE_MAGIC_INIT.
  58784. */
  58785. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  58786. sqlite3 *db;
  58787. db = p->db;
  58788. /* If the VM did not run to completion or if it encountered an
  58789. ** error, then it might not have been halted properly. So halt
  58790. ** it now.
  58791. */
  58792. sqlite3VdbeHalt(p);
  58793. /* If the VDBE has be run even partially, then transfer the error code
  58794. ** and error message from the VDBE into the main database structure. But
  58795. ** if the VDBE has just been set to run but has not actually executed any
  58796. ** instructions yet, leave the main database error information unchanged.
  58797. */
  58798. if( p->pc>=0 ){
  58799. vdbeInvokeSqllog(p);
  58800. sqlite3VdbeTransferError(p);
  58801. sqlite3DbFree(db, p->zErrMsg);
  58802. p->zErrMsg = 0;
  58803. if( p->runOnlyOnce ) p->expired = 1;
  58804. }else if( p->rc && p->expired ){
  58805. /* The expired flag was set on the VDBE before the first call
  58806. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  58807. ** called), set the database error in this case as well.
  58808. */
  58809. sqlite3Error(db, p->rc, 0);
  58810. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  58811. sqlite3DbFree(db, p->zErrMsg);
  58812. p->zErrMsg = 0;
  58813. }
  58814. /* Reclaim all memory used by the VDBE
  58815. */
  58816. Cleanup(p);
  58817. /* Save profiling information from this VDBE run.
  58818. */
  58819. #ifdef VDBE_PROFILE
  58820. {
  58821. FILE *out = fopen("vdbe_profile.out", "a");
  58822. if( out ){
  58823. int i;
  58824. fprintf(out, "---- ");
  58825. for(i=0; i<p->nOp; i++){
  58826. fprintf(out, "%02x", p->aOp[i].opcode);
  58827. }
  58828. fprintf(out, "\n");
  58829. for(i=0; i<p->nOp; i++){
  58830. fprintf(out, "%6d %10lld %8lld ",
  58831. p->aOp[i].cnt,
  58832. p->aOp[i].cycles,
  58833. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  58834. );
  58835. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  58836. }
  58837. fclose(out);
  58838. }
  58839. }
  58840. #endif
  58841. p->iCurrentTime = 0;
  58842. p->magic = VDBE_MAGIC_INIT;
  58843. return p->rc & db->errMask;
  58844. }
  58845. /*
  58846. ** Clean up and delete a VDBE after execution. Return an integer which is
  58847. ** the result code. Write any error message text into *pzErrMsg.
  58848. */
  58849. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  58850. int rc = SQLITE_OK;
  58851. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  58852. rc = sqlite3VdbeReset(p);
  58853. assert( (rc & p->db->errMask)==rc );
  58854. }
  58855. sqlite3VdbeDelete(p);
  58856. return rc;
  58857. }
  58858. /*
  58859. ** If parameter iOp is less than zero, then invoke the destructor for
  58860. ** all auxiliary data pointers currently cached by the VM passed as
  58861. ** the first argument.
  58862. **
  58863. ** Or, if iOp is greater than or equal to zero, then the destructor is
  58864. ** only invoked for those auxiliary data pointers created by the user
  58865. ** function invoked by the OP_Function opcode at instruction iOp of
  58866. ** VM pVdbe, and only then if:
  58867. **
  58868. ** * the associated function parameter is the 32nd or later (counting
  58869. ** from left to right), or
  58870. **
  58871. ** * the corresponding bit in argument mask is clear (where the first
  58872. ** function parameter corrsponds to bit 0 etc.).
  58873. */
  58874. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
  58875. AuxData **pp = &pVdbe->pAuxData;
  58876. while( *pp ){
  58877. AuxData *pAux = *pp;
  58878. if( (iOp<0)
  58879. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & ((u32)1<<pAux->iArg))))
  58880. ){
  58881. if( pAux->xDelete ){
  58882. pAux->xDelete(pAux->pAux);
  58883. }
  58884. *pp = pAux->pNext;
  58885. sqlite3DbFree(pVdbe->db, pAux);
  58886. }else{
  58887. pp= &pAux->pNext;
  58888. }
  58889. }
  58890. }
  58891. /*
  58892. ** Free all memory associated with the Vdbe passed as the second argument,
  58893. ** except for object itself, which is preserved.
  58894. **
  58895. ** The difference between this function and sqlite3VdbeDelete() is that
  58896. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  58897. ** the database connection and frees the object itself.
  58898. */
  58899. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  58900. SubProgram *pSub, *pNext;
  58901. int i;
  58902. assert( p->db==0 || p->db==db );
  58903. releaseMemArray(p->aVar, p->nVar);
  58904. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  58905. for(pSub=p->pProgram; pSub; pSub=pNext){
  58906. pNext = pSub->pNext;
  58907. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  58908. sqlite3DbFree(db, pSub);
  58909. }
  58910. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  58911. vdbeFreeOpArray(db, p->aOp, p->nOp);
  58912. sqlite3DbFree(db, p->aLabel);
  58913. sqlite3DbFree(db, p->aColName);
  58914. sqlite3DbFree(db, p->zSql);
  58915. sqlite3DbFree(db, p->pFree);
  58916. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  58917. sqlite3DbFree(db, p->zExplain);
  58918. sqlite3DbFree(db, p->pExplain);
  58919. #endif
  58920. }
  58921. /*
  58922. ** Delete an entire VDBE.
  58923. */
  58924. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  58925. sqlite3 *db;
  58926. if( NEVER(p==0) ) return;
  58927. db = p->db;
  58928. assert( sqlite3_mutex_held(db->mutex) );
  58929. sqlite3VdbeClearObject(db, p);
  58930. if( p->pPrev ){
  58931. p->pPrev->pNext = p->pNext;
  58932. }else{
  58933. assert( db->pVdbe==p );
  58934. db->pVdbe = p->pNext;
  58935. }
  58936. if( p->pNext ){
  58937. p->pNext->pPrev = p->pPrev;
  58938. }
  58939. p->magic = VDBE_MAGIC_DEAD;
  58940. p->db = 0;
  58941. sqlite3DbFree(db, p);
  58942. }
  58943. /*
  58944. ** Make sure the cursor p is ready to read or write the row to which it
  58945. ** was last positioned. Return an error code if an OOM fault or I/O error
  58946. ** prevents us from positioning the cursor to its correct position.
  58947. **
  58948. ** If a MoveTo operation is pending on the given cursor, then do that
  58949. ** MoveTo now. If no move is pending, check to see if the row has been
  58950. ** deleted out from under the cursor and if it has, mark the row as
  58951. ** a NULL row.
  58952. **
  58953. ** If the cursor is already pointing to the correct row and that row has
  58954. ** not been deleted out from under the cursor, then this routine is a no-op.
  58955. */
  58956. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  58957. if( p->deferredMoveto ){
  58958. int res, rc;
  58959. #ifdef SQLITE_TEST
  58960. extern int sqlite3_search_count;
  58961. #endif
  58962. assert( p->isTable );
  58963. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  58964. if( rc ) return rc;
  58965. p->lastRowid = p->movetoTarget;
  58966. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  58967. p->rowidIsValid = 1;
  58968. #ifdef SQLITE_TEST
  58969. sqlite3_search_count++;
  58970. #endif
  58971. p->deferredMoveto = 0;
  58972. p->cacheStatus = CACHE_STALE;
  58973. }else if( ALWAYS(p->pCursor) ){
  58974. int hasMoved;
  58975. int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
  58976. if( rc ) return rc;
  58977. if( hasMoved ){
  58978. p->cacheStatus = CACHE_STALE;
  58979. p->nullRow = 1;
  58980. }
  58981. }
  58982. return SQLITE_OK;
  58983. }
  58984. /*
  58985. ** The following functions:
  58986. **
  58987. ** sqlite3VdbeSerialType()
  58988. ** sqlite3VdbeSerialTypeLen()
  58989. ** sqlite3VdbeSerialLen()
  58990. ** sqlite3VdbeSerialPut()
  58991. ** sqlite3VdbeSerialGet()
  58992. **
  58993. ** encapsulate the code that serializes values for storage in SQLite
  58994. ** data and index records. Each serialized value consists of a
  58995. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  58996. ** integer, stored as a varint.
  58997. **
  58998. ** In an SQLite index record, the serial type is stored directly before
  58999. ** the blob of data that it corresponds to. In a table record, all serial
  59000. ** types are stored at the start of the record, and the blobs of data at
  59001. ** the end. Hence these functions allow the caller to handle the
  59002. ** serial-type and data blob separately.
  59003. **
  59004. ** The following table describes the various storage classes for data:
  59005. **
  59006. ** serial type bytes of data type
  59007. ** -------------- --------------- ---------------
  59008. ** 0 0 NULL
  59009. ** 1 1 signed integer
  59010. ** 2 2 signed integer
  59011. ** 3 3 signed integer
  59012. ** 4 4 signed integer
  59013. ** 5 6 signed integer
  59014. ** 6 8 signed integer
  59015. ** 7 8 IEEE float
  59016. ** 8 0 Integer constant 0
  59017. ** 9 0 Integer constant 1
  59018. ** 10,11 reserved for expansion
  59019. ** N>=12 and even (N-12)/2 BLOB
  59020. ** N>=13 and odd (N-13)/2 text
  59021. **
  59022. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  59023. ** of SQLite will not understand those serial types.
  59024. */
  59025. /*
  59026. ** Return the serial-type for the value stored in pMem.
  59027. */
  59028. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  59029. int flags = pMem->flags;
  59030. int n;
  59031. if( flags&MEM_Null ){
  59032. return 0;
  59033. }
  59034. if( flags&MEM_Int ){
  59035. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  59036. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  59037. i64 i = pMem->u.i;
  59038. u64 u;
  59039. if( i<0 ){
  59040. if( i<(-MAX_6BYTE) ) return 6;
  59041. /* Previous test prevents: u = -(-9223372036854775808) */
  59042. u = -i;
  59043. }else{
  59044. u = i;
  59045. }
  59046. if( u<=127 ){
  59047. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  59048. }
  59049. if( u<=32767 ) return 2;
  59050. if( u<=8388607 ) return 3;
  59051. if( u<=2147483647 ) return 4;
  59052. if( u<=MAX_6BYTE ) return 5;
  59053. return 6;
  59054. }
  59055. if( flags&MEM_Real ){
  59056. return 7;
  59057. }
  59058. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  59059. n = pMem->n;
  59060. if( flags & MEM_Zero ){
  59061. n += pMem->u.nZero;
  59062. }
  59063. assert( n>=0 );
  59064. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  59065. }
  59066. /*
  59067. ** Return the length of the data corresponding to the supplied serial-type.
  59068. */
  59069. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  59070. if( serial_type>=12 ){
  59071. return (serial_type-12)/2;
  59072. }else{
  59073. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  59074. return aSize[serial_type];
  59075. }
  59076. }
  59077. /*
  59078. ** If we are on an architecture with mixed-endian floating
  59079. ** points (ex: ARM7) then swap the lower 4 bytes with the
  59080. ** upper 4 bytes. Return the result.
  59081. **
  59082. ** For most architectures, this is a no-op.
  59083. **
  59084. ** (later): It is reported to me that the mixed-endian problem
  59085. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  59086. ** that early versions of GCC stored the two words of a 64-bit
  59087. ** float in the wrong order. And that error has been propagated
  59088. ** ever since. The blame is not necessarily with GCC, though.
  59089. ** GCC might have just copying the problem from a prior compiler.
  59090. ** I am also told that newer versions of GCC that follow a different
  59091. ** ABI get the byte order right.
  59092. **
  59093. ** Developers using SQLite on an ARM7 should compile and run their
  59094. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  59095. ** enabled, some asserts below will ensure that the byte order of
  59096. ** floating point values is correct.
  59097. **
  59098. ** (2007-08-30) Frank van Vugt has studied this problem closely
  59099. ** and has send his findings to the SQLite developers. Frank
  59100. ** writes that some Linux kernels offer floating point hardware
  59101. ** emulation that uses only 32-bit mantissas instead of a full
  59102. ** 48-bits as required by the IEEE standard. (This is the
  59103. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  59104. ** byte swapping becomes very complicated. To avoid problems,
  59105. ** the necessary byte swapping is carried out using a 64-bit integer
  59106. ** rather than a 64-bit float. Frank assures us that the code here
  59107. ** works for him. We, the developers, have no way to independently
  59108. ** verify this, but Frank seems to know what he is talking about
  59109. ** so we trust him.
  59110. */
  59111. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  59112. static u64 floatSwap(u64 in){
  59113. union {
  59114. u64 r;
  59115. u32 i[2];
  59116. } u;
  59117. u32 t;
  59118. u.r = in;
  59119. t = u.i[0];
  59120. u.i[0] = u.i[1];
  59121. u.i[1] = t;
  59122. return u.r;
  59123. }
  59124. # define swapMixedEndianFloat(X) X = floatSwap(X)
  59125. #else
  59126. # define swapMixedEndianFloat(X)
  59127. #endif
  59128. /*
  59129. ** Write the serialized data blob for the value stored in pMem into
  59130. ** buf. It is assumed that the caller has allocated sufficient space.
  59131. ** Return the number of bytes written.
  59132. **
  59133. ** nBuf is the amount of space left in buf[]. nBuf must always be
  59134. ** large enough to hold the entire field. Except, if the field is
  59135. ** a blob with a zero-filled tail, then buf[] might be just the right
  59136. ** size to hold everything except for the zero-filled tail. If buf[]
  59137. ** is only big enough to hold the non-zero prefix, then only write that
  59138. ** prefix into buf[]. But if buf[] is large enough to hold both the
  59139. ** prefix and the tail then write the prefix and set the tail to all
  59140. ** zeros.
  59141. **
  59142. ** Return the number of bytes actually written into buf[]. The number
  59143. ** of bytes in the zero-filled tail is included in the return value only
  59144. ** if those bytes were zeroed in buf[].
  59145. */
  59146. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  59147. u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  59148. u32 len;
  59149. /* Integer and Real */
  59150. if( serial_type<=7 && serial_type>0 ){
  59151. u64 v;
  59152. u32 i;
  59153. if( serial_type==7 ){
  59154. assert( sizeof(v)==sizeof(pMem->r) );
  59155. memcpy(&v, &pMem->r, sizeof(v));
  59156. swapMixedEndianFloat(v);
  59157. }else{
  59158. v = pMem->u.i;
  59159. }
  59160. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  59161. assert( len<=(u32)nBuf );
  59162. while( i-- ){
  59163. buf[i] = (u8)(v&0xFF);
  59164. v >>= 8;
  59165. }
  59166. return len;
  59167. }
  59168. /* String or blob */
  59169. if( serial_type>=12 ){
  59170. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  59171. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  59172. assert( pMem->n<=nBuf );
  59173. len = pMem->n;
  59174. memcpy(buf, pMem->z, len);
  59175. if( pMem->flags & MEM_Zero ){
  59176. len += pMem->u.nZero;
  59177. assert( nBuf>=0 );
  59178. if( len > (u32)nBuf ){
  59179. len = (u32)nBuf;
  59180. }
  59181. memset(&buf[pMem->n], 0, len-pMem->n);
  59182. }
  59183. return len;
  59184. }
  59185. /* NULL or constants 0 or 1 */
  59186. return 0;
  59187. }
  59188. /*
  59189. ** Deserialize the data blob pointed to by buf as serial type serial_type
  59190. ** and store the result in pMem. Return the number of bytes read.
  59191. */
  59192. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  59193. const unsigned char *buf, /* Buffer to deserialize from */
  59194. u32 serial_type, /* Serial type to deserialize */
  59195. Mem *pMem /* Memory cell to write value into */
  59196. ){
  59197. switch( serial_type ){
  59198. case 10: /* Reserved for future use */
  59199. case 11: /* Reserved for future use */
  59200. case 0: { /* NULL */
  59201. pMem->flags = MEM_Null;
  59202. break;
  59203. }
  59204. case 1: { /* 1-byte signed integer */
  59205. pMem->u.i = (signed char)buf[0];
  59206. pMem->flags = MEM_Int;
  59207. return 1;
  59208. }
  59209. case 2: { /* 2-byte signed integer */
  59210. pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
  59211. pMem->flags = MEM_Int;
  59212. return 2;
  59213. }
  59214. case 3: { /* 3-byte signed integer */
  59215. pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
  59216. pMem->flags = MEM_Int;
  59217. return 3;
  59218. }
  59219. case 4: { /* 4-byte signed integer */
  59220. pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  59221. pMem->flags = MEM_Int;
  59222. return 4;
  59223. }
  59224. case 5: { /* 6-byte signed integer */
  59225. u64 x = (((signed char)buf[0])<<8) | buf[1];
  59226. u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  59227. x = (x<<32) | y;
  59228. pMem->u.i = *(i64*)&x;
  59229. pMem->flags = MEM_Int;
  59230. return 6;
  59231. }
  59232. case 6: /* 8-byte signed integer */
  59233. case 7: { /* IEEE floating point */
  59234. u64 x;
  59235. u32 y;
  59236. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  59237. /* Verify that integers and floating point values use the same
  59238. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  59239. ** defined that 64-bit floating point values really are mixed
  59240. ** endian.
  59241. */
  59242. static const u64 t1 = ((u64)0x3ff00000)<<32;
  59243. static const double r1 = 1.0;
  59244. u64 t2 = t1;
  59245. swapMixedEndianFloat(t2);
  59246. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  59247. #endif
  59248. x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  59249. y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
  59250. x = (x<<32) | y;
  59251. if( serial_type==6 ){
  59252. pMem->u.i = *(i64*)&x;
  59253. pMem->flags = MEM_Int;
  59254. }else{
  59255. assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  59256. swapMixedEndianFloat(x);
  59257. memcpy(&pMem->r, &x, sizeof(x));
  59258. pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
  59259. }
  59260. return 8;
  59261. }
  59262. case 8: /* Integer 0 */
  59263. case 9: { /* Integer 1 */
  59264. pMem->u.i = serial_type-8;
  59265. pMem->flags = MEM_Int;
  59266. return 0;
  59267. }
  59268. default: {
  59269. u32 len = (serial_type-12)/2;
  59270. pMem->z = (char *)buf;
  59271. pMem->n = len;
  59272. pMem->xDel = 0;
  59273. if( serial_type&0x01 ){
  59274. pMem->flags = MEM_Str | MEM_Ephem;
  59275. }else{
  59276. pMem->flags = MEM_Blob | MEM_Ephem;
  59277. }
  59278. return len;
  59279. }
  59280. }
  59281. return 0;
  59282. }
  59283. /*
  59284. ** This routine is used to allocate sufficient space for an UnpackedRecord
  59285. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  59286. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  59287. **
  59288. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  59289. ** the unaligned buffer passed via the second and third arguments (presumably
  59290. ** stack space). If the former, then *ppFree is set to a pointer that should
  59291. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  59292. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  59293. ** before returning.
  59294. **
  59295. ** If an OOM error occurs, NULL is returned.
  59296. */
  59297. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  59298. KeyInfo *pKeyInfo, /* Description of the record */
  59299. char *pSpace, /* Unaligned space available */
  59300. int szSpace, /* Size of pSpace[] in bytes */
  59301. char **ppFree /* OUT: Caller should free this pointer */
  59302. ){
  59303. UnpackedRecord *p; /* Unpacked record to return */
  59304. int nOff; /* Increment pSpace by nOff to align it */
  59305. int nByte; /* Number of bytes required for *p */
  59306. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  59307. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  59308. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  59309. */
  59310. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  59311. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  59312. if( nByte>szSpace+nOff ){
  59313. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  59314. *ppFree = (char *)p;
  59315. if( !p ) return 0;
  59316. }else{
  59317. p = (UnpackedRecord*)&pSpace[nOff];
  59318. *ppFree = 0;
  59319. }
  59320. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  59321. assert( pKeyInfo->aSortOrder!=0 );
  59322. p->pKeyInfo = pKeyInfo;
  59323. p->nField = pKeyInfo->nField + 1;
  59324. return p;
  59325. }
  59326. /*
  59327. ** Given the nKey-byte encoding of a record in pKey[], populate the
  59328. ** UnpackedRecord structure indicated by the fourth argument with the
  59329. ** contents of the decoded record.
  59330. */
  59331. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  59332. KeyInfo *pKeyInfo, /* Information about the record format */
  59333. int nKey, /* Size of the binary record */
  59334. const void *pKey, /* The binary record */
  59335. UnpackedRecord *p /* Populate this structure before returning. */
  59336. ){
  59337. const unsigned char *aKey = (const unsigned char *)pKey;
  59338. int d;
  59339. u32 idx; /* Offset in aKey[] to read from */
  59340. u16 u; /* Unsigned loop counter */
  59341. u32 szHdr;
  59342. Mem *pMem = p->aMem;
  59343. p->flags = 0;
  59344. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  59345. idx = getVarint32(aKey, szHdr);
  59346. d = szHdr;
  59347. u = 0;
  59348. while( idx<szHdr && u<p->nField && d<=nKey ){
  59349. u32 serial_type;
  59350. idx += getVarint32(&aKey[idx], serial_type);
  59351. pMem->enc = pKeyInfo->enc;
  59352. pMem->db = pKeyInfo->db;
  59353. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  59354. pMem->zMalloc = 0;
  59355. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  59356. pMem++;
  59357. u++;
  59358. }
  59359. assert( u<=pKeyInfo->nField + 1 );
  59360. p->nField = u;
  59361. }
  59362. /*
  59363. ** This function compares the two table rows or index records
  59364. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  59365. ** or positive integer if key1 is less than, equal to or
  59366. ** greater than key2. The {nKey1, pKey1} key must be a blob
  59367. ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
  59368. ** key must be a parsed key such as obtained from
  59369. ** sqlite3VdbeParseRecord.
  59370. **
  59371. ** Key1 and Key2 do not have to contain the same number of fields.
  59372. ** The key with fewer fields is usually compares less than the
  59373. ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
  59374. ** and the common prefixes are equal, then key1 is less than key2.
  59375. ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
  59376. ** equal, then the keys are considered to be equal and
  59377. ** the parts beyond the common prefix are ignored.
  59378. */
  59379. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  59380. int nKey1, const void *pKey1, /* Left key */
  59381. UnpackedRecord *pPKey2 /* Right key */
  59382. ){
  59383. u32 d1; /* Offset into aKey[] of next data element */
  59384. u32 idx1; /* Offset into aKey[] of next header element */
  59385. u32 szHdr1; /* Number of bytes in header */
  59386. int i = 0;
  59387. int rc = 0;
  59388. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  59389. KeyInfo *pKeyInfo;
  59390. Mem mem1;
  59391. pKeyInfo = pPKey2->pKeyInfo;
  59392. mem1.enc = pKeyInfo->enc;
  59393. mem1.db = pKeyInfo->db;
  59394. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  59395. VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
  59396. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  59397. ** We could initialize it, as shown here, to silence those complaints.
  59398. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  59399. ** the unnecessary initialization has a measurable negative performance
  59400. ** impact, since this routine is a very high runner. And so, we choose
  59401. ** to ignore the compiler warnings and leave this variable uninitialized.
  59402. */
  59403. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  59404. idx1 = getVarint32(aKey1, szHdr1);
  59405. d1 = szHdr1;
  59406. assert( pKeyInfo->nField+1>=pPKey2->nField );
  59407. assert( pKeyInfo->aSortOrder!=0 );
  59408. while( idx1<szHdr1 && i<pPKey2->nField ){
  59409. u32 serial_type1;
  59410. /* Read the serial types for the next element in each key. */
  59411. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  59412. /* Verify that there is enough key space remaining to avoid
  59413. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  59414. ** always be greater than or equal to the amount of required key space.
  59415. ** Use that approximation to avoid the more expensive call to
  59416. ** sqlite3VdbeSerialTypeLen() in the common case.
  59417. */
  59418. if( d1+serial_type1+2>(u32)nKey1
  59419. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  59420. ){
  59421. break;
  59422. }
  59423. /* Extract the values to be compared.
  59424. */
  59425. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  59426. /* Do the comparison
  59427. */
  59428. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  59429. if( rc!=0 ){
  59430. assert( mem1.zMalloc==0 ); /* See comment below */
  59431. /* Invert the result if we are using DESC sort order. */
  59432. if( pKeyInfo->aSortOrder[i] ){
  59433. rc = -rc;
  59434. }
  59435. /* If the PREFIX_SEARCH flag is set and all fields except the final
  59436. ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
  59437. ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
  59438. ** This is used by the OP_IsUnique opcode.
  59439. */
  59440. if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
  59441. assert( idx1==szHdr1 && rc );
  59442. assert( mem1.flags & MEM_Int );
  59443. pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
  59444. pPKey2->rowid = mem1.u.i;
  59445. }
  59446. return rc;
  59447. }
  59448. i++;
  59449. }
  59450. /* No memory allocation is ever used on mem1. Prove this using
  59451. ** the following assert(). If the assert() fails, it indicates a
  59452. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  59453. */
  59454. assert( mem1.zMalloc==0 );
  59455. /* rc==0 here means that one of the keys ran out of fields and
  59456. ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
  59457. ** flag is set, then break the tie by treating key2 as larger.
  59458. ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
  59459. ** are considered to be equal. Otherwise, the longer key is the
  59460. ** larger. As it happens, the pPKey2 will always be the longer
  59461. ** if there is a difference.
  59462. */
  59463. assert( rc==0 );
  59464. if( pPKey2->flags & UNPACKED_INCRKEY ){
  59465. rc = -1;
  59466. }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
  59467. /* Leave rc==0 */
  59468. }else if( idx1<szHdr1 ){
  59469. rc = 1;
  59470. }
  59471. return rc;
  59472. }
  59473. /*
  59474. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  59475. ** Read the rowid (the last field in the record) and store it in *rowid.
  59476. ** Return SQLITE_OK if everything works, or an error code otherwise.
  59477. **
  59478. ** pCur might be pointing to text obtained from a corrupt database file.
  59479. ** So the content cannot be trusted. Do appropriate checks on the content.
  59480. */
  59481. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  59482. i64 nCellKey = 0;
  59483. int rc;
  59484. u32 szHdr; /* Size of the header */
  59485. u32 typeRowid; /* Serial type of the rowid */
  59486. u32 lenRowid; /* Size of the rowid */
  59487. Mem m, v;
  59488. UNUSED_PARAMETER(db);
  59489. /* Get the size of the index entry. Only indices entries of less
  59490. ** than 2GiB are support - anything large must be database corruption.
  59491. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  59492. ** this code can safely assume that nCellKey is 32-bits
  59493. */
  59494. assert( sqlite3BtreeCursorIsValid(pCur) );
  59495. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  59496. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  59497. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  59498. /* Read in the complete content of the index entry */
  59499. memset(&m, 0, sizeof(m));
  59500. rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
  59501. if( rc ){
  59502. return rc;
  59503. }
  59504. /* The index entry must begin with a header size */
  59505. (void)getVarint32((u8*)m.z, szHdr);
  59506. testcase( szHdr==3 );
  59507. testcase( szHdr==m.n );
  59508. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  59509. goto idx_rowid_corruption;
  59510. }
  59511. /* The last field of the index should be an integer - the ROWID.
  59512. ** Verify that the last entry really is an integer. */
  59513. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  59514. testcase( typeRowid==1 );
  59515. testcase( typeRowid==2 );
  59516. testcase( typeRowid==3 );
  59517. testcase( typeRowid==4 );
  59518. testcase( typeRowid==5 );
  59519. testcase( typeRowid==6 );
  59520. testcase( typeRowid==8 );
  59521. testcase( typeRowid==9 );
  59522. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  59523. goto idx_rowid_corruption;
  59524. }
  59525. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  59526. testcase( (u32)m.n==szHdr+lenRowid );
  59527. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  59528. goto idx_rowid_corruption;
  59529. }
  59530. /* Fetch the integer off the end of the index record */
  59531. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  59532. *rowid = v.u.i;
  59533. sqlite3VdbeMemRelease(&m);
  59534. return SQLITE_OK;
  59535. /* Jump here if database corruption is detected after m has been
  59536. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  59537. idx_rowid_corruption:
  59538. testcase( m.zMalloc!=0 );
  59539. sqlite3VdbeMemRelease(&m);
  59540. return SQLITE_CORRUPT_BKPT;
  59541. }
  59542. /*
  59543. ** Compare the key of the index entry that cursor pC is pointing to against
  59544. ** the key string in pUnpacked. Write into *pRes a number
  59545. ** that is negative, zero, or positive if pC is less than, equal to,
  59546. ** or greater than pUnpacked. Return SQLITE_OK on success.
  59547. **
  59548. ** pUnpacked is either created without a rowid or is truncated so that it
  59549. ** omits the rowid at the end. The rowid at the end of the index entry
  59550. ** is ignored as well. Hence, this routine only compares the prefixes
  59551. ** of the keys prior to the final rowid, not the entire key.
  59552. */
  59553. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  59554. VdbeCursor *pC, /* The cursor to compare against */
  59555. UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
  59556. int *res /* Write the comparison result here */
  59557. ){
  59558. i64 nCellKey = 0;
  59559. int rc;
  59560. BtCursor *pCur = pC->pCursor;
  59561. Mem m;
  59562. assert( sqlite3BtreeCursorIsValid(pCur) );
  59563. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  59564. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  59565. /* nCellKey will always be between 0 and 0xffffffff because of the say
  59566. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  59567. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  59568. *res = 0;
  59569. return SQLITE_CORRUPT_BKPT;
  59570. }
  59571. memset(&m, 0, sizeof(m));
  59572. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
  59573. if( rc ){
  59574. return rc;
  59575. }
  59576. assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
  59577. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  59578. sqlite3VdbeMemRelease(&m);
  59579. return SQLITE_OK;
  59580. }
  59581. /*
  59582. ** This routine sets the value to be returned by subsequent calls to
  59583. ** sqlite3_changes() on the database handle 'db'.
  59584. */
  59585. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  59586. assert( sqlite3_mutex_held(db->mutex) );
  59587. db->nChange = nChange;
  59588. db->nTotalChange += nChange;
  59589. }
  59590. /*
  59591. ** Set a flag in the vdbe to update the change counter when it is finalised
  59592. ** or reset.
  59593. */
  59594. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  59595. v->changeCntOn = 1;
  59596. }
  59597. /*
  59598. ** Mark every prepared statement associated with a database connection
  59599. ** as expired.
  59600. **
  59601. ** An expired statement means that recompilation of the statement is
  59602. ** recommend. Statements expire when things happen that make their
  59603. ** programs obsolete. Removing user-defined functions or collating
  59604. ** sequences, or changing an authorization function are the types of
  59605. ** things that make prepared statements obsolete.
  59606. */
  59607. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  59608. Vdbe *p;
  59609. for(p = db->pVdbe; p; p=p->pNext){
  59610. p->expired = 1;
  59611. }
  59612. }
  59613. /*
  59614. ** Return the database associated with the Vdbe.
  59615. */
  59616. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  59617. return v->db;
  59618. }
  59619. /*
  59620. ** Return a pointer to an sqlite3_value structure containing the value bound
  59621. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  59622. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  59623. ** constants) to the value before returning it.
  59624. **
  59625. ** The returned value must be freed by the caller using sqlite3ValueFree().
  59626. */
  59627. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  59628. assert( iVar>0 );
  59629. if( v ){
  59630. Mem *pMem = &v->aVar[iVar-1];
  59631. if( 0==(pMem->flags & MEM_Null) ){
  59632. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  59633. if( pRet ){
  59634. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  59635. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  59636. sqlite3VdbeMemStoreType((Mem *)pRet);
  59637. }
  59638. return pRet;
  59639. }
  59640. }
  59641. return 0;
  59642. }
  59643. /*
  59644. ** Configure SQL variable iVar so that binding a new value to it signals
  59645. ** to sqlite3_reoptimize() that re-preparing the statement may result
  59646. ** in a better query plan.
  59647. */
  59648. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  59649. assert( iVar>0 );
  59650. if( iVar>32 ){
  59651. v->expmask = 0xffffffff;
  59652. }else{
  59653. v->expmask |= ((u32)1 << (iVar-1));
  59654. }
  59655. }
  59656. #ifndef SQLITE_OMIT_VIRTUALTABLE
  59657. /*
  59658. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  59659. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  59660. ** in memory obtained from sqlite3DbMalloc).
  59661. */
  59662. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  59663. sqlite3 *db = p->db;
  59664. sqlite3DbFree(db, p->zErrMsg);
  59665. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  59666. sqlite3_free(pVtab->zErrMsg);
  59667. pVtab->zErrMsg = 0;
  59668. }
  59669. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  59670. /************** End of vdbeaux.c *********************************************/
  59671. /************** Begin file vdbeapi.c *****************************************/
  59672. /*
  59673. ** 2004 May 26
  59674. **
  59675. ** The author disclaims copyright to this source code. In place of
  59676. ** a legal notice, here is a blessing:
  59677. **
  59678. ** May you do good and not evil.
  59679. ** May you find forgiveness for yourself and forgive others.
  59680. ** May you share freely, never taking more than you give.
  59681. **
  59682. *************************************************************************
  59683. **
  59684. ** This file contains code use to implement APIs that are part of the
  59685. ** VDBE.
  59686. */
  59687. #ifndef SQLITE_OMIT_DEPRECATED
  59688. /*
  59689. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  59690. ** to be recompiled. A statement needs to be recompiled whenever the
  59691. ** execution environment changes in a way that would alter the program
  59692. ** that sqlite3_prepare() generates. For example, if new functions or
  59693. ** collating sequences are registered or if an authorizer function is
  59694. ** added or changed.
  59695. */
  59696. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  59697. Vdbe *p = (Vdbe*)pStmt;
  59698. return p==0 || p->expired;
  59699. }
  59700. #endif
  59701. /*
  59702. ** Check on a Vdbe to make sure it has not been finalized. Log
  59703. ** an error and return true if it has been finalized (or is otherwise
  59704. ** invalid). Return false if it is ok.
  59705. */
  59706. static int vdbeSafety(Vdbe *p){
  59707. if( p->db==0 ){
  59708. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  59709. return 1;
  59710. }else{
  59711. return 0;
  59712. }
  59713. }
  59714. static int vdbeSafetyNotNull(Vdbe *p){
  59715. if( p==0 ){
  59716. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  59717. return 1;
  59718. }else{
  59719. return vdbeSafety(p);
  59720. }
  59721. }
  59722. /*
  59723. ** The following routine destroys a virtual machine that is created by
  59724. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  59725. ** success/failure code that describes the result of executing the virtual
  59726. ** machine.
  59727. **
  59728. ** This routine sets the error code and string returned by
  59729. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  59730. */
  59731. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  59732. int rc;
  59733. if( pStmt==0 ){
  59734. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  59735. ** pointer is a harmless no-op. */
  59736. rc = SQLITE_OK;
  59737. }else{
  59738. Vdbe *v = (Vdbe*)pStmt;
  59739. sqlite3 *db = v->db;
  59740. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  59741. sqlite3_mutex_enter(db->mutex);
  59742. rc = sqlite3VdbeFinalize(v);
  59743. rc = sqlite3ApiExit(db, rc);
  59744. sqlite3LeaveMutexAndCloseZombie(db);
  59745. }
  59746. return rc;
  59747. }
  59748. /*
  59749. ** Terminate the current execution of an SQL statement and reset it
  59750. ** back to its starting state so that it can be reused. A success code from
  59751. ** the prior execution is returned.
  59752. **
  59753. ** This routine sets the error code and string returned by
  59754. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  59755. */
  59756. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  59757. int rc;
  59758. if( pStmt==0 ){
  59759. rc = SQLITE_OK;
  59760. }else{
  59761. Vdbe *v = (Vdbe*)pStmt;
  59762. sqlite3_mutex_enter(v->db->mutex);
  59763. rc = sqlite3VdbeReset(v);
  59764. sqlite3VdbeRewind(v);
  59765. assert( (rc & (v->db->errMask))==rc );
  59766. rc = sqlite3ApiExit(v->db, rc);
  59767. sqlite3_mutex_leave(v->db->mutex);
  59768. }
  59769. return rc;
  59770. }
  59771. /*
  59772. ** Set all the parameters in the compiled SQL statement to NULL.
  59773. */
  59774. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  59775. int i;
  59776. int rc = SQLITE_OK;
  59777. Vdbe *p = (Vdbe*)pStmt;
  59778. #if SQLITE_THREADSAFE
  59779. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  59780. #endif
  59781. sqlite3_mutex_enter(mutex);
  59782. for(i=0; i<p->nVar; i++){
  59783. sqlite3VdbeMemRelease(&p->aVar[i]);
  59784. p->aVar[i].flags = MEM_Null;
  59785. }
  59786. if( p->isPrepareV2 && p->expmask ){
  59787. p->expired = 1;
  59788. }
  59789. sqlite3_mutex_leave(mutex);
  59790. return rc;
  59791. }
  59792. /**************************** sqlite3_value_ *******************************
  59793. ** The following routines extract information from a Mem or sqlite3_value
  59794. ** structure.
  59795. */
  59796. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  59797. Mem *p = (Mem*)pVal;
  59798. if( p->flags & (MEM_Blob|MEM_Str) ){
  59799. sqlite3VdbeMemExpandBlob(p);
  59800. p->flags &= ~MEM_Str;
  59801. p->flags |= MEM_Blob;
  59802. return p->n ? p->z : 0;
  59803. }else{
  59804. return sqlite3_value_text(pVal);
  59805. }
  59806. }
  59807. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  59808. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  59809. }
  59810. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  59811. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  59812. }
  59813. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  59814. return sqlite3VdbeRealValue((Mem*)pVal);
  59815. }
  59816. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  59817. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  59818. }
  59819. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  59820. return sqlite3VdbeIntValue((Mem*)pVal);
  59821. }
  59822. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  59823. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  59824. }
  59825. #ifndef SQLITE_OMIT_UTF16
  59826. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  59827. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  59828. }
  59829. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  59830. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  59831. }
  59832. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  59833. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  59834. }
  59835. #endif /* SQLITE_OMIT_UTF16 */
  59836. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  59837. return pVal->type;
  59838. }
  59839. /**************************** sqlite3_result_ *******************************
  59840. ** The following routines are used by user-defined functions to specify
  59841. ** the function result.
  59842. **
  59843. ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
  59844. ** result as a string or blob but if the string or blob is too large, it
  59845. ** then sets the error code to SQLITE_TOOBIG
  59846. */
  59847. static void setResultStrOrError(
  59848. sqlite3_context *pCtx, /* Function context */
  59849. const char *z, /* String pointer */
  59850. int n, /* Bytes in string, or negative */
  59851. u8 enc, /* Encoding of z. 0 for BLOBs */
  59852. void (*xDel)(void*) /* Destructor function */
  59853. ){
  59854. if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
  59855. sqlite3_result_error_toobig(pCtx);
  59856. }
  59857. }
  59858. SQLITE_API void sqlite3_result_blob(
  59859. sqlite3_context *pCtx,
  59860. const void *z,
  59861. int n,
  59862. void (*xDel)(void *)
  59863. ){
  59864. assert( n>=0 );
  59865. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59866. setResultStrOrError(pCtx, z, n, 0, xDel);
  59867. }
  59868. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  59869. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59870. sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
  59871. }
  59872. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  59873. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59874. pCtx->isError = SQLITE_ERROR;
  59875. pCtx->fErrorOrAux = 1;
  59876. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  59877. }
  59878. #ifndef SQLITE_OMIT_UTF16
  59879. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  59880. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59881. pCtx->isError = SQLITE_ERROR;
  59882. pCtx->fErrorOrAux = 1;
  59883. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  59884. }
  59885. #endif
  59886. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  59887. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59888. sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
  59889. }
  59890. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  59891. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59892. sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
  59893. }
  59894. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  59895. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59896. sqlite3VdbeMemSetNull(&pCtx->s);
  59897. }
  59898. SQLITE_API void sqlite3_result_text(
  59899. sqlite3_context *pCtx,
  59900. const char *z,
  59901. int n,
  59902. void (*xDel)(void *)
  59903. ){
  59904. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59905. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  59906. }
  59907. #ifndef SQLITE_OMIT_UTF16
  59908. SQLITE_API void sqlite3_result_text16(
  59909. sqlite3_context *pCtx,
  59910. const void *z,
  59911. int n,
  59912. void (*xDel)(void *)
  59913. ){
  59914. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59915. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  59916. }
  59917. SQLITE_API void sqlite3_result_text16be(
  59918. sqlite3_context *pCtx,
  59919. const void *z,
  59920. int n,
  59921. void (*xDel)(void *)
  59922. ){
  59923. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59924. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  59925. }
  59926. SQLITE_API void sqlite3_result_text16le(
  59927. sqlite3_context *pCtx,
  59928. const void *z,
  59929. int n,
  59930. void (*xDel)(void *)
  59931. ){
  59932. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59933. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  59934. }
  59935. #endif /* SQLITE_OMIT_UTF16 */
  59936. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  59937. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59938. sqlite3VdbeMemCopy(&pCtx->s, pValue);
  59939. }
  59940. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  59941. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59942. sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
  59943. }
  59944. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  59945. pCtx->isError = errCode;
  59946. pCtx->fErrorOrAux = 1;
  59947. if( pCtx->s.flags & MEM_Null ){
  59948. sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
  59949. SQLITE_UTF8, SQLITE_STATIC);
  59950. }
  59951. }
  59952. /* Force an SQLITE_TOOBIG error. */
  59953. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  59954. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59955. pCtx->isError = SQLITE_TOOBIG;
  59956. pCtx->fErrorOrAux = 1;
  59957. sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
  59958. SQLITE_UTF8, SQLITE_STATIC);
  59959. }
  59960. /* An SQLITE_NOMEM error. */
  59961. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  59962. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59963. sqlite3VdbeMemSetNull(&pCtx->s);
  59964. pCtx->isError = SQLITE_NOMEM;
  59965. pCtx->fErrorOrAux = 1;
  59966. pCtx->s.db->mallocFailed = 1;
  59967. }
  59968. /*
  59969. ** This function is called after a transaction has been committed. It
  59970. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  59971. */
  59972. static int doWalCallbacks(sqlite3 *db){
  59973. int rc = SQLITE_OK;
  59974. #ifndef SQLITE_OMIT_WAL
  59975. int i;
  59976. for(i=0; i<db->nDb; i++){
  59977. Btree *pBt = db->aDb[i].pBt;
  59978. if( pBt ){
  59979. int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  59980. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  59981. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  59982. }
  59983. }
  59984. }
  59985. #endif
  59986. return rc;
  59987. }
  59988. /*
  59989. ** Execute the statement pStmt, either until a row of data is ready, the
  59990. ** statement is completely executed or an error occurs.
  59991. **
  59992. ** This routine implements the bulk of the logic behind the sqlite_step()
  59993. ** API. The only thing omitted is the automatic recompile if a
  59994. ** schema change has occurred. That detail is handled by the
  59995. ** outer sqlite3_step() wrapper procedure.
  59996. */
  59997. static int sqlite3Step(Vdbe *p){
  59998. sqlite3 *db;
  59999. int rc;
  60000. assert(p);
  60001. if( p->magic!=VDBE_MAGIC_RUN ){
  60002. /* We used to require that sqlite3_reset() be called before retrying
  60003. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  60004. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  60005. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  60006. ** This "automatic-reset" change is not technically an incompatibility,
  60007. ** since any application that receives an SQLITE_MISUSE is broken by
  60008. ** definition.
  60009. **
  60010. ** Nevertheless, some published applications that were originally written
  60011. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  60012. ** returns, and those were broken by the automatic-reset change. As a
  60013. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  60014. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  60015. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  60016. ** or SQLITE_BUSY error.
  60017. */
  60018. #ifdef SQLITE_OMIT_AUTORESET
  60019. if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
  60020. sqlite3_reset((sqlite3_stmt*)p);
  60021. }else{
  60022. return SQLITE_MISUSE_BKPT;
  60023. }
  60024. #else
  60025. sqlite3_reset((sqlite3_stmt*)p);
  60026. #endif
  60027. }
  60028. /* Check that malloc() has not failed. If it has, return early. */
  60029. db = p->db;
  60030. if( db->mallocFailed ){
  60031. p->rc = SQLITE_NOMEM;
  60032. return SQLITE_NOMEM;
  60033. }
  60034. if( p->pc<=0 && p->expired ){
  60035. p->rc = SQLITE_SCHEMA;
  60036. rc = SQLITE_ERROR;
  60037. goto end_of_step;
  60038. }
  60039. if( p->pc<0 ){
  60040. /* If there are no other statements currently running, then
  60041. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  60042. ** from interrupting a statement that has not yet started.
  60043. */
  60044. if( db->nVdbeActive==0 ){
  60045. db->u1.isInterrupted = 0;
  60046. }
  60047. assert( db->nVdbeWrite>0 || db->autoCommit==0
  60048. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  60049. );
  60050. #ifndef SQLITE_OMIT_TRACE
  60051. if( db->xProfile && !db->init.busy ){
  60052. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  60053. }
  60054. #endif
  60055. db->nVdbeActive++;
  60056. if( p->readOnly==0 ) db->nVdbeWrite++;
  60057. if( p->bIsReader ) db->nVdbeRead++;
  60058. p->pc = 0;
  60059. }
  60060. #ifndef SQLITE_OMIT_EXPLAIN
  60061. if( p->explain ){
  60062. rc = sqlite3VdbeList(p);
  60063. }else
  60064. #endif /* SQLITE_OMIT_EXPLAIN */
  60065. {
  60066. db->nVdbeExec++;
  60067. rc = sqlite3VdbeExec(p);
  60068. db->nVdbeExec--;
  60069. }
  60070. #ifndef SQLITE_OMIT_TRACE
  60071. /* Invoke the profile callback if there is one
  60072. */
  60073. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  60074. sqlite3_int64 iNow;
  60075. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  60076. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  60077. }
  60078. #endif
  60079. if( rc==SQLITE_DONE ){
  60080. assert( p->rc==SQLITE_OK );
  60081. p->rc = doWalCallbacks(db);
  60082. if( p->rc!=SQLITE_OK ){
  60083. rc = SQLITE_ERROR;
  60084. }
  60085. }
  60086. db->errCode = rc;
  60087. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  60088. p->rc = SQLITE_NOMEM;
  60089. }
  60090. end_of_step:
  60091. /* At this point local variable rc holds the value that should be
  60092. ** returned if this statement was compiled using the legacy
  60093. ** sqlite3_prepare() interface. According to the docs, this can only
  60094. ** be one of the values in the first assert() below. Variable p->rc
  60095. ** contains the value that would be returned if sqlite3_finalize()
  60096. ** were called on statement p.
  60097. */
  60098. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  60099. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  60100. );
  60101. assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  60102. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  60103. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  60104. ** error has occurred, then return the error code in p->rc to the
  60105. ** caller. Set the error code in the database handle to the same value.
  60106. */
  60107. rc = sqlite3VdbeTransferError(p);
  60108. }
  60109. return (rc&db->errMask);
  60110. }
  60111. /*
  60112. ** This is the top-level implementation of sqlite3_step(). Call
  60113. ** sqlite3Step() to do most of the work. If a schema error occurs,
  60114. ** call sqlite3Reprepare() and try again.
  60115. */
  60116. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  60117. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  60118. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  60119. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  60120. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  60121. sqlite3 *db; /* The database connection */
  60122. if( vdbeSafetyNotNull(v) ){
  60123. return SQLITE_MISUSE_BKPT;
  60124. }
  60125. db = v->db;
  60126. sqlite3_mutex_enter(db->mutex);
  60127. v->doingRerun = 0;
  60128. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  60129. && cnt++ < SQLITE_MAX_SCHEMA_RETRY
  60130. && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
  60131. sqlite3_reset(pStmt);
  60132. v->doingRerun = 1;
  60133. assert( v->expired==0 );
  60134. }
  60135. if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
  60136. /* This case occurs after failing to recompile an sql statement.
  60137. ** The error message from the SQL compiler has already been loaded
  60138. ** into the database handle. This block copies the error message
  60139. ** from the database handle into the statement and sets the statement
  60140. ** program counter to 0 to ensure that when the statement is
  60141. ** finalized or reset the parser error message is available via
  60142. ** sqlite3_errmsg() and sqlite3_errcode().
  60143. */
  60144. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  60145. sqlite3DbFree(db, v->zErrMsg);
  60146. if( !db->mallocFailed ){
  60147. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  60148. v->rc = rc2;
  60149. } else {
  60150. v->zErrMsg = 0;
  60151. v->rc = rc = SQLITE_NOMEM;
  60152. }
  60153. }
  60154. rc = sqlite3ApiExit(db, rc);
  60155. sqlite3_mutex_leave(db->mutex);
  60156. return rc;
  60157. }
  60158. /*
  60159. ** Extract the user data from a sqlite3_context structure and return a
  60160. ** pointer to it.
  60161. */
  60162. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  60163. assert( p && p->pFunc );
  60164. return p->pFunc->pUserData;
  60165. }
  60166. /*
  60167. ** Extract the user data from a sqlite3_context structure and return a
  60168. ** pointer to it.
  60169. **
  60170. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  60171. ** returns a copy of the pointer to the database connection (the 1st
  60172. ** parameter) of the sqlite3_create_function() and
  60173. ** sqlite3_create_function16() routines that originally registered the
  60174. ** application defined function.
  60175. */
  60176. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  60177. assert( p && p->pFunc );
  60178. return p->s.db;
  60179. }
  60180. /*
  60181. ** Return the current time for a statement
  60182. */
  60183. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  60184. Vdbe *v = p->pVdbe;
  60185. int rc;
  60186. if( v->iCurrentTime==0 ){
  60187. rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime);
  60188. if( rc ) v->iCurrentTime = 0;
  60189. }
  60190. return v->iCurrentTime;
  60191. }
  60192. /*
  60193. ** The following is the implementation of an SQL function that always
  60194. ** fails with an error message stating that the function is used in the
  60195. ** wrong context. The sqlite3_overload_function() API might construct
  60196. ** SQL function that use this routine so that the functions will exist
  60197. ** for name resolution but are actually overloaded by the xFindFunction
  60198. ** method of virtual tables.
  60199. */
  60200. SQLITE_PRIVATE void sqlite3InvalidFunction(
  60201. sqlite3_context *context, /* The function calling context */
  60202. int NotUsed, /* Number of arguments to the function */
  60203. sqlite3_value **NotUsed2 /* Value of each argument */
  60204. ){
  60205. const char *zName = context->pFunc->zName;
  60206. char *zErr;
  60207. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  60208. zErr = sqlite3_mprintf(
  60209. "unable to use function %s in the requested context", zName);
  60210. sqlite3_result_error(context, zErr, -1);
  60211. sqlite3_free(zErr);
  60212. }
  60213. /*
  60214. ** Allocate or return the aggregate context for a user function. A new
  60215. ** context is allocated on the first call. Subsequent calls return the
  60216. ** same context that was returned on prior calls.
  60217. */
  60218. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  60219. Mem *pMem;
  60220. assert( p && p->pFunc && p->pFunc->xStep );
  60221. assert( sqlite3_mutex_held(p->s.db->mutex) );
  60222. pMem = p->pMem;
  60223. testcase( nByte<0 );
  60224. if( (pMem->flags & MEM_Agg)==0 ){
  60225. if( nByte<=0 ){
  60226. sqlite3VdbeMemReleaseExternal(pMem);
  60227. pMem->flags = MEM_Null;
  60228. pMem->z = 0;
  60229. }else{
  60230. sqlite3VdbeMemGrow(pMem, nByte, 0);
  60231. pMem->flags = MEM_Agg;
  60232. pMem->u.pDef = p->pFunc;
  60233. if( pMem->z ){
  60234. memset(pMem->z, 0, nByte);
  60235. }
  60236. }
  60237. }
  60238. return (void*)pMem->z;
  60239. }
  60240. /*
  60241. ** Return the auxilary data pointer, if any, for the iArg'th argument to
  60242. ** the user-function defined by pCtx.
  60243. */
  60244. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  60245. AuxData *pAuxData;
  60246. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  60247. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  60248. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  60249. }
  60250. return (pAuxData ? pAuxData->pAux : 0);
  60251. }
  60252. /*
  60253. ** Set the auxilary data pointer and delete function, for the iArg'th
  60254. ** argument to the user-function defined by pCtx. Any previous value is
  60255. ** deleted by calling the delete function specified when it was set.
  60256. */
  60257. SQLITE_API void sqlite3_set_auxdata(
  60258. sqlite3_context *pCtx,
  60259. int iArg,
  60260. void *pAux,
  60261. void (*xDelete)(void*)
  60262. ){
  60263. AuxData *pAuxData;
  60264. Vdbe *pVdbe = pCtx->pVdbe;
  60265. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  60266. if( iArg<0 ) goto failed;
  60267. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  60268. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  60269. }
  60270. if( pAuxData==0 ){
  60271. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  60272. if( !pAuxData ) goto failed;
  60273. pAuxData->iOp = pCtx->iOp;
  60274. pAuxData->iArg = iArg;
  60275. pAuxData->pNext = pVdbe->pAuxData;
  60276. pVdbe->pAuxData = pAuxData;
  60277. if( pCtx->fErrorOrAux==0 ){
  60278. pCtx->isError = 0;
  60279. pCtx->fErrorOrAux = 1;
  60280. }
  60281. }else if( pAuxData->xDelete ){
  60282. pAuxData->xDelete(pAuxData->pAux);
  60283. }
  60284. pAuxData->pAux = pAux;
  60285. pAuxData->xDelete = xDelete;
  60286. return;
  60287. failed:
  60288. if( xDelete ){
  60289. xDelete(pAux);
  60290. }
  60291. }
  60292. #ifndef SQLITE_OMIT_DEPRECATED
  60293. /*
  60294. ** Return the number of times the Step function of a aggregate has been
  60295. ** called.
  60296. **
  60297. ** This function is deprecated. Do not use it for new code. It is
  60298. ** provide only to avoid breaking legacy code. New aggregate function
  60299. ** implementations should keep their own counts within their aggregate
  60300. ** context.
  60301. */
  60302. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  60303. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  60304. return p->pMem->n;
  60305. }
  60306. #endif
  60307. /*
  60308. ** Return the number of columns in the result set for the statement pStmt.
  60309. */
  60310. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  60311. Vdbe *pVm = (Vdbe *)pStmt;
  60312. return pVm ? pVm->nResColumn : 0;
  60313. }
  60314. /*
  60315. ** Return the number of values available from the current row of the
  60316. ** currently executing statement pStmt.
  60317. */
  60318. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  60319. Vdbe *pVm = (Vdbe *)pStmt;
  60320. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  60321. return pVm->nResColumn;
  60322. }
  60323. /*
  60324. ** Check to see if column iCol of the given statement is valid. If
  60325. ** it is, return a pointer to the Mem for the value of that column.
  60326. ** If iCol is not valid, return a pointer to a Mem which has a value
  60327. ** of NULL.
  60328. */
  60329. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  60330. Vdbe *pVm;
  60331. Mem *pOut;
  60332. pVm = (Vdbe *)pStmt;
  60333. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  60334. sqlite3_mutex_enter(pVm->db->mutex);
  60335. pOut = &pVm->pResultSet[i];
  60336. }else{
  60337. /* If the value passed as the second argument is out of range, return
  60338. ** a pointer to the following static Mem object which contains the
  60339. ** value SQL NULL. Even though the Mem structure contains an element
  60340. ** of type i64, on certain architectures (x86) with certain compiler
  60341. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  60342. ** instead of an 8-byte one. This all works fine, except that when
  60343. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  60344. ** that a Mem structure is located on an 8-byte boundary. To prevent
  60345. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  60346. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  60347. ** __attribute__((aligned(8))) macro. */
  60348. static const Mem nullMem
  60349. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  60350. __attribute__((aligned(8)))
  60351. #endif
  60352. = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
  60353. #ifdef SQLITE_DEBUG
  60354. 0, 0, /* pScopyFrom, pFiller */
  60355. #endif
  60356. 0, 0 };
  60357. if( pVm && ALWAYS(pVm->db) ){
  60358. sqlite3_mutex_enter(pVm->db->mutex);
  60359. sqlite3Error(pVm->db, SQLITE_RANGE, 0);
  60360. }
  60361. pOut = (Mem*)&nullMem;
  60362. }
  60363. return pOut;
  60364. }
  60365. /*
  60366. ** This function is called after invoking an sqlite3_value_XXX function on a
  60367. ** column value (i.e. a value returned by evaluating an SQL expression in the
  60368. ** select list of a SELECT statement) that may cause a malloc() failure. If
  60369. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  60370. ** code of statement pStmt set to SQLITE_NOMEM.
  60371. **
  60372. ** Specifically, this is called from within:
  60373. **
  60374. ** sqlite3_column_int()
  60375. ** sqlite3_column_int64()
  60376. ** sqlite3_column_text()
  60377. ** sqlite3_column_text16()
  60378. ** sqlite3_column_real()
  60379. ** sqlite3_column_bytes()
  60380. ** sqlite3_column_bytes16()
  60381. ** sqiite3_column_blob()
  60382. */
  60383. static void columnMallocFailure(sqlite3_stmt *pStmt)
  60384. {
  60385. /* If malloc() failed during an encoding conversion within an
  60386. ** sqlite3_column_XXX API, then set the return code of the statement to
  60387. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  60388. ** and _finalize() will return NOMEM.
  60389. */
  60390. Vdbe *p = (Vdbe *)pStmt;
  60391. if( p ){
  60392. p->rc = sqlite3ApiExit(p->db, p->rc);
  60393. sqlite3_mutex_leave(p->db->mutex);
  60394. }
  60395. }
  60396. /**************************** sqlite3_column_ *******************************
  60397. ** The following routines are used to access elements of the current row
  60398. ** in the result set.
  60399. */
  60400. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  60401. const void *val;
  60402. val = sqlite3_value_blob( columnMem(pStmt,i) );
  60403. /* Even though there is no encoding conversion, value_blob() might
  60404. ** need to call malloc() to expand the result of a zeroblob()
  60405. ** expression.
  60406. */
  60407. columnMallocFailure(pStmt);
  60408. return val;
  60409. }
  60410. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  60411. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  60412. columnMallocFailure(pStmt);
  60413. return val;
  60414. }
  60415. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  60416. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  60417. columnMallocFailure(pStmt);
  60418. return val;
  60419. }
  60420. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  60421. double val = sqlite3_value_double( columnMem(pStmt,i) );
  60422. columnMallocFailure(pStmt);
  60423. return val;
  60424. }
  60425. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  60426. int val = sqlite3_value_int( columnMem(pStmt,i) );
  60427. columnMallocFailure(pStmt);
  60428. return val;
  60429. }
  60430. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  60431. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  60432. columnMallocFailure(pStmt);
  60433. return val;
  60434. }
  60435. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  60436. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  60437. columnMallocFailure(pStmt);
  60438. return val;
  60439. }
  60440. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  60441. Mem *pOut = columnMem(pStmt, i);
  60442. if( pOut->flags&MEM_Static ){
  60443. pOut->flags &= ~MEM_Static;
  60444. pOut->flags |= MEM_Ephem;
  60445. }
  60446. columnMallocFailure(pStmt);
  60447. return (sqlite3_value *)pOut;
  60448. }
  60449. #ifndef SQLITE_OMIT_UTF16
  60450. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  60451. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  60452. columnMallocFailure(pStmt);
  60453. return val;
  60454. }
  60455. #endif /* SQLITE_OMIT_UTF16 */
  60456. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  60457. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  60458. columnMallocFailure(pStmt);
  60459. return iType;
  60460. }
  60461. /*
  60462. ** Convert the N-th element of pStmt->pColName[] into a string using
  60463. ** xFunc() then return that string. If N is out of range, return 0.
  60464. **
  60465. ** There are up to 5 names for each column. useType determines which
  60466. ** name is returned. Here are the names:
  60467. **
  60468. ** 0 The column name as it should be displayed for output
  60469. ** 1 The datatype name for the column
  60470. ** 2 The name of the database that the column derives from
  60471. ** 3 The name of the table that the column derives from
  60472. ** 4 The name of the table column that the result column derives from
  60473. **
  60474. ** If the result is not a simple column reference (if it is an expression
  60475. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  60476. */
  60477. static const void *columnName(
  60478. sqlite3_stmt *pStmt,
  60479. int N,
  60480. const void *(*xFunc)(Mem*),
  60481. int useType
  60482. ){
  60483. const void *ret = 0;
  60484. Vdbe *p = (Vdbe *)pStmt;
  60485. int n;
  60486. sqlite3 *db = p->db;
  60487. assert( db!=0 );
  60488. n = sqlite3_column_count(pStmt);
  60489. if( N<n && N>=0 ){
  60490. N += useType*n;
  60491. sqlite3_mutex_enter(db->mutex);
  60492. assert( db->mallocFailed==0 );
  60493. ret = xFunc(&p->aColName[N]);
  60494. /* A malloc may have failed inside of the xFunc() call. If this
  60495. ** is the case, clear the mallocFailed flag and return NULL.
  60496. */
  60497. if( db->mallocFailed ){
  60498. db->mallocFailed = 0;
  60499. ret = 0;
  60500. }
  60501. sqlite3_mutex_leave(db->mutex);
  60502. }
  60503. return ret;
  60504. }
  60505. /*
  60506. ** Return the name of the Nth column of the result set returned by SQL
  60507. ** statement pStmt.
  60508. */
  60509. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  60510. return columnName(
  60511. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  60512. }
  60513. #ifndef SQLITE_OMIT_UTF16
  60514. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  60515. return columnName(
  60516. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  60517. }
  60518. #endif
  60519. /*
  60520. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  60521. ** not define OMIT_DECLTYPE.
  60522. */
  60523. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  60524. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  60525. and SQLITE_ENABLE_COLUMN_METADATA"
  60526. #endif
  60527. #ifndef SQLITE_OMIT_DECLTYPE
  60528. /*
  60529. ** Return the column declaration type (if applicable) of the 'i'th column
  60530. ** of the result set of SQL statement pStmt.
  60531. */
  60532. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  60533. return columnName(
  60534. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  60535. }
  60536. #ifndef SQLITE_OMIT_UTF16
  60537. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  60538. return columnName(
  60539. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  60540. }
  60541. #endif /* SQLITE_OMIT_UTF16 */
  60542. #endif /* SQLITE_OMIT_DECLTYPE */
  60543. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  60544. /*
  60545. ** Return the name of the database from which a result column derives.
  60546. ** NULL is returned if the result column is an expression or constant or
  60547. ** anything else which is not an unabiguous reference to a database column.
  60548. */
  60549. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  60550. return columnName(
  60551. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  60552. }
  60553. #ifndef SQLITE_OMIT_UTF16
  60554. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  60555. return columnName(
  60556. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  60557. }
  60558. #endif /* SQLITE_OMIT_UTF16 */
  60559. /*
  60560. ** Return the name of the table from which a result column derives.
  60561. ** NULL is returned if the result column is an expression or constant or
  60562. ** anything else which is not an unabiguous reference to a database column.
  60563. */
  60564. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  60565. return columnName(
  60566. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  60567. }
  60568. #ifndef SQLITE_OMIT_UTF16
  60569. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  60570. return columnName(
  60571. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  60572. }
  60573. #endif /* SQLITE_OMIT_UTF16 */
  60574. /*
  60575. ** Return the name of the table column from which a result column derives.
  60576. ** NULL is returned if the result column is an expression or constant or
  60577. ** anything else which is not an unabiguous reference to a database column.
  60578. */
  60579. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  60580. return columnName(
  60581. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  60582. }
  60583. #ifndef SQLITE_OMIT_UTF16
  60584. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  60585. return columnName(
  60586. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  60587. }
  60588. #endif /* SQLITE_OMIT_UTF16 */
  60589. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  60590. /******************************* sqlite3_bind_ ***************************
  60591. **
  60592. ** Routines used to attach values to wildcards in a compiled SQL statement.
  60593. */
  60594. /*
  60595. ** Unbind the value bound to variable i in virtual machine p. This is the
  60596. ** the same as binding a NULL value to the column. If the "i" parameter is
  60597. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  60598. **
  60599. ** A successful evaluation of this routine acquires the mutex on p.
  60600. ** the mutex is released if any kind of error occurs.
  60601. **
  60602. ** The error code stored in database p->db is overwritten with the return
  60603. ** value in any case.
  60604. */
  60605. static int vdbeUnbind(Vdbe *p, int i){
  60606. Mem *pVar;
  60607. if( vdbeSafetyNotNull(p) ){
  60608. return SQLITE_MISUSE_BKPT;
  60609. }
  60610. sqlite3_mutex_enter(p->db->mutex);
  60611. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  60612. sqlite3Error(p->db, SQLITE_MISUSE, 0);
  60613. sqlite3_mutex_leave(p->db->mutex);
  60614. sqlite3_log(SQLITE_MISUSE,
  60615. "bind on a busy prepared statement: [%s]", p->zSql);
  60616. return SQLITE_MISUSE_BKPT;
  60617. }
  60618. if( i<1 || i>p->nVar ){
  60619. sqlite3Error(p->db, SQLITE_RANGE, 0);
  60620. sqlite3_mutex_leave(p->db->mutex);
  60621. return SQLITE_RANGE;
  60622. }
  60623. i--;
  60624. pVar = &p->aVar[i];
  60625. sqlite3VdbeMemRelease(pVar);
  60626. pVar->flags = MEM_Null;
  60627. sqlite3Error(p->db, SQLITE_OK, 0);
  60628. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  60629. ** binding a new value to this variable invalidates the current query plan.
  60630. **
  60631. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  60632. ** parameter in the WHERE clause might influence the choice of query plan
  60633. ** for a statement, then the statement will be automatically recompiled,
  60634. ** as if there had been a schema change, on the first sqlite3_step() call
  60635. ** following any change to the bindings of that parameter.
  60636. */
  60637. if( p->isPrepareV2 &&
  60638. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  60639. ){
  60640. p->expired = 1;
  60641. }
  60642. return SQLITE_OK;
  60643. }
  60644. /*
  60645. ** Bind a text or BLOB value.
  60646. */
  60647. static int bindText(
  60648. sqlite3_stmt *pStmt, /* The statement to bind against */
  60649. int i, /* Index of the parameter to bind */
  60650. const void *zData, /* Pointer to the data to be bound */
  60651. int nData, /* Number of bytes of data to be bound */
  60652. void (*xDel)(void*), /* Destructor for the data */
  60653. u8 encoding /* Encoding for the data */
  60654. ){
  60655. Vdbe *p = (Vdbe *)pStmt;
  60656. Mem *pVar;
  60657. int rc;
  60658. rc = vdbeUnbind(p, i);
  60659. if( rc==SQLITE_OK ){
  60660. if( zData!=0 ){
  60661. pVar = &p->aVar[i-1];
  60662. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  60663. if( rc==SQLITE_OK && encoding!=0 ){
  60664. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  60665. }
  60666. sqlite3Error(p->db, rc, 0);
  60667. rc = sqlite3ApiExit(p->db, rc);
  60668. }
  60669. sqlite3_mutex_leave(p->db->mutex);
  60670. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  60671. xDel((void*)zData);
  60672. }
  60673. return rc;
  60674. }
  60675. /*
  60676. ** Bind a blob value to an SQL statement variable.
  60677. */
  60678. SQLITE_API int sqlite3_bind_blob(
  60679. sqlite3_stmt *pStmt,
  60680. int i,
  60681. const void *zData,
  60682. int nData,
  60683. void (*xDel)(void*)
  60684. ){
  60685. return bindText(pStmt, i, zData, nData, xDel, 0);
  60686. }
  60687. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  60688. int rc;
  60689. Vdbe *p = (Vdbe *)pStmt;
  60690. rc = vdbeUnbind(p, i);
  60691. if( rc==SQLITE_OK ){
  60692. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  60693. sqlite3_mutex_leave(p->db->mutex);
  60694. }
  60695. return rc;
  60696. }
  60697. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  60698. return sqlite3_bind_int64(p, i, (i64)iValue);
  60699. }
  60700. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  60701. int rc;
  60702. Vdbe *p = (Vdbe *)pStmt;
  60703. rc = vdbeUnbind(p, i);
  60704. if( rc==SQLITE_OK ){
  60705. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  60706. sqlite3_mutex_leave(p->db->mutex);
  60707. }
  60708. return rc;
  60709. }
  60710. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  60711. int rc;
  60712. Vdbe *p = (Vdbe*)pStmt;
  60713. rc = vdbeUnbind(p, i);
  60714. if( rc==SQLITE_OK ){
  60715. sqlite3_mutex_leave(p->db->mutex);
  60716. }
  60717. return rc;
  60718. }
  60719. SQLITE_API int sqlite3_bind_text(
  60720. sqlite3_stmt *pStmt,
  60721. int i,
  60722. const char *zData,
  60723. int nData,
  60724. void (*xDel)(void*)
  60725. ){
  60726. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  60727. }
  60728. #ifndef SQLITE_OMIT_UTF16
  60729. SQLITE_API int sqlite3_bind_text16(
  60730. sqlite3_stmt *pStmt,
  60731. int i,
  60732. const void *zData,
  60733. int nData,
  60734. void (*xDel)(void*)
  60735. ){
  60736. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  60737. }
  60738. #endif /* SQLITE_OMIT_UTF16 */
  60739. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  60740. int rc;
  60741. switch( pValue->type ){
  60742. case SQLITE_INTEGER: {
  60743. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  60744. break;
  60745. }
  60746. case SQLITE_FLOAT: {
  60747. rc = sqlite3_bind_double(pStmt, i, pValue->r);
  60748. break;
  60749. }
  60750. case SQLITE_BLOB: {
  60751. if( pValue->flags & MEM_Zero ){
  60752. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  60753. }else{
  60754. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  60755. }
  60756. break;
  60757. }
  60758. case SQLITE_TEXT: {
  60759. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  60760. pValue->enc);
  60761. break;
  60762. }
  60763. default: {
  60764. rc = sqlite3_bind_null(pStmt, i);
  60765. break;
  60766. }
  60767. }
  60768. return rc;
  60769. }
  60770. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  60771. int rc;
  60772. Vdbe *p = (Vdbe *)pStmt;
  60773. rc = vdbeUnbind(p, i);
  60774. if( rc==SQLITE_OK ){
  60775. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  60776. sqlite3_mutex_leave(p->db->mutex);
  60777. }
  60778. return rc;
  60779. }
  60780. /*
  60781. ** Return the number of wildcards that can be potentially bound to.
  60782. ** This routine is added to support DBD::SQLite.
  60783. */
  60784. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  60785. Vdbe *p = (Vdbe*)pStmt;
  60786. return p ? p->nVar : 0;
  60787. }
  60788. /*
  60789. ** Return the name of a wildcard parameter. Return NULL if the index
  60790. ** is out of range or if the wildcard is unnamed.
  60791. **
  60792. ** The result is always UTF-8.
  60793. */
  60794. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  60795. Vdbe *p = (Vdbe*)pStmt;
  60796. if( p==0 || i<1 || i>p->nzVar ){
  60797. return 0;
  60798. }
  60799. return p->azVar[i-1];
  60800. }
  60801. /*
  60802. ** Given a wildcard parameter name, return the index of the variable
  60803. ** with that name. If there is no variable with the given name,
  60804. ** return 0.
  60805. */
  60806. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  60807. int i;
  60808. if( p==0 ){
  60809. return 0;
  60810. }
  60811. if( zName ){
  60812. for(i=0; i<p->nzVar; i++){
  60813. const char *z = p->azVar[i];
  60814. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  60815. return i+1;
  60816. }
  60817. }
  60818. }
  60819. return 0;
  60820. }
  60821. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  60822. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  60823. }
  60824. /*
  60825. ** Transfer all bindings from the first statement over to the second.
  60826. */
  60827. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  60828. Vdbe *pFrom = (Vdbe*)pFromStmt;
  60829. Vdbe *pTo = (Vdbe*)pToStmt;
  60830. int i;
  60831. assert( pTo->db==pFrom->db );
  60832. assert( pTo->nVar==pFrom->nVar );
  60833. sqlite3_mutex_enter(pTo->db->mutex);
  60834. for(i=0; i<pFrom->nVar; i++){
  60835. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  60836. }
  60837. sqlite3_mutex_leave(pTo->db->mutex);
  60838. return SQLITE_OK;
  60839. }
  60840. #ifndef SQLITE_OMIT_DEPRECATED
  60841. /*
  60842. ** Deprecated external interface. Internal/core SQLite code
  60843. ** should call sqlite3TransferBindings.
  60844. **
  60845. ** Is is misuse to call this routine with statements from different
  60846. ** database connections. But as this is a deprecated interface, we
  60847. ** will not bother to check for that condition.
  60848. **
  60849. ** If the two statements contain a different number of bindings, then
  60850. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  60851. ** SQLITE_OK is returned.
  60852. */
  60853. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  60854. Vdbe *pFrom = (Vdbe*)pFromStmt;
  60855. Vdbe *pTo = (Vdbe*)pToStmt;
  60856. if( pFrom->nVar!=pTo->nVar ){
  60857. return SQLITE_ERROR;
  60858. }
  60859. if( pTo->isPrepareV2 && pTo->expmask ){
  60860. pTo->expired = 1;
  60861. }
  60862. if( pFrom->isPrepareV2 && pFrom->expmask ){
  60863. pFrom->expired = 1;
  60864. }
  60865. return sqlite3TransferBindings(pFromStmt, pToStmt);
  60866. }
  60867. #endif
  60868. /*
  60869. ** Return the sqlite3* database handle to which the prepared statement given
  60870. ** in the argument belongs. This is the same database handle that was
  60871. ** the first argument to the sqlite3_prepare() that was used to create
  60872. ** the statement in the first place.
  60873. */
  60874. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  60875. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  60876. }
  60877. /*
  60878. ** Return true if the prepared statement is guaranteed to not modify the
  60879. ** database.
  60880. */
  60881. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  60882. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  60883. }
  60884. /*
  60885. ** Return true if the prepared statement is in need of being reset.
  60886. */
  60887. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  60888. Vdbe *v = (Vdbe*)pStmt;
  60889. return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
  60890. }
  60891. /*
  60892. ** Return a pointer to the next prepared statement after pStmt associated
  60893. ** with database connection pDb. If pStmt is NULL, return the first
  60894. ** prepared statement for the database connection. Return NULL if there
  60895. ** are no more.
  60896. */
  60897. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  60898. sqlite3_stmt *pNext;
  60899. sqlite3_mutex_enter(pDb->mutex);
  60900. if( pStmt==0 ){
  60901. pNext = (sqlite3_stmt*)pDb->pVdbe;
  60902. }else{
  60903. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  60904. }
  60905. sqlite3_mutex_leave(pDb->mutex);
  60906. return pNext;
  60907. }
  60908. /*
  60909. ** Return the value of a status counter for a prepared statement
  60910. */
  60911. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  60912. Vdbe *pVdbe = (Vdbe*)pStmt;
  60913. u32 v = pVdbe->aCounter[op];
  60914. if( resetFlag ) pVdbe->aCounter[op] = 0;
  60915. return (int)v;
  60916. }
  60917. /************** End of vdbeapi.c *********************************************/
  60918. /************** Begin file vdbetrace.c ***************************************/
  60919. /*
  60920. ** 2009 November 25
  60921. **
  60922. ** The author disclaims copyright to this source code. In place of
  60923. ** a legal notice, here is a blessing:
  60924. **
  60925. ** May you do good and not evil.
  60926. ** May you find forgiveness for yourself and forgive others.
  60927. ** May you share freely, never taking more than you give.
  60928. **
  60929. *************************************************************************
  60930. **
  60931. ** This file contains code used to insert the values of host parameters
  60932. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  60933. **
  60934. ** The Vdbe parse-tree explainer is also found here.
  60935. */
  60936. #ifndef SQLITE_OMIT_TRACE
  60937. /*
  60938. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  60939. ** bytes in this text up to but excluding the first character in
  60940. ** a host parameter. If the text contains no host parameters, return
  60941. ** the total number of bytes in the text.
  60942. */
  60943. static int findNextHostParameter(const char *zSql, int *pnToken){
  60944. int tokenType;
  60945. int nTotal = 0;
  60946. int n;
  60947. *pnToken = 0;
  60948. while( zSql[0] ){
  60949. n = sqlite3GetToken((u8*)zSql, &tokenType);
  60950. assert( n>0 && tokenType!=TK_ILLEGAL );
  60951. if( tokenType==TK_VARIABLE ){
  60952. *pnToken = n;
  60953. break;
  60954. }
  60955. nTotal += n;
  60956. zSql += n;
  60957. }
  60958. return nTotal;
  60959. }
  60960. /*
  60961. ** This function returns a pointer to a nul-terminated string in memory
  60962. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  60963. ** string contains a copy of zRawSql but with host parameters expanded to
  60964. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  60965. ** then the returned string holds a copy of zRawSql with "-- " prepended
  60966. ** to each line of text.
  60967. **
  60968. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  60969. ** then long strings and blobs are truncated to that many bytes. This
  60970. ** can be used to prevent unreasonably large trace strings when dealing
  60971. ** with large (multi-megabyte) strings and blobs.
  60972. **
  60973. ** The calling function is responsible for making sure the memory returned
  60974. ** is eventually freed.
  60975. **
  60976. ** ALGORITHM: Scan the input string looking for host parameters in any of
  60977. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  60978. ** string literals, quoted identifier names, and comments. For text forms,
  60979. ** the host parameter index is found by scanning the perpared
  60980. ** statement for the corresponding OP_Variable opcode. Once the host
  60981. ** parameter index is known, locate the value in p->aVar[]. Then render
  60982. ** the value as a literal in place of the host parameter name.
  60983. */
  60984. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  60985. Vdbe *p, /* The prepared statement being evaluated */
  60986. const char *zRawSql /* Raw text of the SQL statement */
  60987. ){
  60988. sqlite3 *db; /* The database connection */
  60989. int idx = 0; /* Index of a host parameter */
  60990. int nextIndex = 1; /* Index of next ? host parameter */
  60991. int n; /* Length of a token prefix */
  60992. int nToken; /* Length of the parameter token */
  60993. int i; /* Loop counter */
  60994. Mem *pVar; /* Value of a host parameter */
  60995. StrAccum out; /* Accumulate the output here */
  60996. char zBase[100]; /* Initial working space */
  60997. db = p->db;
  60998. sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
  60999. db->aLimit[SQLITE_LIMIT_LENGTH]);
  61000. out.db = db;
  61001. if( db->nVdbeExec>1 ){
  61002. while( *zRawSql ){
  61003. const char *zStart = zRawSql;
  61004. while( *(zRawSql++)!='\n' && *zRawSql );
  61005. sqlite3StrAccumAppend(&out, "-- ", 3);
  61006. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  61007. }
  61008. }else{
  61009. while( zRawSql[0] ){
  61010. n = findNextHostParameter(zRawSql, &nToken);
  61011. assert( n>0 );
  61012. sqlite3StrAccumAppend(&out, zRawSql, n);
  61013. zRawSql += n;
  61014. assert( zRawSql[0] || nToken==0 );
  61015. if( nToken==0 ) break;
  61016. if( zRawSql[0]=='?' ){
  61017. if( nToken>1 ){
  61018. assert( sqlite3Isdigit(zRawSql[1]) );
  61019. sqlite3GetInt32(&zRawSql[1], &idx);
  61020. }else{
  61021. idx = nextIndex;
  61022. }
  61023. }else{
  61024. assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
  61025. testcase( zRawSql[0]==':' );
  61026. testcase( zRawSql[0]=='$' );
  61027. testcase( zRawSql[0]=='@' );
  61028. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  61029. assert( idx>0 );
  61030. }
  61031. zRawSql += nToken;
  61032. nextIndex = idx + 1;
  61033. assert( idx>0 && idx<=p->nVar );
  61034. pVar = &p->aVar[idx-1];
  61035. if( pVar->flags & MEM_Null ){
  61036. sqlite3StrAccumAppend(&out, "NULL", 4);
  61037. }else if( pVar->flags & MEM_Int ){
  61038. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  61039. }else if( pVar->flags & MEM_Real ){
  61040. sqlite3XPrintf(&out, "%!.15g", pVar->r);
  61041. }else if( pVar->flags & MEM_Str ){
  61042. int nOut; /* Number of bytes of the string text to include in output */
  61043. #ifndef SQLITE_OMIT_UTF16
  61044. u8 enc = ENC(db);
  61045. Mem utf8;
  61046. if( enc!=SQLITE_UTF8 ){
  61047. memset(&utf8, 0, sizeof(utf8));
  61048. utf8.db = db;
  61049. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  61050. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  61051. pVar = &utf8;
  61052. }
  61053. #endif
  61054. nOut = pVar->n;
  61055. #ifdef SQLITE_TRACE_SIZE_LIMIT
  61056. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  61057. nOut = SQLITE_TRACE_SIZE_LIMIT;
  61058. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  61059. }
  61060. #endif
  61061. sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
  61062. #ifdef SQLITE_TRACE_SIZE_LIMIT
  61063. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  61064. #endif
  61065. #ifndef SQLITE_OMIT_UTF16
  61066. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  61067. #endif
  61068. }else if( pVar->flags & MEM_Zero ){
  61069. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  61070. }else{
  61071. int nOut; /* Number of bytes of the blob to include in output */
  61072. assert( pVar->flags & MEM_Blob );
  61073. sqlite3StrAccumAppend(&out, "x'", 2);
  61074. nOut = pVar->n;
  61075. #ifdef SQLITE_TRACE_SIZE_LIMIT
  61076. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  61077. #endif
  61078. for(i=0; i<nOut; i++){
  61079. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  61080. }
  61081. sqlite3StrAccumAppend(&out, "'", 1);
  61082. #ifdef SQLITE_TRACE_SIZE_LIMIT
  61083. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  61084. #endif
  61085. }
  61086. }
  61087. }
  61088. return sqlite3StrAccumFinish(&out);
  61089. }
  61090. #endif /* #ifndef SQLITE_OMIT_TRACE */
  61091. /*****************************************************************************
  61092. ** The following code implements the data-structure explaining logic
  61093. ** for the Vdbe.
  61094. */
  61095. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  61096. /*
  61097. ** Allocate a new Explain object
  61098. */
  61099. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
  61100. if( pVdbe ){
  61101. Explain *p;
  61102. sqlite3BeginBenignMalloc();
  61103. p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
  61104. if( p ){
  61105. p->pVdbe = pVdbe;
  61106. sqlite3_free(pVdbe->pExplain);
  61107. pVdbe->pExplain = p;
  61108. sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
  61109. SQLITE_MAX_LENGTH);
  61110. p->str.useMalloc = 2;
  61111. }else{
  61112. sqlite3EndBenignMalloc();
  61113. }
  61114. }
  61115. }
  61116. /*
  61117. ** Return true if the Explain ends with a new-line.
  61118. */
  61119. static int endsWithNL(Explain *p){
  61120. return p && p->str.zText && p->str.nChar
  61121. && p->str.zText[p->str.nChar-1]=='\n';
  61122. }
  61123. /*
  61124. ** Append text to the indentation
  61125. */
  61126. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
  61127. Explain *p;
  61128. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  61129. va_list ap;
  61130. if( p->nIndent && endsWithNL(p) ){
  61131. int n = p->nIndent;
  61132. if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
  61133. sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
  61134. }
  61135. va_start(ap, zFormat);
  61136. sqlite3VXPrintf(&p->str, 1, zFormat, ap);
  61137. va_end(ap);
  61138. }
  61139. }
  61140. /*
  61141. ** Append a '\n' if there is not already one.
  61142. */
  61143. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
  61144. Explain *p;
  61145. if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
  61146. sqlite3StrAccumAppend(&p->str, "\n", 1);
  61147. }
  61148. }
  61149. /*
  61150. ** Push a new indentation level. Subsequent lines will be indented
  61151. ** so that they begin at the current cursor position.
  61152. */
  61153. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
  61154. Explain *p;
  61155. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  61156. if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
  61157. const char *z = p->str.zText;
  61158. int i = p->str.nChar-1;
  61159. int x;
  61160. while( i>=0 && z[i]!='\n' ){ i--; }
  61161. x = (p->str.nChar - 1) - i;
  61162. if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
  61163. x = p->aIndent[p->nIndent-1];
  61164. }
  61165. p->aIndent[p->nIndent] = x;
  61166. }
  61167. p->nIndent++;
  61168. }
  61169. }
  61170. /*
  61171. ** Pop the indentation stack by one level.
  61172. */
  61173. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
  61174. if( p && p->pExplain ) p->pExplain->nIndent--;
  61175. }
  61176. /*
  61177. ** Free the indentation structure
  61178. */
  61179. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
  61180. if( pVdbe && pVdbe->pExplain ){
  61181. sqlite3_free(pVdbe->zExplain);
  61182. sqlite3ExplainNL(pVdbe);
  61183. pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
  61184. sqlite3_free(pVdbe->pExplain);
  61185. pVdbe->pExplain = 0;
  61186. sqlite3EndBenignMalloc();
  61187. }
  61188. }
  61189. /*
  61190. ** Return the explanation of a virtual machine.
  61191. */
  61192. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
  61193. return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
  61194. }
  61195. #endif /* defined(SQLITE_DEBUG) */
  61196. /************** End of vdbetrace.c *******************************************/
  61197. /************** Begin file vdbe.c ********************************************/
  61198. /*
  61199. ** 2001 September 15
  61200. **
  61201. ** The author disclaims copyright to this source code. In place of
  61202. ** a legal notice, here is a blessing:
  61203. **
  61204. ** May you do good and not evil.
  61205. ** May you find forgiveness for yourself and forgive others.
  61206. ** May you share freely, never taking more than you give.
  61207. **
  61208. *************************************************************************
  61209. ** The code in this file implements execution method of the
  61210. ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  61211. ** handles housekeeping details such as creating and deleting
  61212. ** VDBE instances. This file is solely interested in executing
  61213. ** the VDBE program.
  61214. **
  61215. ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
  61216. ** to a VDBE.
  61217. **
  61218. ** The SQL parser generates a program which is then executed by
  61219. ** the VDBE to do the work of the SQL statement. VDBE programs are
  61220. ** similar in form to assembly language. The program consists of
  61221. ** a linear sequence of operations. Each operation has an opcode
  61222. ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
  61223. ** is a null-terminated string. Operand P5 is an unsigned character.
  61224. ** Few opcodes use all 5 operands.
  61225. **
  61226. ** Computation results are stored on a set of registers numbered beginning
  61227. ** with 1 and going up to Vdbe.nMem. Each register can store
  61228. ** either an integer, a null-terminated string, a floating point
  61229. ** number, or the SQL "NULL" value. An implicit conversion from one
  61230. ** type to the other occurs as necessary.
  61231. **
  61232. ** Most of the code in this file is taken up by the sqlite3VdbeExec()
  61233. ** function which does the work of interpreting a VDBE program.
  61234. ** But other routines are also provided to help in building up
  61235. ** a program instruction by instruction.
  61236. **
  61237. ** Various scripts scan this source file in order to generate HTML
  61238. ** documentation, headers files, or other derived files. The formatting
  61239. ** of the code in this file is, therefore, important. See other comments
  61240. ** in this file for details. If in doubt, do not deviate from existing
  61241. ** commenting and indentation practices when changing or adding code.
  61242. */
  61243. /*
  61244. ** Invoke this macro on memory cells just prior to changing the
  61245. ** value of the cell. This macro verifies that shallow copies are
  61246. ** not misused.
  61247. */
  61248. #ifdef SQLITE_DEBUG
  61249. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  61250. #else
  61251. # define memAboutToChange(P,M)
  61252. #endif
  61253. /*
  61254. ** The following global variable is incremented every time a cursor
  61255. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  61256. ** procedures use this information to make sure that indices are
  61257. ** working correctly. This variable has no function other than to
  61258. ** help verify the correct operation of the library.
  61259. */
  61260. #ifdef SQLITE_TEST
  61261. SQLITE_API int sqlite3_search_count = 0;
  61262. #endif
  61263. /*
  61264. ** When this global variable is positive, it gets decremented once before
  61265. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  61266. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  61267. **
  61268. ** This facility is used for testing purposes only. It does not function
  61269. ** in an ordinary build.
  61270. */
  61271. #ifdef SQLITE_TEST
  61272. SQLITE_API int sqlite3_interrupt_count = 0;
  61273. #endif
  61274. /*
  61275. ** The next global variable is incremented each type the OP_Sort opcode
  61276. ** is executed. The test procedures use this information to make sure that
  61277. ** sorting is occurring or not occurring at appropriate times. This variable
  61278. ** has no function other than to help verify the correct operation of the
  61279. ** library.
  61280. */
  61281. #ifdef SQLITE_TEST
  61282. SQLITE_API int sqlite3_sort_count = 0;
  61283. #endif
  61284. /*
  61285. ** The next global variable records the size of the largest MEM_Blob
  61286. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  61287. ** use this information to make sure that the zero-blob functionality
  61288. ** is working correctly. This variable has no function other than to
  61289. ** help verify the correct operation of the library.
  61290. */
  61291. #ifdef SQLITE_TEST
  61292. SQLITE_API int sqlite3_max_blobsize = 0;
  61293. static void updateMaxBlobsize(Mem *p){
  61294. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  61295. sqlite3_max_blobsize = p->n;
  61296. }
  61297. }
  61298. #endif
  61299. /*
  61300. ** The next global variable is incremented each type the OP_Found opcode
  61301. ** is executed. This is used to test whether or not the foreign key
  61302. ** operation implemented using OP_FkIsZero is working. This variable
  61303. ** has no function other than to help verify the correct operation of the
  61304. ** library.
  61305. */
  61306. #ifdef SQLITE_TEST
  61307. SQLITE_API int sqlite3_found_count = 0;
  61308. #endif
  61309. /*
  61310. ** Test a register to see if it exceeds the current maximum blob size.
  61311. ** If it does, record the new maximum blob size.
  61312. */
  61313. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  61314. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  61315. #else
  61316. # define UPDATE_MAX_BLOBSIZE(P)
  61317. #endif
  61318. /*
  61319. ** Convert the given register into a string if it isn't one
  61320. ** already. Return non-zero if a malloc() fails.
  61321. */
  61322. #define Stringify(P, enc) \
  61323. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
  61324. { goto no_mem; }
  61325. /*
  61326. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  61327. ** a pointer to a dynamically allocated string where some other entity
  61328. ** is responsible for deallocating that string. Because the register
  61329. ** does not control the string, it might be deleted without the register
  61330. ** knowing it.
  61331. **
  61332. ** This routine converts an ephemeral string into a dynamically allocated
  61333. ** string that the register itself controls. In other words, it
  61334. ** converts an MEM_Ephem string into an MEM_Dyn string.
  61335. */
  61336. #define Deephemeralize(P) \
  61337. if( ((P)->flags&MEM_Ephem)!=0 \
  61338. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  61339. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  61340. # define isSorter(x) ((x)->pSorter!=0)
  61341. /*
  61342. ** Argument pMem points at a register that will be passed to a
  61343. ** user-defined function or returned to the user as the result of a query.
  61344. ** This routine sets the pMem->type variable used by the sqlite3_value_*()
  61345. ** routines.
  61346. */
  61347. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
  61348. int flags = pMem->flags;
  61349. if( flags & MEM_Null ){
  61350. pMem->type = SQLITE_NULL;
  61351. }
  61352. else if( flags & MEM_Int ){
  61353. pMem->type = SQLITE_INTEGER;
  61354. }
  61355. else if( flags & MEM_Real ){
  61356. pMem->type = SQLITE_FLOAT;
  61357. }
  61358. else if( flags & MEM_Str ){
  61359. pMem->type = SQLITE_TEXT;
  61360. }else{
  61361. pMem->type = SQLITE_BLOB;
  61362. }
  61363. }
  61364. /*
  61365. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  61366. ** if we run out of memory.
  61367. */
  61368. static VdbeCursor *allocateCursor(
  61369. Vdbe *p, /* The virtual machine */
  61370. int iCur, /* Index of the new VdbeCursor */
  61371. int nField, /* Number of fields in the table or index */
  61372. int iDb, /* Database the cursor belongs to, or -1 */
  61373. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  61374. ){
  61375. /* Find the memory cell that will be used to store the blob of memory
  61376. ** required for this VdbeCursor structure. It is convenient to use a
  61377. ** vdbe memory cell to manage the memory allocation required for a
  61378. ** VdbeCursor structure for the following reasons:
  61379. **
  61380. ** * Sometimes cursor numbers are used for a couple of different
  61381. ** purposes in a vdbe program. The different uses might require
  61382. ** different sized allocations. Memory cells provide growable
  61383. ** allocations.
  61384. **
  61385. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  61386. ** be freed lazily via the sqlite3_release_memory() API. This
  61387. ** minimizes the number of malloc calls made by the system.
  61388. **
  61389. ** Memory cells for cursors are allocated at the top of the address
  61390. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  61391. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  61392. */
  61393. Mem *pMem = &p->aMem[p->nMem-iCur];
  61394. int nByte;
  61395. VdbeCursor *pCx = 0;
  61396. nByte =
  61397. ROUND8(sizeof(VdbeCursor)) +
  61398. (isBtreeCursor?sqlite3BtreeCursorSize():0) +
  61399. 2*nField*sizeof(u32);
  61400. assert( iCur<p->nCursor );
  61401. if( p->apCsr[iCur] ){
  61402. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  61403. p->apCsr[iCur] = 0;
  61404. }
  61405. if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  61406. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  61407. memset(pCx, 0, sizeof(VdbeCursor));
  61408. pCx->iDb = iDb;
  61409. pCx->nField = nField;
  61410. if( nField ){
  61411. pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
  61412. }
  61413. if( isBtreeCursor ){
  61414. pCx->pCursor = (BtCursor*)
  61415. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
  61416. sqlite3BtreeCursorZero(pCx->pCursor);
  61417. }
  61418. }
  61419. return pCx;
  61420. }
  61421. /*
  61422. ** Try to convert a value into a numeric representation if we can
  61423. ** do so without loss of information. In other words, if the string
  61424. ** looks like a number, convert it into a number. If it does not
  61425. ** look like a number, leave it alone.
  61426. */
  61427. static void applyNumericAffinity(Mem *pRec){
  61428. if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
  61429. double rValue;
  61430. i64 iValue;
  61431. u8 enc = pRec->enc;
  61432. if( (pRec->flags&MEM_Str)==0 ) return;
  61433. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  61434. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  61435. pRec->u.i = iValue;
  61436. pRec->flags |= MEM_Int;
  61437. }else{
  61438. pRec->r = rValue;
  61439. pRec->flags |= MEM_Real;
  61440. }
  61441. }
  61442. }
  61443. /*
  61444. ** Processing is determine by the affinity parameter:
  61445. **
  61446. ** SQLITE_AFF_INTEGER:
  61447. ** SQLITE_AFF_REAL:
  61448. ** SQLITE_AFF_NUMERIC:
  61449. ** Try to convert pRec to an integer representation or a
  61450. ** floating-point representation if an integer representation
  61451. ** is not possible. Note that the integer representation is
  61452. ** always preferred, even if the affinity is REAL, because
  61453. ** an integer representation is more space efficient on disk.
  61454. **
  61455. ** SQLITE_AFF_TEXT:
  61456. ** Convert pRec to a text representation.
  61457. **
  61458. ** SQLITE_AFF_NONE:
  61459. ** No-op. pRec is unchanged.
  61460. */
  61461. static void applyAffinity(
  61462. Mem *pRec, /* The value to apply affinity to */
  61463. char affinity, /* The affinity to be applied */
  61464. u8 enc /* Use this text encoding */
  61465. ){
  61466. if( affinity==SQLITE_AFF_TEXT ){
  61467. /* Only attempt the conversion to TEXT if there is an integer or real
  61468. ** representation (blob and NULL do not get converted) but no string
  61469. ** representation.
  61470. */
  61471. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  61472. sqlite3VdbeMemStringify(pRec, enc);
  61473. }
  61474. pRec->flags &= ~(MEM_Real|MEM_Int);
  61475. }else if( affinity!=SQLITE_AFF_NONE ){
  61476. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  61477. || affinity==SQLITE_AFF_NUMERIC );
  61478. applyNumericAffinity(pRec);
  61479. if( pRec->flags & MEM_Real ){
  61480. sqlite3VdbeIntegerAffinity(pRec);
  61481. }
  61482. }
  61483. }
  61484. /*
  61485. ** Try to convert the type of a function argument or a result column
  61486. ** into a numeric representation. Use either INTEGER or REAL whichever
  61487. ** is appropriate. But only do the conversion if it is possible without
  61488. ** loss of information and return the revised type of the argument.
  61489. */
  61490. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  61491. Mem *pMem = (Mem*)pVal;
  61492. if( pMem->type==SQLITE_TEXT ){
  61493. applyNumericAffinity(pMem);
  61494. sqlite3VdbeMemStoreType(pMem);
  61495. }
  61496. return pMem->type;
  61497. }
  61498. /*
  61499. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  61500. ** not the internal Mem* type.
  61501. */
  61502. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  61503. sqlite3_value *pVal,
  61504. u8 affinity,
  61505. u8 enc
  61506. ){
  61507. applyAffinity((Mem *)pVal, affinity, enc);
  61508. }
  61509. #ifdef SQLITE_DEBUG
  61510. /*
  61511. ** Write a nice string representation of the contents of cell pMem
  61512. ** into buffer zBuf, length nBuf.
  61513. */
  61514. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  61515. char *zCsr = zBuf;
  61516. int f = pMem->flags;
  61517. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  61518. if( f&MEM_Blob ){
  61519. int i;
  61520. char c;
  61521. if( f & MEM_Dyn ){
  61522. c = 'z';
  61523. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  61524. }else if( f & MEM_Static ){
  61525. c = 't';
  61526. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  61527. }else if( f & MEM_Ephem ){
  61528. c = 'e';
  61529. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  61530. }else{
  61531. c = 's';
  61532. }
  61533. sqlite3_snprintf(100, zCsr, "%c", c);
  61534. zCsr += sqlite3Strlen30(zCsr);
  61535. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  61536. zCsr += sqlite3Strlen30(zCsr);
  61537. for(i=0; i<16 && i<pMem->n; i++){
  61538. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  61539. zCsr += sqlite3Strlen30(zCsr);
  61540. }
  61541. for(i=0; i<16 && i<pMem->n; i++){
  61542. char z = pMem->z[i];
  61543. if( z<32 || z>126 ) *zCsr++ = '.';
  61544. else *zCsr++ = z;
  61545. }
  61546. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  61547. zCsr += sqlite3Strlen30(zCsr);
  61548. if( f & MEM_Zero ){
  61549. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  61550. zCsr += sqlite3Strlen30(zCsr);
  61551. }
  61552. *zCsr = '\0';
  61553. }else if( f & MEM_Str ){
  61554. int j, k;
  61555. zBuf[0] = ' ';
  61556. if( f & MEM_Dyn ){
  61557. zBuf[1] = 'z';
  61558. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  61559. }else if( f & MEM_Static ){
  61560. zBuf[1] = 't';
  61561. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  61562. }else if( f & MEM_Ephem ){
  61563. zBuf[1] = 'e';
  61564. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  61565. }else{
  61566. zBuf[1] = 's';
  61567. }
  61568. k = 2;
  61569. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  61570. k += sqlite3Strlen30(&zBuf[k]);
  61571. zBuf[k++] = '[';
  61572. for(j=0; j<15 && j<pMem->n; j++){
  61573. u8 c = pMem->z[j];
  61574. if( c>=0x20 && c<0x7f ){
  61575. zBuf[k++] = c;
  61576. }else{
  61577. zBuf[k++] = '.';
  61578. }
  61579. }
  61580. zBuf[k++] = ']';
  61581. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  61582. k += sqlite3Strlen30(&zBuf[k]);
  61583. zBuf[k++] = 0;
  61584. }
  61585. }
  61586. #endif
  61587. #ifdef SQLITE_DEBUG
  61588. /*
  61589. ** Print the value of a register for tracing purposes:
  61590. */
  61591. static void memTracePrint(FILE *out, Mem *p){
  61592. if( p->flags & MEM_Invalid ){
  61593. fprintf(out, " undefined");
  61594. }else if( p->flags & MEM_Null ){
  61595. fprintf(out, " NULL");
  61596. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  61597. fprintf(out, " si:%lld", p->u.i);
  61598. }else if( p->flags & MEM_Int ){
  61599. fprintf(out, " i:%lld", p->u.i);
  61600. #ifndef SQLITE_OMIT_FLOATING_POINT
  61601. }else if( p->flags & MEM_Real ){
  61602. fprintf(out, " r:%g", p->r);
  61603. #endif
  61604. }else if( p->flags & MEM_RowSet ){
  61605. fprintf(out, " (rowset)");
  61606. }else{
  61607. char zBuf[200];
  61608. sqlite3VdbeMemPrettyPrint(p, zBuf);
  61609. fprintf(out, " ");
  61610. fprintf(out, "%s", zBuf);
  61611. }
  61612. }
  61613. static void registerTrace(FILE *out, int iReg, Mem *p){
  61614. fprintf(out, "REG[%d] = ", iReg);
  61615. memTracePrint(out, p);
  61616. fprintf(out, "\n");
  61617. }
  61618. #endif
  61619. #ifdef SQLITE_DEBUG
  61620. # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
  61621. #else
  61622. # define REGISTER_TRACE(R,M)
  61623. #endif
  61624. #ifdef VDBE_PROFILE
  61625. /*
  61626. ** hwtime.h contains inline assembler code for implementing
  61627. ** high-performance timing routines.
  61628. */
  61629. /************** Include hwtime.h in the middle of vdbe.c *********************/
  61630. /************** Begin file hwtime.h ******************************************/
  61631. /*
  61632. ** 2008 May 27
  61633. **
  61634. ** The author disclaims copyright to this source code. In place of
  61635. ** a legal notice, here is a blessing:
  61636. **
  61637. ** May you do good and not evil.
  61638. ** May you find forgiveness for yourself and forgive others.
  61639. ** May you share freely, never taking more than you give.
  61640. **
  61641. ******************************************************************************
  61642. **
  61643. ** This file contains inline asm code for retrieving "high-performance"
  61644. ** counters for x86 class CPUs.
  61645. */
  61646. #ifndef _HWTIME_H_
  61647. #define _HWTIME_H_
  61648. /*
  61649. ** The following routine only works on pentium-class (or newer) processors.
  61650. ** It uses the RDTSC opcode to read the cycle count value out of the
  61651. ** processor and returns that value. This can be used for high-res
  61652. ** profiling.
  61653. */
  61654. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  61655. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  61656. #if defined(__GNUC__)
  61657. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  61658. unsigned int lo, hi;
  61659. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  61660. return (sqlite_uint64)hi << 32 | lo;
  61661. }
  61662. #elif defined(_MSC_VER)
  61663. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  61664. __asm {
  61665. rdtsc
  61666. ret ; return value at EDX:EAX
  61667. }
  61668. }
  61669. #endif
  61670. #elif (defined(__GNUC__) && defined(__x86_64__))
  61671. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  61672. unsigned long val;
  61673. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  61674. return val;
  61675. }
  61676. #elif (defined(__GNUC__) && defined(__ppc__))
  61677. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  61678. unsigned long long retval;
  61679. unsigned long junk;
  61680. __asm__ __volatile__ ("\n\
  61681. 1: mftbu %1\n\
  61682. mftb %L0\n\
  61683. mftbu %0\n\
  61684. cmpw %0,%1\n\
  61685. bne 1b"
  61686. : "=r" (retval), "=r" (junk));
  61687. return retval;
  61688. }
  61689. #else
  61690. #error Need implementation of sqlite3Hwtime() for your platform.
  61691. /*
  61692. ** To compile without implementing sqlite3Hwtime() for your platform,
  61693. ** you can remove the above #error and use the following
  61694. ** stub function. You will lose timing support for many
  61695. ** of the debugging and testing utilities, but it should at
  61696. ** least compile and run.
  61697. */
  61698. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  61699. #endif
  61700. #endif /* !defined(_HWTIME_H_) */
  61701. /************** End of hwtime.h **********************************************/
  61702. /************** Continuing where we left off in vdbe.c ***********************/
  61703. #endif
  61704. /*
  61705. ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  61706. ** sqlite3_interrupt() routine has been called. If it has been, then
  61707. ** processing of the VDBE program is interrupted.
  61708. **
  61709. ** This macro added to every instruction that does a jump in order to
  61710. ** implement a loop. This test used to be on every single instruction,
  61711. ** but that meant we more testing than we needed. By only testing the
  61712. ** flag on jump instructions, we get a (small) speed improvement.
  61713. */
  61714. #define CHECK_FOR_INTERRUPT \
  61715. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  61716. #ifndef NDEBUG
  61717. /*
  61718. ** This function is only called from within an assert() expression. It
  61719. ** checks that the sqlite3.nTransaction variable is correctly set to
  61720. ** the number of non-transaction savepoints currently in the
  61721. ** linked list starting at sqlite3.pSavepoint.
  61722. **
  61723. ** Usage:
  61724. **
  61725. ** assert( checkSavepointCount(db) );
  61726. */
  61727. static int checkSavepointCount(sqlite3 *db){
  61728. int n = 0;
  61729. Savepoint *p;
  61730. for(p=db->pSavepoint; p; p=p->pNext) n++;
  61731. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  61732. return 1;
  61733. }
  61734. #endif
  61735. /*
  61736. ** Execute as much of a VDBE program as we can then return.
  61737. **
  61738. ** sqlite3VdbeMakeReady() must be called before this routine in order to
  61739. ** close the program with a final OP_Halt and to set up the callbacks
  61740. ** and the error message pointer.
  61741. **
  61742. ** Whenever a row or result data is available, this routine will either
  61743. ** invoke the result callback (if there is one) or return with
  61744. ** SQLITE_ROW.
  61745. **
  61746. ** If an attempt is made to open a locked database, then this routine
  61747. ** will either invoke the busy callback (if there is one) or it will
  61748. ** return SQLITE_BUSY.
  61749. **
  61750. ** If an error occurs, an error message is written to memory obtained
  61751. ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
  61752. ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  61753. **
  61754. ** If the callback ever returns non-zero, then the program exits
  61755. ** immediately. There will be no error message but the p->rc field is
  61756. ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  61757. **
  61758. ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  61759. ** routine to return SQLITE_ERROR.
  61760. **
  61761. ** Other fatal errors return SQLITE_ERROR.
  61762. **
  61763. ** After this routine has finished, sqlite3VdbeFinalize() should be
  61764. ** used to clean up the mess that was left behind.
  61765. */
  61766. SQLITE_PRIVATE int sqlite3VdbeExec(
  61767. Vdbe *p /* The VDBE */
  61768. ){
  61769. int pc=0; /* The program counter */
  61770. Op *aOp = p->aOp; /* Copy of p->aOp */
  61771. Op *pOp; /* Current operation */
  61772. int rc = SQLITE_OK; /* Value to return */
  61773. sqlite3 *db = p->db; /* The database */
  61774. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  61775. u8 encoding = ENC(db); /* The database encoding */
  61776. int iCompare = 0; /* Result of last OP_Compare operation */
  61777. unsigned nVmStep = 0; /* Number of virtual machine steps */
  61778. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  61779. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  61780. #endif
  61781. Mem *aMem = p->aMem; /* Copy of p->aMem */
  61782. Mem *pIn1 = 0; /* 1st input operand */
  61783. Mem *pIn2 = 0; /* 2nd input operand */
  61784. Mem *pIn3 = 0; /* 3rd input operand */
  61785. Mem *pOut = 0; /* Output operand */
  61786. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  61787. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  61788. #ifdef VDBE_PROFILE
  61789. u64 start; /* CPU clock count at start of opcode */
  61790. int origPc; /* Program counter at start of opcode */
  61791. #endif
  61792. /********************************************************************
  61793. ** Automatically generated code
  61794. **
  61795. ** The following union is automatically generated by the
  61796. ** vdbe-compress.tcl script. The purpose of this union is to
  61797. ** reduce the amount of stack space required by this function.
  61798. ** See comments in the vdbe-compress.tcl script for details.
  61799. */
  61800. union vdbeExecUnion {
  61801. struct OP_Yield_stack_vars {
  61802. int pcDest;
  61803. } aa;
  61804. struct OP_Null_stack_vars {
  61805. int cnt;
  61806. u16 nullFlag;
  61807. } ab;
  61808. struct OP_Variable_stack_vars {
  61809. Mem *pVar; /* Value being transferred */
  61810. } ac;
  61811. struct OP_Move_stack_vars {
  61812. char *zMalloc; /* Holding variable for allocated memory */
  61813. int n; /* Number of registers left to copy */
  61814. int p1; /* Register to copy from */
  61815. int p2; /* Register to copy to */
  61816. } ad;
  61817. struct OP_Copy_stack_vars {
  61818. int n;
  61819. } ae;
  61820. struct OP_ResultRow_stack_vars {
  61821. Mem *pMem;
  61822. int i;
  61823. } af;
  61824. struct OP_Concat_stack_vars {
  61825. i64 nByte;
  61826. } ag;
  61827. struct OP_Remainder_stack_vars {
  61828. char bIntint; /* Started out as two integer operands */
  61829. int flags; /* Combined MEM_* flags from both inputs */
  61830. i64 iA; /* Integer value of left operand */
  61831. i64 iB; /* Integer value of right operand */
  61832. double rA; /* Real value of left operand */
  61833. double rB; /* Real value of right operand */
  61834. } ah;
  61835. struct OP_Function_stack_vars {
  61836. int i;
  61837. Mem *pArg;
  61838. sqlite3_context ctx;
  61839. sqlite3_value **apVal;
  61840. int n;
  61841. } ai;
  61842. struct OP_ShiftRight_stack_vars {
  61843. i64 iA;
  61844. u64 uA;
  61845. i64 iB;
  61846. u8 op;
  61847. } aj;
  61848. struct OP_Ge_stack_vars {
  61849. int res; /* Result of the comparison of pIn1 against pIn3 */
  61850. char affinity; /* Affinity to use for comparison */
  61851. u16 flags1; /* Copy of initial value of pIn1->flags */
  61852. u16 flags3; /* Copy of initial value of pIn3->flags */
  61853. } ak;
  61854. struct OP_Compare_stack_vars {
  61855. int n;
  61856. int i;
  61857. int p1;
  61858. int p2;
  61859. const KeyInfo *pKeyInfo;
  61860. int idx;
  61861. CollSeq *pColl; /* Collating sequence to use on this term */
  61862. int bRev; /* True for DESCENDING sort order */
  61863. } al;
  61864. struct OP_Or_stack_vars {
  61865. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  61866. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  61867. } am;
  61868. struct OP_IfNot_stack_vars {
  61869. int c;
  61870. } an;
  61871. struct OP_Column_stack_vars {
  61872. u32 payloadSize; /* Number of bytes in the record */
  61873. i64 payloadSize64; /* Number of bytes in the record */
  61874. int p1; /* P1 value of the opcode */
  61875. int p2; /* column number to retrieve */
  61876. VdbeCursor *pC; /* The VDBE cursor */
  61877. char *zRec; /* Pointer to complete record-data */
  61878. BtCursor *pCrsr; /* The BTree cursor */
  61879. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  61880. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  61881. int nField; /* number of fields in the record */
  61882. int len; /* The length of the serialized data for the column */
  61883. int i; /* Loop counter */
  61884. char *zData; /* Part of the record being decoded */
  61885. Mem *pDest; /* Where to write the extracted value */
  61886. Mem sMem; /* For storing the record being decoded */
  61887. u8 *zIdx; /* Index into header */
  61888. u8 *zEndHdr; /* Pointer to first byte after the header */
  61889. u32 offset; /* Offset into the data */
  61890. u32 szField; /* Number of bytes in the content of a field */
  61891. int szHdr; /* Size of the header size field at start of record */
  61892. int avail; /* Number of bytes of available data */
  61893. u32 t; /* A type code from the record header */
  61894. Mem *pReg; /* PseudoTable input register */
  61895. } ao;
  61896. struct OP_Affinity_stack_vars {
  61897. const char *zAffinity; /* The affinity to be applied */
  61898. char cAff; /* A single character of affinity */
  61899. } ap;
  61900. struct OP_MakeRecord_stack_vars {
  61901. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  61902. Mem *pRec; /* The new record */
  61903. u64 nData; /* Number of bytes of data space */
  61904. int nHdr; /* Number of bytes of header space */
  61905. i64 nByte; /* Data space required for this record */
  61906. int nZero; /* Number of zero bytes at the end of the record */
  61907. int nVarint; /* Number of bytes in a varint */
  61908. u32 serial_type; /* Type field */
  61909. Mem *pData0; /* First field to be combined into the record */
  61910. Mem *pLast; /* Last field of the record */
  61911. int nField; /* Number of fields in the record */
  61912. char *zAffinity; /* The affinity string for the record */
  61913. int file_format; /* File format to use for encoding */
  61914. int i; /* Space used in zNewRecord[] */
  61915. int len; /* Length of a field */
  61916. } aq;
  61917. struct OP_Count_stack_vars {
  61918. i64 nEntry;
  61919. BtCursor *pCrsr;
  61920. } ar;
  61921. struct OP_Savepoint_stack_vars {
  61922. int p1; /* Value of P1 operand */
  61923. char *zName; /* Name of savepoint */
  61924. int nName;
  61925. Savepoint *pNew;
  61926. Savepoint *pSavepoint;
  61927. Savepoint *pTmp;
  61928. int iSavepoint;
  61929. int ii;
  61930. } as;
  61931. struct OP_AutoCommit_stack_vars {
  61932. int desiredAutoCommit;
  61933. int iRollback;
  61934. int turnOnAC;
  61935. } at;
  61936. struct OP_Transaction_stack_vars {
  61937. Btree *pBt;
  61938. } au;
  61939. struct OP_ReadCookie_stack_vars {
  61940. int iMeta;
  61941. int iDb;
  61942. int iCookie;
  61943. } av;
  61944. struct OP_SetCookie_stack_vars {
  61945. Db *pDb;
  61946. } aw;
  61947. struct OP_VerifyCookie_stack_vars {
  61948. int iMeta;
  61949. int iGen;
  61950. Btree *pBt;
  61951. } ax;
  61952. struct OP_OpenWrite_stack_vars {
  61953. int nField;
  61954. KeyInfo *pKeyInfo;
  61955. int p2;
  61956. int iDb;
  61957. int wrFlag;
  61958. Btree *pX;
  61959. VdbeCursor *pCur;
  61960. Db *pDb;
  61961. } ay;
  61962. struct OP_OpenEphemeral_stack_vars {
  61963. VdbeCursor *pCx;
  61964. } az;
  61965. struct OP_SorterOpen_stack_vars {
  61966. VdbeCursor *pCx;
  61967. } ba;
  61968. struct OP_OpenPseudo_stack_vars {
  61969. VdbeCursor *pCx;
  61970. } bb;
  61971. struct OP_SeekGt_stack_vars {
  61972. int res;
  61973. int oc;
  61974. VdbeCursor *pC;
  61975. UnpackedRecord r;
  61976. int nField;
  61977. i64 iKey; /* The rowid we are to seek to */
  61978. } bc;
  61979. struct OP_Seek_stack_vars {
  61980. VdbeCursor *pC;
  61981. } bd;
  61982. struct OP_Found_stack_vars {
  61983. int alreadyExists;
  61984. VdbeCursor *pC;
  61985. int res;
  61986. char *pFree;
  61987. UnpackedRecord *pIdxKey;
  61988. UnpackedRecord r;
  61989. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  61990. } be;
  61991. struct OP_IsUnique_stack_vars {
  61992. u16 ii;
  61993. VdbeCursor *pCx;
  61994. BtCursor *pCrsr;
  61995. u16 nField;
  61996. Mem *aMx;
  61997. UnpackedRecord r; /* B-Tree index search key */
  61998. i64 R; /* Rowid stored in register P3 */
  61999. } bf;
  62000. struct OP_NotExists_stack_vars {
  62001. VdbeCursor *pC;
  62002. BtCursor *pCrsr;
  62003. int res;
  62004. u64 iKey;
  62005. } bg;
  62006. struct OP_NewRowid_stack_vars {
  62007. i64 v; /* The new rowid */
  62008. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  62009. int res; /* Result of an sqlite3BtreeLast() */
  62010. int cnt; /* Counter to limit the number of searches */
  62011. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  62012. VdbeFrame *pFrame; /* Root frame of VDBE */
  62013. } bh;
  62014. struct OP_InsertInt_stack_vars {
  62015. Mem *pData; /* MEM cell holding data for the record to be inserted */
  62016. Mem *pKey; /* MEM cell holding key for the record */
  62017. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  62018. VdbeCursor *pC; /* Cursor to table into which insert is written */
  62019. int nZero; /* Number of zero-bytes to append */
  62020. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  62021. const char *zDb; /* database name - used by the update hook */
  62022. const char *zTbl; /* Table name - used by the opdate hook */
  62023. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  62024. } bi;
  62025. struct OP_Delete_stack_vars {
  62026. i64 iKey;
  62027. VdbeCursor *pC;
  62028. } bj;
  62029. struct OP_SorterCompare_stack_vars {
  62030. VdbeCursor *pC;
  62031. int res;
  62032. } bk;
  62033. struct OP_SorterData_stack_vars {
  62034. VdbeCursor *pC;
  62035. } bl;
  62036. struct OP_RowData_stack_vars {
  62037. VdbeCursor *pC;
  62038. BtCursor *pCrsr;
  62039. u32 n;
  62040. i64 n64;
  62041. } bm;
  62042. struct OP_Rowid_stack_vars {
  62043. VdbeCursor *pC;
  62044. i64 v;
  62045. sqlite3_vtab *pVtab;
  62046. const sqlite3_module *pModule;
  62047. } bn;
  62048. struct OP_NullRow_stack_vars {
  62049. VdbeCursor *pC;
  62050. } bo;
  62051. struct OP_Last_stack_vars {
  62052. VdbeCursor *pC;
  62053. BtCursor *pCrsr;
  62054. int res;
  62055. } bp;
  62056. struct OP_Rewind_stack_vars {
  62057. VdbeCursor *pC;
  62058. BtCursor *pCrsr;
  62059. int res;
  62060. } bq;
  62061. struct OP_Next_stack_vars {
  62062. VdbeCursor *pC;
  62063. int res;
  62064. } br;
  62065. struct OP_IdxInsert_stack_vars {
  62066. VdbeCursor *pC;
  62067. BtCursor *pCrsr;
  62068. int nKey;
  62069. const char *zKey;
  62070. } bs;
  62071. struct OP_IdxDelete_stack_vars {
  62072. VdbeCursor *pC;
  62073. BtCursor *pCrsr;
  62074. int res;
  62075. UnpackedRecord r;
  62076. } bt;
  62077. struct OP_IdxRowid_stack_vars {
  62078. BtCursor *pCrsr;
  62079. VdbeCursor *pC;
  62080. i64 rowid;
  62081. } bu;
  62082. struct OP_IdxGE_stack_vars {
  62083. VdbeCursor *pC;
  62084. int res;
  62085. UnpackedRecord r;
  62086. } bv;
  62087. struct OP_Destroy_stack_vars {
  62088. int iMoved;
  62089. int iCnt;
  62090. Vdbe *pVdbe;
  62091. int iDb;
  62092. } bw;
  62093. struct OP_Clear_stack_vars {
  62094. int nChange;
  62095. } bx;
  62096. struct OP_CreateTable_stack_vars {
  62097. int pgno;
  62098. int flags;
  62099. Db *pDb;
  62100. } by;
  62101. struct OP_ParseSchema_stack_vars {
  62102. int iDb;
  62103. const char *zMaster;
  62104. char *zSql;
  62105. InitData initData;
  62106. } bz;
  62107. struct OP_IntegrityCk_stack_vars {
  62108. int nRoot; /* Number of tables to check. (Number of root pages.) */
  62109. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  62110. int j; /* Loop counter */
  62111. int nErr; /* Number of errors reported */
  62112. char *z; /* Text of the error report */
  62113. Mem *pnErr; /* Register keeping track of errors remaining */
  62114. } ca;
  62115. struct OP_RowSetRead_stack_vars {
  62116. i64 val;
  62117. } cb;
  62118. struct OP_RowSetTest_stack_vars {
  62119. int iSet;
  62120. int exists;
  62121. } cc;
  62122. struct OP_Program_stack_vars {
  62123. int nMem; /* Number of memory registers for sub-program */
  62124. int nByte; /* Bytes of runtime space required for sub-program */
  62125. Mem *pRt; /* Register to allocate runtime space */
  62126. Mem *pMem; /* Used to iterate through memory cells */
  62127. Mem *pEnd; /* Last memory cell in new array */
  62128. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  62129. SubProgram *pProgram; /* Sub-program to execute */
  62130. void *t; /* Token identifying trigger */
  62131. } cd;
  62132. struct OP_Param_stack_vars {
  62133. VdbeFrame *pFrame;
  62134. Mem *pIn;
  62135. } ce;
  62136. struct OP_MemMax_stack_vars {
  62137. Mem *pIn1;
  62138. VdbeFrame *pFrame;
  62139. } cf;
  62140. struct OP_AggStep_stack_vars {
  62141. int n;
  62142. int i;
  62143. Mem *pMem;
  62144. Mem *pRec;
  62145. sqlite3_context ctx;
  62146. sqlite3_value **apVal;
  62147. } cg;
  62148. struct OP_AggFinal_stack_vars {
  62149. Mem *pMem;
  62150. } ch;
  62151. struct OP_Checkpoint_stack_vars {
  62152. int i; /* Loop counter */
  62153. int aRes[3]; /* Results */
  62154. Mem *pMem; /* Write results here */
  62155. } ci;
  62156. struct OP_JournalMode_stack_vars {
  62157. Btree *pBt; /* Btree to change journal mode of */
  62158. Pager *pPager; /* Pager associated with pBt */
  62159. int eNew; /* New journal mode */
  62160. int eOld; /* The old journal mode */
  62161. #ifndef SQLITE_OMIT_WAL
  62162. const char *zFilename; /* Name of database file for pPager */
  62163. #endif
  62164. } cj;
  62165. struct OP_IncrVacuum_stack_vars {
  62166. Btree *pBt;
  62167. } ck;
  62168. struct OP_VBegin_stack_vars {
  62169. VTable *pVTab;
  62170. } cl;
  62171. struct OP_VOpen_stack_vars {
  62172. VdbeCursor *pCur;
  62173. sqlite3_vtab_cursor *pVtabCursor;
  62174. sqlite3_vtab *pVtab;
  62175. sqlite3_module *pModule;
  62176. } cm;
  62177. struct OP_VFilter_stack_vars {
  62178. int nArg;
  62179. int iQuery;
  62180. const sqlite3_module *pModule;
  62181. Mem *pQuery;
  62182. Mem *pArgc;
  62183. sqlite3_vtab_cursor *pVtabCursor;
  62184. sqlite3_vtab *pVtab;
  62185. VdbeCursor *pCur;
  62186. int res;
  62187. int i;
  62188. Mem **apArg;
  62189. } cn;
  62190. struct OP_VColumn_stack_vars {
  62191. sqlite3_vtab *pVtab;
  62192. const sqlite3_module *pModule;
  62193. Mem *pDest;
  62194. sqlite3_context sContext;
  62195. } co;
  62196. struct OP_VNext_stack_vars {
  62197. sqlite3_vtab *pVtab;
  62198. const sqlite3_module *pModule;
  62199. int res;
  62200. VdbeCursor *pCur;
  62201. } cp;
  62202. struct OP_VRename_stack_vars {
  62203. sqlite3_vtab *pVtab;
  62204. Mem *pName;
  62205. } cq;
  62206. struct OP_VUpdate_stack_vars {
  62207. sqlite3_vtab *pVtab;
  62208. sqlite3_module *pModule;
  62209. int nArg;
  62210. int i;
  62211. sqlite_int64 rowid;
  62212. Mem **apArg;
  62213. Mem *pX;
  62214. } cr;
  62215. struct OP_Trace_stack_vars {
  62216. char *zTrace;
  62217. char *z;
  62218. } cs;
  62219. } u;
  62220. /* End automatically generated code
  62221. ********************************************************************/
  62222. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  62223. sqlite3VdbeEnter(p);
  62224. if( p->rc==SQLITE_NOMEM ){
  62225. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  62226. ** sqlite3_column_text16() failed. */
  62227. goto no_mem;
  62228. }
  62229. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  62230. assert( p->bIsReader || p->readOnly!=0 );
  62231. p->rc = SQLITE_OK;
  62232. p->iCurrentTime = 0;
  62233. assert( p->explain==0 );
  62234. p->pResultSet = 0;
  62235. db->busyHandler.nBusy = 0;
  62236. CHECK_FOR_INTERRUPT;
  62237. sqlite3VdbeIOTraceSql(p);
  62238. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  62239. if( db->xProgress ){
  62240. assert( 0 < db->nProgressOps );
  62241. nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  62242. if( nProgressLimit==0 ){
  62243. nProgressLimit = db->nProgressOps;
  62244. }else{
  62245. nProgressLimit %= (unsigned)db->nProgressOps;
  62246. }
  62247. }
  62248. #endif
  62249. #ifdef SQLITE_DEBUG
  62250. sqlite3BeginBenignMalloc();
  62251. if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
  62252. int i;
  62253. printf("VDBE Program Listing:\n");
  62254. sqlite3VdbePrintSql(p);
  62255. for(i=0; i<p->nOp; i++){
  62256. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  62257. }
  62258. }
  62259. sqlite3EndBenignMalloc();
  62260. #endif
  62261. for(pc=p->pc; rc==SQLITE_OK; pc++){
  62262. assert( pc>=0 && pc<p->nOp );
  62263. if( db->mallocFailed ) goto no_mem;
  62264. #ifdef VDBE_PROFILE
  62265. origPc = pc;
  62266. start = sqlite3Hwtime();
  62267. #endif
  62268. nVmStep++;
  62269. pOp = &aOp[pc];
  62270. /* Only allow tracing if SQLITE_DEBUG is defined.
  62271. */
  62272. #ifdef SQLITE_DEBUG
  62273. if( p->trace ){
  62274. if( pc==0 ){
  62275. printf("VDBE Execution Trace:\n");
  62276. sqlite3VdbePrintSql(p);
  62277. }
  62278. sqlite3VdbePrintOp(p->trace, pc, pOp);
  62279. }
  62280. #endif
  62281. /* Check to see if we need to simulate an interrupt. This only happens
  62282. ** if we have a special test build.
  62283. */
  62284. #ifdef SQLITE_TEST
  62285. if( sqlite3_interrupt_count>0 ){
  62286. sqlite3_interrupt_count--;
  62287. if( sqlite3_interrupt_count==0 ){
  62288. sqlite3_interrupt(db);
  62289. }
  62290. }
  62291. #endif
  62292. /* On any opcode with the "out2-prerelease" tag, free any
  62293. ** external allocations out of mem[p2] and set mem[p2] to be
  62294. ** an undefined integer. Opcodes will either fill in the integer
  62295. ** value or convert mem[p2] to a different type.
  62296. */
  62297. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  62298. if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
  62299. assert( pOp->p2>0 );
  62300. assert( pOp->p2<=(p->nMem-p->nCursor) );
  62301. pOut = &aMem[pOp->p2];
  62302. memAboutToChange(p, pOut);
  62303. VdbeMemRelease(pOut);
  62304. pOut->flags = MEM_Int;
  62305. }
  62306. /* Sanity checking on other operands */
  62307. #ifdef SQLITE_DEBUG
  62308. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  62309. assert( pOp->p1>0 );
  62310. assert( pOp->p1<=(p->nMem-p->nCursor) );
  62311. assert( memIsValid(&aMem[pOp->p1]) );
  62312. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  62313. }
  62314. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  62315. assert( pOp->p2>0 );
  62316. assert( pOp->p2<=(p->nMem-p->nCursor) );
  62317. assert( memIsValid(&aMem[pOp->p2]) );
  62318. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  62319. }
  62320. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  62321. assert( pOp->p3>0 );
  62322. assert( pOp->p3<=(p->nMem-p->nCursor) );
  62323. assert( memIsValid(&aMem[pOp->p3]) );
  62324. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  62325. }
  62326. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  62327. assert( pOp->p2>0 );
  62328. assert( pOp->p2<=(p->nMem-p->nCursor) );
  62329. memAboutToChange(p, &aMem[pOp->p2]);
  62330. }
  62331. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  62332. assert( pOp->p3>0 );
  62333. assert( pOp->p3<=(p->nMem-p->nCursor) );
  62334. memAboutToChange(p, &aMem[pOp->p3]);
  62335. }
  62336. #endif
  62337. switch( pOp->opcode ){
  62338. /*****************************************************************************
  62339. ** What follows is a massive switch statement where each case implements a
  62340. ** separate instruction in the virtual machine. If we follow the usual
  62341. ** indentation conventions, each case should be indented by 6 spaces. But
  62342. ** that is a lot of wasted space on the left margin. So the code within
  62343. ** the switch statement will break with convention and be flush-left. Another
  62344. ** big comment (similar to this one) will mark the point in the code where
  62345. ** we transition back to normal indentation.
  62346. **
  62347. ** The formatting of each case is important. The makefile for SQLite
  62348. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  62349. ** file looking for lines that begin with "case OP_". The opcodes.h files
  62350. ** will be filled with #defines that give unique integer values to each
  62351. ** opcode and the opcodes.c file is filled with an array of strings where
  62352. ** each string is the symbolic name for the corresponding opcode. If the
  62353. ** case statement is followed by a comment of the form "/# same as ... #/"
  62354. ** that comment is used to determine the particular value of the opcode.
  62355. **
  62356. ** Other keywords in the comment that follows each case are used to
  62357. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  62358. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  62359. ** the mkopcodeh.awk script for additional information.
  62360. **
  62361. ** Documentation about VDBE opcodes is generated by scanning this file
  62362. ** for lines of that contain "Opcode:". That line and all subsequent
  62363. ** comment lines are used in the generation of the opcode.html documentation
  62364. ** file.
  62365. **
  62366. ** SUMMARY:
  62367. **
  62368. ** Formatting is important to scripts that scan this file.
  62369. ** Do not deviate from the formatting style currently in use.
  62370. **
  62371. *****************************************************************************/
  62372. /* Opcode: Goto * P2 * * *
  62373. **
  62374. ** An unconditional jump to address P2.
  62375. ** The next instruction executed will be
  62376. ** the one at index P2 from the beginning of
  62377. ** the program.
  62378. */
  62379. case OP_Goto: { /* jump */
  62380. pc = pOp->p2 - 1;
  62381. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  62382. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  62383. ** completion. Check to see if sqlite3_interrupt() has been called
  62384. ** or if the progress callback needs to be invoked.
  62385. **
  62386. ** This code uses unstructured "goto" statements and does not look clean.
  62387. ** But that is not due to sloppy coding habits. The code is written this
  62388. ** way for performance, to avoid having to run the interrupt and progress
  62389. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  62390. ** faster according to "valgrind --tool=cachegrind" */
  62391. check_for_interrupt:
  62392. CHECK_FOR_INTERRUPT;
  62393. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  62394. /* Call the progress callback if it is configured and the required number
  62395. ** of VDBE ops have been executed (either since this invocation of
  62396. ** sqlite3VdbeExec() or since last time the progress callback was called).
  62397. ** If the progress callback returns non-zero, exit the virtual machine with
  62398. ** a return code SQLITE_ABORT.
  62399. */
  62400. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  62401. int prc;
  62402. prc = db->xProgress(db->pProgressArg);
  62403. if( prc!=0 ){
  62404. rc = SQLITE_INTERRUPT;
  62405. goto vdbe_error_halt;
  62406. }
  62407. if( db->xProgress!=0 ){
  62408. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  62409. }
  62410. }
  62411. #endif
  62412. break;
  62413. }
  62414. /* Opcode: Gosub P1 P2 * * *
  62415. **
  62416. ** Write the current address onto register P1
  62417. ** and then jump to address P2.
  62418. */
  62419. case OP_Gosub: { /* jump */
  62420. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  62421. pIn1 = &aMem[pOp->p1];
  62422. assert( (pIn1->flags & MEM_Dyn)==0 );
  62423. memAboutToChange(p, pIn1);
  62424. pIn1->flags = MEM_Int;
  62425. pIn1->u.i = pc;
  62426. REGISTER_TRACE(pOp->p1, pIn1);
  62427. pc = pOp->p2 - 1;
  62428. break;
  62429. }
  62430. /* Opcode: Return P1 * * * *
  62431. **
  62432. ** Jump to the next instruction after the address in register P1.
  62433. */
  62434. case OP_Return: { /* in1 */
  62435. pIn1 = &aMem[pOp->p1];
  62436. assert( pIn1->flags & MEM_Int );
  62437. pc = (int)pIn1->u.i;
  62438. break;
  62439. }
  62440. /* Opcode: Yield P1 * * * *
  62441. **
  62442. ** Swap the program counter with the value in register P1.
  62443. */
  62444. case OP_Yield: { /* in1 */
  62445. #if 0 /* local variables moved into u.aa */
  62446. int pcDest;
  62447. #endif /* local variables moved into u.aa */
  62448. pIn1 = &aMem[pOp->p1];
  62449. assert( (pIn1->flags & MEM_Dyn)==0 );
  62450. pIn1->flags = MEM_Int;
  62451. u.aa.pcDest = (int)pIn1->u.i;
  62452. pIn1->u.i = pc;
  62453. REGISTER_TRACE(pOp->p1, pIn1);
  62454. pc = u.aa.pcDest;
  62455. break;
  62456. }
  62457. /* Opcode: HaltIfNull P1 P2 P3 P4 *
  62458. **
  62459. ** Check the value in register P3. If it is NULL then Halt using
  62460. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  62461. ** value in register P3 is not NULL, then this routine is a no-op.
  62462. */
  62463. case OP_HaltIfNull: { /* in3 */
  62464. pIn3 = &aMem[pOp->p3];
  62465. if( (pIn3->flags & MEM_Null)==0 ) break;
  62466. /* Fall through into OP_Halt */
  62467. }
  62468. /* Opcode: Halt P1 P2 * P4 *
  62469. **
  62470. ** Exit immediately. All open cursors, etc are closed
  62471. ** automatically.
  62472. **
  62473. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  62474. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  62475. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  62476. ** whether or not to rollback the current transaction. Do not rollback
  62477. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  62478. ** then back out all changes that have occurred during this execution of the
  62479. ** VDBE, but do not rollback the transaction.
  62480. **
  62481. ** If P4 is not null then it is an error message string.
  62482. **
  62483. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  62484. ** every program. So a jump past the last instruction of the program
  62485. ** is the same as executing Halt.
  62486. */
  62487. case OP_Halt: {
  62488. if( pOp->p1==SQLITE_OK && p->pFrame ){
  62489. /* Halt the sub-program. Return control to the parent frame. */
  62490. VdbeFrame *pFrame = p->pFrame;
  62491. p->pFrame = pFrame->pParent;
  62492. p->nFrame--;
  62493. sqlite3VdbeSetChanges(db, p->nChange);
  62494. pc = sqlite3VdbeFrameRestore(pFrame);
  62495. lastRowid = db->lastRowid;
  62496. if( pOp->p2==OE_Ignore ){
  62497. /* Instruction pc is the OP_Program that invoked the sub-program
  62498. ** currently being halted. If the p2 instruction of this OP_Halt
  62499. ** instruction is set to OE_Ignore, then the sub-program is throwing
  62500. ** an IGNORE exception. In this case jump to the address specified
  62501. ** as the p2 of the calling OP_Program. */
  62502. pc = p->aOp[pc].p2-1;
  62503. }
  62504. aOp = p->aOp;
  62505. aMem = p->aMem;
  62506. break;
  62507. }
  62508. p->rc = pOp->p1;
  62509. p->errorAction = (u8)pOp->p2;
  62510. p->pc = pc;
  62511. if( pOp->p4.z ){
  62512. assert( p->rc!=SQLITE_OK );
  62513. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  62514. testcase( sqlite3GlobalConfig.xLog!=0 );
  62515. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
  62516. }else if( p->rc ){
  62517. testcase( sqlite3GlobalConfig.xLog!=0 );
  62518. sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
  62519. }
  62520. rc = sqlite3VdbeHalt(p);
  62521. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  62522. if( rc==SQLITE_BUSY ){
  62523. p->rc = rc = SQLITE_BUSY;
  62524. }else{
  62525. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  62526. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  62527. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  62528. }
  62529. goto vdbe_return;
  62530. }
  62531. /* Opcode: Integer P1 P2 * * *
  62532. **
  62533. ** The 32-bit integer value P1 is written into register P2.
  62534. */
  62535. case OP_Integer: { /* out2-prerelease */
  62536. pOut->u.i = pOp->p1;
  62537. break;
  62538. }
  62539. /* Opcode: Int64 * P2 * P4 *
  62540. **
  62541. ** P4 is a pointer to a 64-bit integer value.
  62542. ** Write that value into register P2.
  62543. */
  62544. case OP_Int64: { /* out2-prerelease */
  62545. assert( pOp->p4.pI64!=0 );
  62546. pOut->u.i = *pOp->p4.pI64;
  62547. break;
  62548. }
  62549. #ifndef SQLITE_OMIT_FLOATING_POINT
  62550. /* Opcode: Real * P2 * P4 *
  62551. **
  62552. ** P4 is a pointer to a 64-bit floating point value.
  62553. ** Write that value into register P2.
  62554. */
  62555. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  62556. pOut->flags = MEM_Real;
  62557. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  62558. pOut->r = *pOp->p4.pReal;
  62559. break;
  62560. }
  62561. #endif
  62562. /* Opcode: String8 * P2 * P4 *
  62563. **
  62564. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  62565. ** into an OP_String before it is executed for the first time.
  62566. */
  62567. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  62568. assert( pOp->p4.z!=0 );
  62569. pOp->opcode = OP_String;
  62570. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  62571. #ifndef SQLITE_OMIT_UTF16
  62572. if( encoding!=SQLITE_UTF8 ){
  62573. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  62574. if( rc==SQLITE_TOOBIG ) goto too_big;
  62575. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  62576. assert( pOut->zMalloc==pOut->z );
  62577. assert( pOut->flags & MEM_Dyn );
  62578. pOut->zMalloc = 0;
  62579. pOut->flags |= MEM_Static;
  62580. pOut->flags &= ~MEM_Dyn;
  62581. if( pOp->p4type==P4_DYNAMIC ){
  62582. sqlite3DbFree(db, pOp->p4.z);
  62583. }
  62584. pOp->p4type = P4_DYNAMIC;
  62585. pOp->p4.z = pOut->z;
  62586. pOp->p1 = pOut->n;
  62587. }
  62588. #endif
  62589. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  62590. goto too_big;
  62591. }
  62592. /* Fall through to the next case, OP_String */
  62593. }
  62594. /* Opcode: String P1 P2 * P4 *
  62595. **
  62596. ** The string value P4 of length P1 (bytes) is stored in register P2.
  62597. */
  62598. case OP_String: { /* out2-prerelease */
  62599. assert( pOp->p4.z!=0 );
  62600. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  62601. pOut->z = pOp->p4.z;
  62602. pOut->n = pOp->p1;
  62603. pOut->enc = encoding;
  62604. UPDATE_MAX_BLOBSIZE(pOut);
  62605. break;
  62606. }
  62607. /* Opcode: Null P1 P2 P3 * *
  62608. **
  62609. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  62610. ** NULL into register P3 and every register in between P2 and P3. If P3
  62611. ** is less than P2 (typically P3 is zero) then only register P2 is
  62612. ** set to NULL.
  62613. **
  62614. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  62615. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  62616. ** OP_Ne or OP_Eq.
  62617. */
  62618. case OP_Null: { /* out2-prerelease */
  62619. #if 0 /* local variables moved into u.ab */
  62620. int cnt;
  62621. u16 nullFlag;
  62622. #endif /* local variables moved into u.ab */
  62623. u.ab.cnt = pOp->p3-pOp->p2;
  62624. assert( pOp->p3<=(p->nMem-p->nCursor) );
  62625. pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  62626. while( u.ab.cnt>0 ){
  62627. pOut++;
  62628. memAboutToChange(p, pOut);
  62629. VdbeMemRelease(pOut);
  62630. pOut->flags = u.ab.nullFlag;
  62631. u.ab.cnt--;
  62632. }
  62633. break;
  62634. }
  62635. /* Opcode: Blob P1 P2 * P4
  62636. **
  62637. ** P4 points to a blob of data P1 bytes long. Store this
  62638. ** blob in register P2.
  62639. */
  62640. case OP_Blob: { /* out2-prerelease */
  62641. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  62642. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  62643. pOut->enc = encoding;
  62644. UPDATE_MAX_BLOBSIZE(pOut);
  62645. break;
  62646. }
  62647. /* Opcode: Variable P1 P2 * P4 *
  62648. **
  62649. ** Transfer the values of bound parameter P1 into register P2
  62650. **
  62651. ** If the parameter is named, then its name appears in P4 and P3==1.
  62652. ** The P4 value is used by sqlite3_bind_parameter_name().
  62653. */
  62654. case OP_Variable: { /* out2-prerelease */
  62655. #if 0 /* local variables moved into u.ac */
  62656. Mem *pVar; /* Value being transferred */
  62657. #endif /* local variables moved into u.ac */
  62658. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  62659. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  62660. u.ac.pVar = &p->aVar[pOp->p1 - 1];
  62661. if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
  62662. goto too_big;
  62663. }
  62664. sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
  62665. UPDATE_MAX_BLOBSIZE(pOut);
  62666. break;
  62667. }
  62668. /* Opcode: Move P1 P2 P3 * *
  62669. **
  62670. ** Move the values in register P1..P1+P3 over into
  62671. ** registers P2..P2+P3. Registers P1..P1+P3 are
  62672. ** left holding a NULL. It is an error for register ranges
  62673. ** P1..P1+P3 and P2..P2+P3 to overlap.
  62674. */
  62675. case OP_Move: {
  62676. #if 0 /* local variables moved into u.ad */
  62677. char *zMalloc; /* Holding variable for allocated memory */
  62678. int n; /* Number of registers left to copy */
  62679. int p1; /* Register to copy from */
  62680. int p2; /* Register to copy to */
  62681. #endif /* local variables moved into u.ad */
  62682. u.ad.n = pOp->p3 + 1;
  62683. u.ad.p1 = pOp->p1;
  62684. u.ad.p2 = pOp->p2;
  62685. assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
  62686. assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
  62687. pIn1 = &aMem[u.ad.p1];
  62688. pOut = &aMem[u.ad.p2];
  62689. while( u.ad.n-- ){
  62690. assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  62691. assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  62692. assert( memIsValid(pIn1) );
  62693. memAboutToChange(p, pOut);
  62694. u.ad.zMalloc = pOut->zMalloc;
  62695. pOut->zMalloc = 0;
  62696. sqlite3VdbeMemMove(pOut, pIn1);
  62697. #ifdef SQLITE_DEBUG
  62698. if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
  62699. pOut->pScopyFrom += u.ad.p1 - pOp->p2;
  62700. }
  62701. #endif
  62702. pIn1->zMalloc = u.ad.zMalloc;
  62703. REGISTER_TRACE(u.ad.p2++, pOut);
  62704. pIn1++;
  62705. pOut++;
  62706. }
  62707. break;
  62708. }
  62709. /* Opcode: Copy P1 P2 P3 * *
  62710. **
  62711. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  62712. **
  62713. ** This instruction makes a deep copy of the value. A duplicate
  62714. ** is made of any string or blob constant. See also OP_SCopy.
  62715. */
  62716. case OP_Copy: {
  62717. #if 0 /* local variables moved into u.ae */
  62718. int n;
  62719. #endif /* local variables moved into u.ae */
  62720. u.ae.n = pOp->p3;
  62721. pIn1 = &aMem[pOp->p1];
  62722. pOut = &aMem[pOp->p2];
  62723. assert( pOut!=pIn1 );
  62724. while( 1 ){
  62725. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  62726. Deephemeralize(pOut);
  62727. #ifdef SQLITE_DEBUG
  62728. pOut->pScopyFrom = 0;
  62729. #endif
  62730. REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
  62731. if( (u.ae.n--)==0 ) break;
  62732. pOut++;
  62733. pIn1++;
  62734. }
  62735. break;
  62736. }
  62737. /* Opcode: SCopy P1 P2 * * *
  62738. **
  62739. ** Make a shallow copy of register P1 into register P2.
  62740. **
  62741. ** This instruction makes a shallow copy of the value. If the value
  62742. ** is a string or blob, then the copy is only a pointer to the
  62743. ** original and hence if the original changes so will the copy.
  62744. ** Worse, if the original is deallocated, the copy becomes invalid.
  62745. ** Thus the program must guarantee that the original will not change
  62746. ** during the lifetime of the copy. Use OP_Copy to make a complete
  62747. ** copy.
  62748. */
  62749. case OP_SCopy: { /* in1, out2 */
  62750. pIn1 = &aMem[pOp->p1];
  62751. pOut = &aMem[pOp->p2];
  62752. assert( pOut!=pIn1 );
  62753. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  62754. #ifdef SQLITE_DEBUG
  62755. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  62756. #endif
  62757. REGISTER_TRACE(pOp->p2, pOut);
  62758. break;
  62759. }
  62760. /* Opcode: ResultRow P1 P2 * * *
  62761. **
  62762. ** The registers P1 through P1+P2-1 contain a single row of
  62763. ** results. This opcode causes the sqlite3_step() call to terminate
  62764. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  62765. ** structure to provide access to the top P1 values as the result
  62766. ** row.
  62767. */
  62768. case OP_ResultRow: {
  62769. #if 0 /* local variables moved into u.af */
  62770. Mem *pMem;
  62771. int i;
  62772. #endif /* local variables moved into u.af */
  62773. assert( p->nResColumn==pOp->p2 );
  62774. assert( pOp->p1>0 );
  62775. assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
  62776. /* If this statement has violated immediate foreign key constraints, do
  62777. ** not return the number of rows modified. And do not RELEASE the statement
  62778. ** transaction. It needs to be rolled back. */
  62779. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  62780. assert( db->flags&SQLITE_CountRows );
  62781. assert( p->usesStmtJournal );
  62782. break;
  62783. }
  62784. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  62785. ** DML statements invoke this opcode to return the number of rows
  62786. ** modified to the user. This is the only way that a VM that
  62787. ** opens a statement transaction may invoke this opcode.
  62788. **
  62789. ** In case this is such a statement, close any statement transaction
  62790. ** opened by this VM before returning control to the user. This is to
  62791. ** ensure that statement-transactions are always nested, not overlapping.
  62792. ** If the open statement-transaction is not closed here, then the user
  62793. ** may step another VM that opens its own statement transaction. This
  62794. ** may lead to overlapping statement transactions.
  62795. **
  62796. ** The statement transaction is never a top-level transaction. Hence
  62797. ** the RELEASE call below can never fail.
  62798. */
  62799. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  62800. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  62801. if( NEVER(rc!=SQLITE_OK) ){
  62802. break;
  62803. }
  62804. /* Invalidate all ephemeral cursor row caches */
  62805. p->cacheCtr = (p->cacheCtr + 2)|1;
  62806. /* Make sure the results of the current row are \000 terminated
  62807. ** and have an assigned type. The results are de-ephemeralized as
  62808. ** a side effect.
  62809. */
  62810. u.af.pMem = p->pResultSet = &aMem[pOp->p1];
  62811. for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
  62812. assert( memIsValid(&u.af.pMem[u.af.i]) );
  62813. Deephemeralize(&u.af.pMem[u.af.i]);
  62814. assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
  62815. || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
  62816. sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
  62817. sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
  62818. REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
  62819. }
  62820. if( db->mallocFailed ) goto no_mem;
  62821. /* Return SQLITE_ROW
  62822. */
  62823. p->pc = pc + 1;
  62824. rc = SQLITE_ROW;
  62825. goto vdbe_return;
  62826. }
  62827. /* Opcode: Concat P1 P2 P3 * *
  62828. **
  62829. ** Add the text in register P1 onto the end of the text in
  62830. ** register P2 and store the result in register P3.
  62831. ** If either the P1 or P2 text are NULL then store NULL in P3.
  62832. **
  62833. ** P3 = P2 || P1
  62834. **
  62835. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  62836. ** if P3 is the same register as P2, the implementation is able
  62837. ** to avoid a memcpy().
  62838. */
  62839. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  62840. #if 0 /* local variables moved into u.ag */
  62841. i64 nByte;
  62842. #endif /* local variables moved into u.ag */
  62843. pIn1 = &aMem[pOp->p1];
  62844. pIn2 = &aMem[pOp->p2];
  62845. pOut = &aMem[pOp->p3];
  62846. assert( pIn1!=pOut );
  62847. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  62848. sqlite3VdbeMemSetNull(pOut);
  62849. break;
  62850. }
  62851. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  62852. Stringify(pIn1, encoding);
  62853. Stringify(pIn2, encoding);
  62854. u.ag.nByte = pIn1->n + pIn2->n;
  62855. if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  62856. goto too_big;
  62857. }
  62858. MemSetTypeFlag(pOut, MEM_Str);
  62859. if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
  62860. goto no_mem;
  62861. }
  62862. if( pOut!=pIn2 ){
  62863. memcpy(pOut->z, pIn2->z, pIn2->n);
  62864. }
  62865. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  62866. pOut->z[u.ag.nByte] = 0;
  62867. pOut->z[u.ag.nByte+1] = 0;
  62868. pOut->flags |= MEM_Term;
  62869. pOut->n = (int)u.ag.nByte;
  62870. pOut->enc = encoding;
  62871. UPDATE_MAX_BLOBSIZE(pOut);
  62872. break;
  62873. }
  62874. /* Opcode: Add P1 P2 P3 * *
  62875. **
  62876. ** Add the value in register P1 to the value in register P2
  62877. ** and store the result in register P3.
  62878. ** If either input is NULL, the result is NULL.
  62879. */
  62880. /* Opcode: Multiply P1 P2 P3 * *
  62881. **
  62882. **
  62883. ** Multiply the value in register P1 by the value in register P2
  62884. ** and store the result in register P3.
  62885. ** If either input is NULL, the result is NULL.
  62886. */
  62887. /* Opcode: Subtract P1 P2 P3 * *
  62888. **
  62889. ** Subtract the value in register P1 from the value in register P2
  62890. ** and store the result in register P3.
  62891. ** If either input is NULL, the result is NULL.
  62892. */
  62893. /* Opcode: Divide P1 P2 P3 * *
  62894. **
  62895. ** Divide the value in register P1 by the value in register P2
  62896. ** and store the result in register P3 (P3=P2/P1). If the value in
  62897. ** register P1 is zero, then the result is NULL. If either input is
  62898. ** NULL, the result is NULL.
  62899. */
  62900. /* Opcode: Remainder P1 P2 P3 * *
  62901. **
  62902. ** Compute the remainder after integer division of the value in
  62903. ** register P1 by the value in register P2 and store the result in P3.
  62904. ** If the value in register P2 is zero the result is NULL.
  62905. ** If either operand is NULL, the result is NULL.
  62906. */
  62907. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  62908. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  62909. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  62910. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  62911. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  62912. #if 0 /* local variables moved into u.ah */
  62913. char bIntint; /* Started out as two integer operands */
  62914. int flags; /* Combined MEM_* flags from both inputs */
  62915. i64 iA; /* Integer value of left operand */
  62916. i64 iB; /* Integer value of right operand */
  62917. double rA; /* Real value of left operand */
  62918. double rB; /* Real value of right operand */
  62919. #endif /* local variables moved into u.ah */
  62920. pIn1 = &aMem[pOp->p1];
  62921. applyNumericAffinity(pIn1);
  62922. pIn2 = &aMem[pOp->p2];
  62923. applyNumericAffinity(pIn2);
  62924. pOut = &aMem[pOp->p3];
  62925. u.ah.flags = pIn1->flags | pIn2->flags;
  62926. if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  62927. if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
  62928. u.ah.iA = pIn1->u.i;
  62929. u.ah.iB = pIn2->u.i;
  62930. u.ah.bIntint = 1;
  62931. switch( pOp->opcode ){
  62932. case OP_Add: if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  62933. case OP_Subtract: if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  62934. case OP_Multiply: if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  62935. case OP_Divide: {
  62936. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  62937. if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
  62938. u.ah.iB /= u.ah.iA;
  62939. break;
  62940. }
  62941. default: {
  62942. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  62943. if( u.ah.iA==-1 ) u.ah.iA = 1;
  62944. u.ah.iB %= u.ah.iA;
  62945. break;
  62946. }
  62947. }
  62948. pOut->u.i = u.ah.iB;
  62949. MemSetTypeFlag(pOut, MEM_Int);
  62950. }else{
  62951. u.ah.bIntint = 0;
  62952. fp_math:
  62953. u.ah.rA = sqlite3VdbeRealValue(pIn1);
  62954. u.ah.rB = sqlite3VdbeRealValue(pIn2);
  62955. switch( pOp->opcode ){
  62956. case OP_Add: u.ah.rB += u.ah.rA; break;
  62957. case OP_Subtract: u.ah.rB -= u.ah.rA; break;
  62958. case OP_Multiply: u.ah.rB *= u.ah.rA; break;
  62959. case OP_Divide: {
  62960. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  62961. if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
  62962. u.ah.rB /= u.ah.rA;
  62963. break;
  62964. }
  62965. default: {
  62966. u.ah.iA = (i64)u.ah.rA;
  62967. u.ah.iB = (i64)u.ah.rB;
  62968. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  62969. if( u.ah.iA==-1 ) u.ah.iA = 1;
  62970. u.ah.rB = (double)(u.ah.iB % u.ah.iA);
  62971. break;
  62972. }
  62973. }
  62974. #ifdef SQLITE_OMIT_FLOATING_POINT
  62975. pOut->u.i = u.ah.rB;
  62976. MemSetTypeFlag(pOut, MEM_Int);
  62977. #else
  62978. if( sqlite3IsNaN(u.ah.rB) ){
  62979. goto arithmetic_result_is_null;
  62980. }
  62981. pOut->r = u.ah.rB;
  62982. MemSetTypeFlag(pOut, MEM_Real);
  62983. if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
  62984. sqlite3VdbeIntegerAffinity(pOut);
  62985. }
  62986. #endif
  62987. }
  62988. break;
  62989. arithmetic_result_is_null:
  62990. sqlite3VdbeMemSetNull(pOut);
  62991. break;
  62992. }
  62993. /* Opcode: CollSeq P1 * * P4
  62994. **
  62995. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  62996. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  62997. ** be returned. This is used by the built-in min(), max() and nullif()
  62998. ** functions.
  62999. **
  63000. ** If P1 is not zero, then it is a register that a subsequent min() or
  63001. ** max() aggregate will set to 1 if the current row is not the minimum or
  63002. ** maximum. The P1 register is initialized to 0 by this instruction.
  63003. **
  63004. ** The interface used by the implementation of the aforementioned functions
  63005. ** to retrieve the collation sequence set by this opcode is not available
  63006. ** publicly, only to user functions defined in func.c.
  63007. */
  63008. case OP_CollSeq: {
  63009. assert( pOp->p4type==P4_COLLSEQ );
  63010. if( pOp->p1 ){
  63011. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  63012. }
  63013. break;
  63014. }
  63015. /* Opcode: Function P1 P2 P3 P4 P5
  63016. **
  63017. ** Invoke a user function (P4 is a pointer to a Function structure that
  63018. ** defines the function) with P5 arguments taken from register P2 and
  63019. ** successors. The result of the function is stored in register P3.
  63020. ** Register P3 must not be one of the function inputs.
  63021. **
  63022. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  63023. ** function was determined to be constant at compile time. If the first
  63024. ** argument was constant then bit 0 of P1 is set. This is used to determine
  63025. ** whether meta data associated with a user function argument using the
  63026. ** sqlite3_set_auxdata() API may be safely retained until the next
  63027. ** invocation of this opcode.
  63028. **
  63029. ** See also: AggStep and AggFinal
  63030. */
  63031. case OP_Function: {
  63032. #if 0 /* local variables moved into u.ai */
  63033. int i;
  63034. Mem *pArg;
  63035. sqlite3_context ctx;
  63036. sqlite3_value **apVal;
  63037. int n;
  63038. #endif /* local variables moved into u.ai */
  63039. u.ai.n = pOp->p5;
  63040. u.ai.apVal = p->apArg;
  63041. assert( u.ai.apVal || u.ai.n==0 );
  63042. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  63043. pOut = &aMem[pOp->p3];
  63044. memAboutToChange(p, pOut);
  63045. assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=(p->nMem-p->nCursor)+1) );
  63046. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
  63047. u.ai.pArg = &aMem[pOp->p2];
  63048. for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
  63049. assert( memIsValid(u.ai.pArg) );
  63050. u.ai.apVal[u.ai.i] = u.ai.pArg;
  63051. Deephemeralize(u.ai.pArg);
  63052. sqlite3VdbeMemStoreType(u.ai.pArg);
  63053. REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
  63054. }
  63055. assert( pOp->p4type==P4_FUNCDEF );
  63056. u.ai.ctx.pFunc = pOp->p4.pFunc;
  63057. u.ai.ctx.s.flags = MEM_Null;
  63058. u.ai.ctx.s.db = db;
  63059. u.ai.ctx.s.xDel = 0;
  63060. u.ai.ctx.s.zMalloc = 0;
  63061. u.ai.ctx.iOp = pc;
  63062. u.ai.ctx.pVdbe = p;
  63063. /* The output cell may already have a buffer allocated. Move
  63064. ** the pointer to u.ai.ctx.s so in case the user-function can use
  63065. ** the already allocated buffer instead of allocating a new one.
  63066. */
  63067. sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
  63068. MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
  63069. u.ai.ctx.fErrorOrAux = 0;
  63070. if( u.ai.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  63071. assert( pOp>aOp );
  63072. assert( pOp[-1].p4type==P4_COLLSEQ );
  63073. assert( pOp[-1].opcode==OP_CollSeq );
  63074. u.ai.ctx.pColl = pOp[-1].p4.pColl;
  63075. }
  63076. db->lastRowid = lastRowid;
  63077. (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
  63078. lastRowid = db->lastRowid;
  63079. if( db->mallocFailed ){
  63080. /* Even though a malloc() has failed, the implementation of the
  63081. ** user function may have called an sqlite3_result_XXX() function
  63082. ** to return a value. The following call releases any resources
  63083. ** associated with such a value.
  63084. */
  63085. sqlite3VdbeMemRelease(&u.ai.ctx.s);
  63086. goto no_mem;
  63087. }
  63088. /* If the function returned an error, throw an exception */
  63089. if( u.ai.ctx.fErrorOrAux ){
  63090. if( u.ai.ctx.isError ){
  63091. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
  63092. rc = u.ai.ctx.isError;
  63093. }
  63094. sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
  63095. }
  63096. /* Copy the result of the function into register P3 */
  63097. sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
  63098. sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
  63099. if( sqlite3VdbeMemTooBig(pOut) ){
  63100. goto too_big;
  63101. }
  63102. #if 0
  63103. /* The app-defined function has done something that as caused this
  63104. ** statement to expire. (Perhaps the function called sqlite3_exec()
  63105. ** with a CREATE TABLE statement.)
  63106. */
  63107. if( p->expired ) rc = SQLITE_ABORT;
  63108. #endif
  63109. REGISTER_TRACE(pOp->p3, pOut);
  63110. UPDATE_MAX_BLOBSIZE(pOut);
  63111. break;
  63112. }
  63113. /* Opcode: BitAnd P1 P2 P3 * *
  63114. **
  63115. ** Take the bit-wise AND of the values in register P1 and P2 and
  63116. ** store the result in register P3.
  63117. ** If either input is NULL, the result is NULL.
  63118. */
  63119. /* Opcode: BitOr P1 P2 P3 * *
  63120. **
  63121. ** Take the bit-wise OR of the values in register P1 and P2 and
  63122. ** store the result in register P3.
  63123. ** If either input is NULL, the result is NULL.
  63124. */
  63125. /* Opcode: ShiftLeft P1 P2 P3 * *
  63126. **
  63127. ** Shift the integer value in register P2 to the left by the
  63128. ** number of bits specified by the integer in register P1.
  63129. ** Store the result in register P3.
  63130. ** If either input is NULL, the result is NULL.
  63131. */
  63132. /* Opcode: ShiftRight P1 P2 P3 * *
  63133. **
  63134. ** Shift the integer value in register P2 to the right by the
  63135. ** number of bits specified by the integer in register P1.
  63136. ** Store the result in register P3.
  63137. ** If either input is NULL, the result is NULL.
  63138. */
  63139. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  63140. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  63141. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  63142. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  63143. #if 0 /* local variables moved into u.aj */
  63144. i64 iA;
  63145. u64 uA;
  63146. i64 iB;
  63147. u8 op;
  63148. #endif /* local variables moved into u.aj */
  63149. pIn1 = &aMem[pOp->p1];
  63150. pIn2 = &aMem[pOp->p2];
  63151. pOut = &aMem[pOp->p3];
  63152. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  63153. sqlite3VdbeMemSetNull(pOut);
  63154. break;
  63155. }
  63156. u.aj.iA = sqlite3VdbeIntValue(pIn2);
  63157. u.aj.iB = sqlite3VdbeIntValue(pIn1);
  63158. u.aj.op = pOp->opcode;
  63159. if( u.aj.op==OP_BitAnd ){
  63160. u.aj.iA &= u.aj.iB;
  63161. }else if( u.aj.op==OP_BitOr ){
  63162. u.aj.iA |= u.aj.iB;
  63163. }else if( u.aj.iB!=0 ){
  63164. assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
  63165. /* If shifting by a negative amount, shift in the other direction */
  63166. if( u.aj.iB<0 ){
  63167. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  63168. u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
  63169. u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
  63170. }
  63171. if( u.aj.iB>=64 ){
  63172. u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
  63173. }else{
  63174. memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
  63175. if( u.aj.op==OP_ShiftLeft ){
  63176. u.aj.uA <<= u.aj.iB;
  63177. }else{
  63178. u.aj.uA >>= u.aj.iB;
  63179. /* Sign-extend on a right shift of a negative number */
  63180. if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
  63181. }
  63182. memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
  63183. }
  63184. }
  63185. pOut->u.i = u.aj.iA;
  63186. MemSetTypeFlag(pOut, MEM_Int);
  63187. break;
  63188. }
  63189. /* Opcode: AddImm P1 P2 * * *
  63190. **
  63191. ** Add the constant P2 to the value in register P1.
  63192. ** The result is always an integer.
  63193. **
  63194. ** To force any register to be an integer, just add 0.
  63195. */
  63196. case OP_AddImm: { /* in1 */
  63197. pIn1 = &aMem[pOp->p1];
  63198. memAboutToChange(p, pIn1);
  63199. sqlite3VdbeMemIntegerify(pIn1);
  63200. pIn1->u.i += pOp->p2;
  63201. break;
  63202. }
  63203. /* Opcode: MustBeInt P1 P2 * * *
  63204. **
  63205. ** Force the value in register P1 to be an integer. If the value
  63206. ** in P1 is not an integer and cannot be converted into an integer
  63207. ** without data loss, then jump immediately to P2, or if P2==0
  63208. ** raise an SQLITE_MISMATCH exception.
  63209. */
  63210. case OP_MustBeInt: { /* jump, in1 */
  63211. pIn1 = &aMem[pOp->p1];
  63212. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  63213. if( (pIn1->flags & MEM_Int)==0 ){
  63214. if( pOp->p2==0 ){
  63215. rc = SQLITE_MISMATCH;
  63216. goto abort_due_to_error;
  63217. }else{
  63218. pc = pOp->p2 - 1;
  63219. }
  63220. }else{
  63221. MemSetTypeFlag(pIn1, MEM_Int);
  63222. }
  63223. break;
  63224. }
  63225. #ifndef SQLITE_OMIT_FLOATING_POINT
  63226. /* Opcode: RealAffinity P1 * * * *
  63227. **
  63228. ** If register P1 holds an integer convert it to a real value.
  63229. **
  63230. ** This opcode is used when extracting information from a column that
  63231. ** has REAL affinity. Such column values may still be stored as
  63232. ** integers, for space efficiency, but after extraction we want them
  63233. ** to have only a real value.
  63234. */
  63235. case OP_RealAffinity: { /* in1 */
  63236. pIn1 = &aMem[pOp->p1];
  63237. if( pIn1->flags & MEM_Int ){
  63238. sqlite3VdbeMemRealify(pIn1);
  63239. }
  63240. break;
  63241. }
  63242. #endif
  63243. #ifndef SQLITE_OMIT_CAST
  63244. /* Opcode: ToText P1 * * * *
  63245. **
  63246. ** Force the value in register P1 to be text.
  63247. ** If the value is numeric, convert it to a string using the
  63248. ** equivalent of printf(). Blob values are unchanged and
  63249. ** are afterwards simply interpreted as text.
  63250. **
  63251. ** A NULL value is not changed by this routine. It remains NULL.
  63252. */
  63253. case OP_ToText: { /* same as TK_TO_TEXT, in1 */
  63254. pIn1 = &aMem[pOp->p1];
  63255. memAboutToChange(p, pIn1);
  63256. if( pIn1->flags & MEM_Null ) break;
  63257. assert( MEM_Str==(MEM_Blob>>3) );
  63258. pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
  63259. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  63260. rc = ExpandBlob(pIn1);
  63261. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  63262. pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  63263. UPDATE_MAX_BLOBSIZE(pIn1);
  63264. break;
  63265. }
  63266. /* Opcode: ToBlob P1 * * * *
  63267. **
  63268. ** Force the value in register P1 to be a BLOB.
  63269. ** If the value is numeric, convert it to a string first.
  63270. ** Strings are simply reinterpreted as blobs with no change
  63271. ** to the underlying data.
  63272. **
  63273. ** A NULL value is not changed by this routine. It remains NULL.
  63274. */
  63275. case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
  63276. pIn1 = &aMem[pOp->p1];
  63277. if( pIn1->flags & MEM_Null ) break;
  63278. if( (pIn1->flags & MEM_Blob)==0 ){
  63279. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  63280. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  63281. MemSetTypeFlag(pIn1, MEM_Blob);
  63282. }else{
  63283. pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
  63284. }
  63285. UPDATE_MAX_BLOBSIZE(pIn1);
  63286. break;
  63287. }
  63288. /* Opcode: ToNumeric P1 * * * *
  63289. **
  63290. ** Force the value in register P1 to be numeric (either an
  63291. ** integer or a floating-point number.)
  63292. ** If the value is text or blob, try to convert it to an using the
  63293. ** equivalent of atoi() or atof() and store 0 if no such conversion
  63294. ** is possible.
  63295. **
  63296. ** A NULL value is not changed by this routine. It remains NULL.
  63297. */
  63298. case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
  63299. pIn1 = &aMem[pOp->p1];
  63300. sqlite3VdbeMemNumerify(pIn1);
  63301. break;
  63302. }
  63303. #endif /* SQLITE_OMIT_CAST */
  63304. /* Opcode: ToInt P1 * * * *
  63305. **
  63306. ** Force the value in register P1 to be an integer. If
  63307. ** The value is currently a real number, drop its fractional part.
  63308. ** If the value is text or blob, try to convert it to an integer using the
  63309. ** equivalent of atoi() and store 0 if no such conversion is possible.
  63310. **
  63311. ** A NULL value is not changed by this routine. It remains NULL.
  63312. */
  63313. case OP_ToInt: { /* same as TK_TO_INT, in1 */
  63314. pIn1 = &aMem[pOp->p1];
  63315. if( (pIn1->flags & MEM_Null)==0 ){
  63316. sqlite3VdbeMemIntegerify(pIn1);
  63317. }
  63318. break;
  63319. }
  63320. #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
  63321. /* Opcode: ToReal P1 * * * *
  63322. **
  63323. ** Force the value in register P1 to be a floating point number.
  63324. ** If The value is currently an integer, convert it.
  63325. ** If the value is text or blob, try to convert it to an integer using the
  63326. ** equivalent of atoi() and store 0.0 if no such conversion is possible.
  63327. **
  63328. ** A NULL value is not changed by this routine. It remains NULL.
  63329. */
  63330. case OP_ToReal: { /* same as TK_TO_REAL, in1 */
  63331. pIn1 = &aMem[pOp->p1];
  63332. memAboutToChange(p, pIn1);
  63333. if( (pIn1->flags & MEM_Null)==0 ){
  63334. sqlite3VdbeMemRealify(pIn1);
  63335. }
  63336. break;
  63337. }
  63338. #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
  63339. /* Opcode: Lt P1 P2 P3 P4 P5
  63340. **
  63341. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  63342. ** jump to address P2.
  63343. **
  63344. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  63345. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  63346. ** bit is clear then fall through if either operand is NULL.
  63347. **
  63348. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  63349. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  63350. ** to coerce both inputs according to this affinity before the
  63351. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  63352. ** affinity is used. Note that the affinity conversions are stored
  63353. ** back into the input registers P1 and P3. So this opcode can cause
  63354. ** persistent changes to registers P1 and P3.
  63355. **
  63356. ** Once any conversions have taken place, and neither value is NULL,
  63357. ** the values are compared. If both values are blobs then memcmp() is
  63358. ** used to determine the results of the comparison. If both values
  63359. ** are text, then the appropriate collating function specified in
  63360. ** P4 is used to do the comparison. If P4 is not specified then
  63361. ** memcmp() is used to compare text string. If both values are
  63362. ** numeric, then a numeric comparison is used. If the two values
  63363. ** are of different types, then numbers are considered less than
  63364. ** strings and strings are considered less than blobs.
  63365. **
  63366. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  63367. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  63368. **
  63369. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  63370. ** equal to one another, provided that they do not have their MEM_Cleared
  63371. ** bit set.
  63372. */
  63373. /* Opcode: Ne P1 P2 P3 P4 P5
  63374. **
  63375. ** This works just like the Lt opcode except that the jump is taken if
  63376. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  63377. ** additional information.
  63378. **
  63379. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  63380. ** true or false and is never NULL. If both operands are NULL then the result
  63381. ** of comparison is false. If either operand is NULL then the result is true.
  63382. ** If neither operand is NULL the result is the same as it would be if
  63383. ** the SQLITE_NULLEQ flag were omitted from P5.
  63384. */
  63385. /* Opcode: Eq P1 P2 P3 P4 P5
  63386. **
  63387. ** This works just like the Lt opcode except that the jump is taken if
  63388. ** the operands in registers P1 and P3 are equal.
  63389. ** See the Lt opcode for additional information.
  63390. **
  63391. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  63392. ** true or false and is never NULL. If both operands are NULL then the result
  63393. ** of comparison is true. If either operand is NULL then the result is false.
  63394. ** If neither operand is NULL the result is the same as it would be if
  63395. ** the SQLITE_NULLEQ flag were omitted from P5.
  63396. */
  63397. /* Opcode: Le P1 P2 P3 P4 P5
  63398. **
  63399. ** This works just like the Lt opcode except that the jump is taken if
  63400. ** the content of register P3 is less than or equal to the content of
  63401. ** register P1. See the Lt opcode for additional information.
  63402. */
  63403. /* Opcode: Gt P1 P2 P3 P4 P5
  63404. **
  63405. ** This works just like the Lt opcode except that the jump is taken if
  63406. ** the content of register P3 is greater than the content of
  63407. ** register P1. See the Lt opcode for additional information.
  63408. */
  63409. /* Opcode: Ge P1 P2 P3 P4 P5
  63410. **
  63411. ** This works just like the Lt opcode except that the jump is taken if
  63412. ** the content of register P3 is greater than or equal to the content of
  63413. ** register P1. See the Lt opcode for additional information.
  63414. */
  63415. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  63416. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  63417. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  63418. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  63419. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  63420. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  63421. #if 0 /* local variables moved into u.ak */
  63422. int res; /* Result of the comparison of pIn1 against pIn3 */
  63423. char affinity; /* Affinity to use for comparison */
  63424. u16 flags1; /* Copy of initial value of pIn1->flags */
  63425. u16 flags3; /* Copy of initial value of pIn3->flags */
  63426. #endif /* local variables moved into u.ak */
  63427. pIn1 = &aMem[pOp->p1];
  63428. pIn3 = &aMem[pOp->p3];
  63429. u.ak.flags1 = pIn1->flags;
  63430. u.ak.flags3 = pIn3->flags;
  63431. if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
  63432. /* One or both operands are NULL */
  63433. if( pOp->p5 & SQLITE_NULLEQ ){
  63434. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  63435. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  63436. ** or not both operands are null.
  63437. */
  63438. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  63439. assert( (u.ak.flags1 & MEM_Cleared)==0 );
  63440. if( (u.ak.flags1&MEM_Null)!=0
  63441. && (u.ak.flags3&MEM_Null)!=0
  63442. && (u.ak.flags3&MEM_Cleared)==0
  63443. ){
  63444. u.ak.res = 0; /* Results are equal */
  63445. }else{
  63446. u.ak.res = 1; /* Results are not equal */
  63447. }
  63448. }else{
  63449. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  63450. ** then the result is always NULL.
  63451. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  63452. */
  63453. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  63454. pc = pOp->p2-1;
  63455. }else if( pOp->p5 & SQLITE_STOREP2 ){
  63456. pOut = &aMem[pOp->p2];
  63457. MemSetTypeFlag(pOut, MEM_Null);
  63458. REGISTER_TRACE(pOp->p2, pOut);
  63459. }
  63460. break;
  63461. }
  63462. }else{
  63463. /* Neither operand is NULL. Do a comparison. */
  63464. u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
  63465. if( u.ak.affinity ){
  63466. applyAffinity(pIn1, u.ak.affinity, encoding);
  63467. applyAffinity(pIn3, u.ak.affinity, encoding);
  63468. if( db->mallocFailed ) goto no_mem;
  63469. }
  63470. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  63471. ExpandBlob(pIn1);
  63472. ExpandBlob(pIn3);
  63473. u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  63474. }
  63475. switch( pOp->opcode ){
  63476. case OP_Eq: u.ak.res = u.ak.res==0; break;
  63477. case OP_Ne: u.ak.res = u.ak.res!=0; break;
  63478. case OP_Lt: u.ak.res = u.ak.res<0; break;
  63479. case OP_Le: u.ak.res = u.ak.res<=0; break;
  63480. case OP_Gt: u.ak.res = u.ak.res>0; break;
  63481. default: u.ak.res = u.ak.res>=0; break;
  63482. }
  63483. if( pOp->p5 & SQLITE_STOREP2 ){
  63484. pOut = &aMem[pOp->p2];
  63485. memAboutToChange(p, pOut);
  63486. MemSetTypeFlag(pOut, MEM_Int);
  63487. pOut->u.i = u.ak.res;
  63488. REGISTER_TRACE(pOp->p2, pOut);
  63489. }else if( u.ak.res ){
  63490. pc = pOp->p2-1;
  63491. }
  63492. /* Undo any changes made by applyAffinity() to the input registers. */
  63493. pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
  63494. pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
  63495. break;
  63496. }
  63497. /* Opcode: Permutation * * * P4 *
  63498. **
  63499. ** Set the permutation used by the OP_Compare operator to be the array
  63500. ** of integers in P4.
  63501. **
  63502. ** The permutation is only valid until the next OP_Compare that has
  63503. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  63504. ** occur immediately prior to the OP_Compare.
  63505. */
  63506. case OP_Permutation: {
  63507. assert( pOp->p4type==P4_INTARRAY );
  63508. assert( pOp->p4.ai );
  63509. aPermute = pOp->p4.ai;
  63510. break;
  63511. }
  63512. /* Opcode: Compare P1 P2 P3 P4 P5
  63513. **
  63514. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  63515. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  63516. ** the comparison for use by the next OP_Jump instruct.
  63517. **
  63518. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  63519. ** determined by the most recent OP_Permutation operator. If the
  63520. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  63521. ** order.
  63522. **
  63523. ** P4 is a KeyInfo structure that defines collating sequences and sort
  63524. ** orders for the comparison. The permutation applies to registers
  63525. ** only. The KeyInfo elements are used sequentially.
  63526. **
  63527. ** The comparison is a sort comparison, so NULLs compare equal,
  63528. ** NULLs are less than numbers, numbers are less than strings,
  63529. ** and strings are less than blobs.
  63530. */
  63531. case OP_Compare: {
  63532. #if 0 /* local variables moved into u.al */
  63533. int n;
  63534. int i;
  63535. int p1;
  63536. int p2;
  63537. const KeyInfo *pKeyInfo;
  63538. int idx;
  63539. CollSeq *pColl; /* Collating sequence to use on this term */
  63540. int bRev; /* True for DESCENDING sort order */
  63541. #endif /* local variables moved into u.al */
  63542. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  63543. u.al.n = pOp->p3;
  63544. u.al.pKeyInfo = pOp->p4.pKeyInfo;
  63545. assert( u.al.n>0 );
  63546. assert( u.al.pKeyInfo!=0 );
  63547. u.al.p1 = pOp->p1;
  63548. u.al.p2 = pOp->p2;
  63549. #if SQLITE_DEBUG
  63550. if( aPermute ){
  63551. int k, mx = 0;
  63552. for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  63553. assert( u.al.p1>0 && u.al.p1+mx<=(p->nMem-p->nCursor)+1 );
  63554. assert( u.al.p2>0 && u.al.p2+mx<=(p->nMem-p->nCursor)+1 );
  63555. }else{
  63556. assert( u.al.p1>0 && u.al.p1+u.al.n<=(p->nMem-p->nCursor)+1 );
  63557. assert( u.al.p2>0 && u.al.p2+u.al.n<=(p->nMem-p->nCursor)+1 );
  63558. }
  63559. #endif /* SQLITE_DEBUG */
  63560. for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
  63561. u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
  63562. assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
  63563. assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
  63564. REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
  63565. REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
  63566. assert( u.al.i<u.al.pKeyInfo->nField );
  63567. u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
  63568. u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
  63569. iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
  63570. if( iCompare ){
  63571. if( u.al.bRev ) iCompare = -iCompare;
  63572. break;
  63573. }
  63574. }
  63575. aPermute = 0;
  63576. break;
  63577. }
  63578. /* Opcode: Jump P1 P2 P3 * *
  63579. **
  63580. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  63581. ** in the most recent OP_Compare instruction the P1 vector was less than
  63582. ** equal to, or greater than the P2 vector, respectively.
  63583. */
  63584. case OP_Jump: { /* jump */
  63585. if( iCompare<0 ){
  63586. pc = pOp->p1 - 1;
  63587. }else if( iCompare==0 ){
  63588. pc = pOp->p2 - 1;
  63589. }else{
  63590. pc = pOp->p3 - 1;
  63591. }
  63592. break;
  63593. }
  63594. /* Opcode: And P1 P2 P3 * *
  63595. **
  63596. ** Take the logical AND of the values in registers P1 and P2 and
  63597. ** write the result into register P3.
  63598. **
  63599. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  63600. ** the other input is NULL. A NULL and true or two NULLs give
  63601. ** a NULL output.
  63602. */
  63603. /* Opcode: Or P1 P2 P3 * *
  63604. **
  63605. ** Take the logical OR of the values in register P1 and P2 and
  63606. ** store the answer in register P3.
  63607. **
  63608. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  63609. ** even if the other input is NULL. A NULL and false or two NULLs
  63610. ** give a NULL output.
  63611. */
  63612. case OP_And: /* same as TK_AND, in1, in2, out3 */
  63613. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  63614. #if 0 /* local variables moved into u.am */
  63615. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  63616. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  63617. #endif /* local variables moved into u.am */
  63618. pIn1 = &aMem[pOp->p1];
  63619. if( pIn1->flags & MEM_Null ){
  63620. u.am.v1 = 2;
  63621. }else{
  63622. u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
  63623. }
  63624. pIn2 = &aMem[pOp->p2];
  63625. if( pIn2->flags & MEM_Null ){
  63626. u.am.v2 = 2;
  63627. }else{
  63628. u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
  63629. }
  63630. if( pOp->opcode==OP_And ){
  63631. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  63632. u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
  63633. }else{
  63634. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  63635. u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
  63636. }
  63637. pOut = &aMem[pOp->p3];
  63638. if( u.am.v1==2 ){
  63639. MemSetTypeFlag(pOut, MEM_Null);
  63640. }else{
  63641. pOut->u.i = u.am.v1;
  63642. MemSetTypeFlag(pOut, MEM_Int);
  63643. }
  63644. break;
  63645. }
  63646. /* Opcode: Not P1 P2 * * *
  63647. **
  63648. ** Interpret the value in register P1 as a boolean value. Store the
  63649. ** boolean complement in register P2. If the value in register P1 is
  63650. ** NULL, then a NULL is stored in P2.
  63651. */
  63652. case OP_Not: { /* same as TK_NOT, in1, out2 */
  63653. pIn1 = &aMem[pOp->p1];
  63654. pOut = &aMem[pOp->p2];
  63655. if( pIn1->flags & MEM_Null ){
  63656. sqlite3VdbeMemSetNull(pOut);
  63657. }else{
  63658. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
  63659. }
  63660. break;
  63661. }
  63662. /* Opcode: BitNot P1 P2 * * *
  63663. **
  63664. ** Interpret the content of register P1 as an integer. Store the
  63665. ** ones-complement of the P1 value into register P2. If P1 holds
  63666. ** a NULL then store a NULL in P2.
  63667. */
  63668. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  63669. pIn1 = &aMem[pOp->p1];
  63670. pOut = &aMem[pOp->p2];
  63671. if( pIn1->flags & MEM_Null ){
  63672. sqlite3VdbeMemSetNull(pOut);
  63673. }else{
  63674. sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
  63675. }
  63676. break;
  63677. }
  63678. /* Opcode: Once P1 P2 * * *
  63679. **
  63680. ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
  63681. ** set the flag and fall through to the next instruction.
  63682. */
  63683. case OP_Once: { /* jump */
  63684. assert( pOp->p1<p->nOnceFlag );
  63685. if( p->aOnceFlag[pOp->p1] ){
  63686. pc = pOp->p2-1;
  63687. }else{
  63688. p->aOnceFlag[pOp->p1] = 1;
  63689. }
  63690. break;
  63691. }
  63692. /* Opcode: If P1 P2 P3 * *
  63693. **
  63694. ** Jump to P2 if the value in register P1 is true. The value
  63695. ** is considered true if it is numeric and non-zero. If the value
  63696. ** in P1 is NULL then take the jump if P3 is non-zero.
  63697. */
  63698. /* Opcode: IfNot P1 P2 P3 * *
  63699. **
  63700. ** Jump to P2 if the value in register P1 is False. The value
  63701. ** is considered false if it has a numeric value of zero. If the value
  63702. ** in P1 is NULL then take the jump if P3 is zero.
  63703. */
  63704. case OP_If: /* jump, in1 */
  63705. case OP_IfNot: { /* jump, in1 */
  63706. #if 0 /* local variables moved into u.an */
  63707. int c;
  63708. #endif /* local variables moved into u.an */
  63709. pIn1 = &aMem[pOp->p1];
  63710. if( pIn1->flags & MEM_Null ){
  63711. u.an.c = pOp->p3;
  63712. }else{
  63713. #ifdef SQLITE_OMIT_FLOATING_POINT
  63714. u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
  63715. #else
  63716. u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
  63717. #endif
  63718. if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
  63719. }
  63720. if( u.an.c ){
  63721. pc = pOp->p2-1;
  63722. }
  63723. break;
  63724. }
  63725. /* Opcode: IsNull P1 P2 * * *
  63726. **
  63727. ** Jump to P2 if the value in register P1 is NULL.
  63728. */
  63729. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  63730. pIn1 = &aMem[pOp->p1];
  63731. if( (pIn1->flags & MEM_Null)!=0 ){
  63732. pc = pOp->p2 - 1;
  63733. }
  63734. break;
  63735. }
  63736. /* Opcode: NotNull P1 P2 * * *
  63737. **
  63738. ** Jump to P2 if the value in register P1 is not NULL.
  63739. */
  63740. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  63741. pIn1 = &aMem[pOp->p1];
  63742. if( (pIn1->flags & MEM_Null)==0 ){
  63743. pc = pOp->p2 - 1;
  63744. }
  63745. break;
  63746. }
  63747. /* Opcode: Column P1 P2 P3 P4 P5
  63748. **
  63749. ** Interpret the data that cursor P1 points to as a structure built using
  63750. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  63751. ** information about the format of the data.) Extract the P2-th column
  63752. ** from this record. If there are less that (P2+1)
  63753. ** values in the record, extract a NULL.
  63754. **
  63755. ** The value extracted is stored in register P3.
  63756. **
  63757. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  63758. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  63759. ** the result.
  63760. **
  63761. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  63762. ** then the cache of the cursor is reset prior to extracting the column.
  63763. ** The first OP_Column against a pseudo-table after the value of the content
  63764. ** register has changed should have this bit set.
  63765. **
  63766. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  63767. ** the result is guaranteed to only be used as the argument of a length()
  63768. ** or typeof() function, respectively. The loading of large blobs can be
  63769. ** skipped for length() and all content loading can be skipped for typeof().
  63770. */
  63771. case OP_Column: {
  63772. #if 0 /* local variables moved into u.ao */
  63773. u32 payloadSize; /* Number of bytes in the record */
  63774. i64 payloadSize64; /* Number of bytes in the record */
  63775. int p1; /* P1 value of the opcode */
  63776. int p2; /* column number to retrieve */
  63777. VdbeCursor *pC; /* The VDBE cursor */
  63778. char *zRec; /* Pointer to complete record-data */
  63779. BtCursor *pCrsr; /* The BTree cursor */
  63780. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  63781. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  63782. int nField; /* number of fields in the record */
  63783. int len; /* The length of the serialized data for the column */
  63784. int i; /* Loop counter */
  63785. char *zData; /* Part of the record being decoded */
  63786. Mem *pDest; /* Where to write the extracted value */
  63787. Mem sMem; /* For storing the record being decoded */
  63788. u8 *zIdx; /* Index into header */
  63789. u8 *zEndHdr; /* Pointer to first byte after the header */
  63790. u32 offset; /* Offset into the data */
  63791. u32 szField; /* Number of bytes in the content of a field */
  63792. int szHdr; /* Size of the header size field at start of record */
  63793. int avail; /* Number of bytes of available data */
  63794. u32 t; /* A type code from the record header */
  63795. Mem *pReg; /* PseudoTable input register */
  63796. #endif /* local variables moved into u.ao */
  63797. u.ao.p1 = pOp->p1;
  63798. u.ao.p2 = pOp->p2;
  63799. u.ao.pC = 0;
  63800. memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
  63801. assert( u.ao.p1<p->nCursor );
  63802. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  63803. u.ao.pDest = &aMem[pOp->p3];
  63804. memAboutToChange(p, u.ao.pDest);
  63805. u.ao.zRec = 0;
  63806. /* This block sets the variable u.ao.payloadSize to be the total number of
  63807. ** bytes in the record.
  63808. **
  63809. ** u.ao.zRec is set to be the complete text of the record if it is available.
  63810. ** The complete record text is always available for pseudo-tables
  63811. ** If the record is stored in a cursor, the complete record text
  63812. ** might be available in the u.ao.pC->aRow cache. Or it might not be.
  63813. ** If the data is unavailable, u.ao.zRec is set to NULL.
  63814. **
  63815. ** We also compute the number of columns in the record. For cursors,
  63816. ** the number of columns is stored in the VdbeCursor.nField element.
  63817. */
  63818. u.ao.pC = p->apCsr[u.ao.p1];
  63819. assert( u.ao.pC!=0 );
  63820. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63821. assert( u.ao.pC->pVtabCursor==0 );
  63822. #endif
  63823. u.ao.pCrsr = u.ao.pC->pCursor;
  63824. if( u.ao.pCrsr!=0 ){
  63825. /* The record is stored in a B-Tree */
  63826. rc = sqlite3VdbeCursorMoveto(u.ao.pC);
  63827. if( rc ) goto abort_due_to_error;
  63828. if( u.ao.pC->nullRow ){
  63829. u.ao.payloadSize = 0;
  63830. }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
  63831. u.ao.payloadSize = u.ao.pC->payloadSize;
  63832. u.ao.zRec = (char*)u.ao.pC->aRow;
  63833. }else if( u.ao.pC->isIndex ){
  63834. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  63835. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
  63836. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  63837. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  63838. ** payload size, so it is impossible for u.ao.payloadSize64 to be
  63839. ** larger than 32 bits. */
  63840. assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
  63841. u.ao.payloadSize = (u32)u.ao.payloadSize64;
  63842. }else{
  63843. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  63844. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
  63845. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  63846. }
  63847. }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
  63848. u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
  63849. if( u.ao.pC->multiPseudo ){
  63850. sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
  63851. Deephemeralize(u.ao.pDest);
  63852. goto op_column_out;
  63853. }
  63854. assert( u.ao.pReg->flags & MEM_Blob );
  63855. assert( memIsValid(u.ao.pReg) );
  63856. u.ao.payloadSize = u.ao.pReg->n;
  63857. u.ao.zRec = u.ao.pReg->z;
  63858. u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
  63859. assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
  63860. }else{
  63861. /* Consider the row to be NULL */
  63862. u.ao.payloadSize = 0;
  63863. }
  63864. /* If u.ao.payloadSize is 0, then just store a NULL. This can happen because of
  63865. ** nullRow or because of a corrupt database. */
  63866. if( u.ao.payloadSize==0 ){
  63867. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  63868. goto op_column_out;
  63869. }
  63870. assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
  63871. if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  63872. goto too_big;
  63873. }
  63874. u.ao.nField = u.ao.pC->nField;
  63875. assert( u.ao.p2<u.ao.nField );
  63876. /* Read and parse the table header. Store the results of the parse
  63877. ** into the record header cache fields of the cursor.
  63878. */
  63879. u.ao.aType = u.ao.pC->aType;
  63880. if( u.ao.pC->cacheStatus==p->cacheCtr ){
  63881. u.ao.aOffset = u.ao.pC->aOffset;
  63882. }else{
  63883. assert(u.ao.aType);
  63884. u.ao.avail = 0;
  63885. u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
  63886. u.ao.pC->payloadSize = u.ao.payloadSize;
  63887. u.ao.pC->cacheStatus = p->cacheCtr;
  63888. /* Figure out how many bytes are in the header */
  63889. if( u.ao.zRec ){
  63890. u.ao.zData = u.ao.zRec;
  63891. }else{
  63892. if( u.ao.pC->isIndex ){
  63893. u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
  63894. }else{
  63895. u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
  63896. }
  63897. /* If KeyFetch()/DataFetch() managed to get the entire payload,
  63898. ** save the payload in the u.ao.pC->aRow cache. That will save us from
  63899. ** having to make additional calls to fetch the content portion of
  63900. ** the record.
  63901. */
  63902. assert( u.ao.avail>=0 );
  63903. if( u.ao.payloadSize <= (u32)u.ao.avail ){
  63904. u.ao.zRec = u.ao.zData;
  63905. u.ao.pC->aRow = (u8*)u.ao.zData;
  63906. }else{
  63907. u.ao.pC->aRow = 0;
  63908. }
  63909. }
  63910. /* The following assert is true in all cases except when
  63911. ** the database file has been corrupted externally.
  63912. ** assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
  63913. u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
  63914. /* Make sure a corrupt database has not given us an oversize header.
  63915. ** Do this now to avoid an oversize memory allocation.
  63916. **
  63917. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  63918. ** types use so much data space that there can only be 4096 and 32 of
  63919. ** them, respectively. So the maximum header length results from a
  63920. ** 3-byte type for each of the maximum of 32768 columns plus three
  63921. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  63922. */
  63923. if( u.ao.offset > 98307 ){
  63924. rc = SQLITE_CORRUPT_BKPT;
  63925. goto op_column_out;
  63926. }
  63927. /* Compute in u.ao.len the number of bytes of data we need to read in order
  63928. ** to get u.ao.nField type values. u.ao.offset is an upper bound on this. But
  63929. ** u.ao.nField might be significantly less than the true number of columns
  63930. ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
  63931. ** We want to minimize u.ao.len in order to limit the size of the memory
  63932. ** allocation, especially if a corrupt database file has caused u.ao.offset
  63933. ** to be oversized. Offset is limited to 98307 above. But 98307 might
  63934. ** still exceed Robson memory allocation limits on some configurations.
  63935. ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
  63936. ** will likely be much smaller since u.ao.nField will likely be less than
  63937. ** 20 or so. This insures that Robson memory allocation limits are
  63938. ** not exceeded even for corrupt database files.
  63939. */
  63940. u.ao.len = u.ao.nField*5 + 3;
  63941. if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
  63942. /* The KeyFetch() or DataFetch() above are fast and will get the entire
  63943. ** record header in most cases. But they will fail to get the complete
  63944. ** record header if the record header does not fit on a single page
  63945. ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
  63946. ** acquire the complete header text.
  63947. */
  63948. if( !u.ao.zRec && u.ao.avail<u.ao.len ){
  63949. u.ao.sMem.flags = 0;
  63950. u.ao.sMem.db = 0;
  63951. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
  63952. if( rc!=SQLITE_OK ){
  63953. goto op_column_out;
  63954. }
  63955. u.ao.zData = u.ao.sMem.z;
  63956. }
  63957. u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
  63958. u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
  63959. /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
  63960. ** arrays. u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
  63961. ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
  63962. ** of the record to the start of the data for the u.ao.i-th column
  63963. */
  63964. for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
  63965. if( u.ao.zIdx<u.ao.zEndHdr ){
  63966. u.ao.aOffset[u.ao.i] = u.ao.offset;
  63967. if( u.ao.zIdx[0]<0x80 ){
  63968. u.ao.t = u.ao.zIdx[0];
  63969. u.ao.zIdx++;
  63970. }else{
  63971. u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
  63972. }
  63973. u.ao.aType[u.ao.i] = u.ao.t;
  63974. u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
  63975. u.ao.offset += u.ao.szField;
  63976. if( u.ao.offset<u.ao.szField ){ /* True if u.ao.offset overflows */
  63977. u.ao.zIdx = &u.ao.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  63978. break;
  63979. }
  63980. }else{
  63981. /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
  63982. ** record than SetNumColumns indicated there are columns in the
  63983. ** table. Set the u.ao.offset for any extra columns not present in
  63984. ** the record to 0. This tells code below to store the default value
  63985. ** for the column instead of deserializing a value from the record.
  63986. */
  63987. u.ao.aOffset[u.ao.i] = 0;
  63988. }
  63989. }
  63990. sqlite3VdbeMemRelease(&u.ao.sMem);
  63991. u.ao.sMem.flags = MEM_Null;
  63992. /* If we have read more header data than was contained in the header,
  63993. ** or if the end of the last field appears to be past the end of the
  63994. ** record, or if the end of the last field appears to be before the end
  63995. ** of the record (when all fields present), then we must be dealing
  63996. ** with a corrupt database.
  63997. */
  63998. if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
  63999. || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
  64000. rc = SQLITE_CORRUPT_BKPT;
  64001. goto op_column_out;
  64002. }
  64003. }
  64004. /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
  64005. ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
  64006. ** then there are not enough fields in the record to satisfy the
  64007. ** request. In this case, set the value NULL or to P4 if P4 is
  64008. ** a pointer to a Mem object.
  64009. */
  64010. if( u.ao.aOffset[u.ao.p2] ){
  64011. assert( rc==SQLITE_OK );
  64012. if( u.ao.zRec ){
  64013. /* This is the common case where the whole row fits on a single page */
  64014. VdbeMemRelease(u.ao.pDest);
  64015. sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
  64016. }else{
  64017. /* This branch happens only when the row overflows onto multiple pages */
  64018. u.ao.t = u.ao.aType[u.ao.p2];
  64019. if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  64020. && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
  64021. ){
  64022. /* Content is irrelevant for the typeof() function and for
  64023. ** the length(X) function if X is a blob. So we might as well use
  64024. ** bogus content rather than reading content from disk. NULL works
  64025. ** for text and blob and whatever is in the u.ao.payloadSize64 variable
  64026. ** will work for everything else. */
  64027. u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
  64028. }else{
  64029. u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
  64030. sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
  64031. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len, u.ao.pC->isIndex,
  64032. &u.ao.sMem);
  64033. if( rc!=SQLITE_OK ){
  64034. goto op_column_out;
  64035. }
  64036. u.ao.zData = u.ao.sMem.z;
  64037. }
  64038. sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
  64039. }
  64040. u.ao.pDest->enc = encoding;
  64041. }else{
  64042. if( pOp->p4type==P4_MEM ){
  64043. sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
  64044. }else{
  64045. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  64046. }
  64047. }
  64048. /* If we dynamically allocated space to hold the data (in the
  64049. ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  64050. ** dynamically allocated space over to the u.ao.pDest structure.
  64051. ** This prevents a memory copy.
  64052. */
  64053. if( u.ao.sMem.zMalloc ){
  64054. assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
  64055. assert( !(u.ao.pDest->flags & MEM_Dyn) );
  64056. assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
  64057. u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
  64058. u.ao.pDest->flags |= MEM_Term;
  64059. u.ao.pDest->z = u.ao.sMem.z;
  64060. u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
  64061. }
  64062. rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
  64063. op_column_out:
  64064. UPDATE_MAX_BLOBSIZE(u.ao.pDest);
  64065. REGISTER_TRACE(pOp->p3, u.ao.pDest);
  64066. break;
  64067. }
  64068. /* Opcode: Affinity P1 P2 * P4 *
  64069. **
  64070. ** Apply affinities to a range of P2 registers starting with P1.
  64071. **
  64072. ** P4 is a string that is P2 characters long. The nth character of the
  64073. ** string indicates the column affinity that should be used for the nth
  64074. ** memory cell in the range.
  64075. */
  64076. case OP_Affinity: {
  64077. #if 0 /* local variables moved into u.ap */
  64078. const char *zAffinity; /* The affinity to be applied */
  64079. char cAff; /* A single character of affinity */
  64080. #endif /* local variables moved into u.ap */
  64081. u.ap.zAffinity = pOp->p4.z;
  64082. assert( u.ap.zAffinity!=0 );
  64083. assert( u.ap.zAffinity[pOp->p2]==0 );
  64084. pIn1 = &aMem[pOp->p1];
  64085. while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
  64086. assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  64087. assert( memIsValid(pIn1) );
  64088. ExpandBlob(pIn1);
  64089. applyAffinity(pIn1, u.ap.cAff, encoding);
  64090. pIn1++;
  64091. }
  64092. break;
  64093. }
  64094. /* Opcode: MakeRecord P1 P2 P3 P4 *
  64095. **
  64096. ** Convert P2 registers beginning with P1 into the [record format]
  64097. ** use as a data record in a database table or as a key
  64098. ** in an index. The OP_Column opcode can decode the record later.
  64099. **
  64100. ** P4 may be a string that is P2 characters long. The nth character of the
  64101. ** string indicates the column affinity that should be used for the nth
  64102. ** field of the index key.
  64103. **
  64104. ** The mapping from character to affinity is given by the SQLITE_AFF_
  64105. ** macros defined in sqliteInt.h.
  64106. **
  64107. ** If P4 is NULL then all index fields have the affinity NONE.
  64108. */
  64109. case OP_MakeRecord: {
  64110. #if 0 /* local variables moved into u.aq */
  64111. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  64112. Mem *pRec; /* The new record */
  64113. u64 nData; /* Number of bytes of data space */
  64114. int nHdr; /* Number of bytes of header space */
  64115. i64 nByte; /* Data space required for this record */
  64116. int nZero; /* Number of zero bytes at the end of the record */
  64117. int nVarint; /* Number of bytes in a varint */
  64118. u32 serial_type; /* Type field */
  64119. Mem *pData0; /* First field to be combined into the record */
  64120. Mem *pLast; /* Last field of the record */
  64121. int nField; /* Number of fields in the record */
  64122. char *zAffinity; /* The affinity string for the record */
  64123. int file_format; /* File format to use for encoding */
  64124. int i; /* Space used in zNewRecord[] */
  64125. int len; /* Length of a field */
  64126. #endif /* local variables moved into u.aq */
  64127. /* Assuming the record contains N fields, the record format looks
  64128. ** like this:
  64129. **
  64130. ** ------------------------------------------------------------------------
  64131. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  64132. ** ------------------------------------------------------------------------
  64133. **
  64134. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  64135. ** and so froth.
  64136. **
  64137. ** Each type field is a varint representing the serial type of the
  64138. ** corresponding data element (see sqlite3VdbeSerialType()). The
  64139. ** hdr-size field is also a varint which is the offset from the beginning
  64140. ** of the record to data0.
  64141. */
  64142. u.aq.nData = 0; /* Number of bytes of data space */
  64143. u.aq.nHdr = 0; /* Number of bytes of header space */
  64144. u.aq.nZero = 0; /* Number of zero bytes at the end of the record */
  64145. u.aq.nField = pOp->p1;
  64146. u.aq.zAffinity = pOp->p4.z;
  64147. assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=(p->nMem-p->nCursor)+1 );
  64148. u.aq.pData0 = &aMem[u.aq.nField];
  64149. u.aq.nField = pOp->p2;
  64150. u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
  64151. u.aq.file_format = p->minWriteFileFormat;
  64152. /* Identify the output register */
  64153. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  64154. pOut = &aMem[pOp->p3];
  64155. memAboutToChange(p, pOut);
  64156. /* Loop through the elements that will make up the record to figure
  64157. ** out how much space is required for the new record.
  64158. */
  64159. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  64160. assert( memIsValid(u.aq.pRec) );
  64161. if( u.aq.zAffinity ){
  64162. applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
  64163. }
  64164. if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
  64165. sqlite3VdbeMemExpandBlob(u.aq.pRec);
  64166. }
  64167. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  64168. u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
  64169. u.aq.nData += u.aq.len;
  64170. u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
  64171. if( u.aq.pRec->flags & MEM_Zero ){
  64172. /* Only pure zero-filled BLOBs can be input to this Opcode.
  64173. ** We do not allow blobs with a prefix and a zero-filled tail. */
  64174. u.aq.nZero += u.aq.pRec->u.nZero;
  64175. }else if( u.aq.len ){
  64176. u.aq.nZero = 0;
  64177. }
  64178. }
  64179. /* Add the initial header varint and total the size */
  64180. u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
  64181. if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
  64182. u.aq.nHdr++;
  64183. }
  64184. u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
  64185. if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  64186. goto too_big;
  64187. }
  64188. /* Make sure the output register has a buffer large enough to store
  64189. ** the new record. The output register (pOp->p3) is not allowed to
  64190. ** be one of the input registers (because the following call to
  64191. ** sqlite3VdbeMemGrow() could clobber the value before it is used).
  64192. */
  64193. if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
  64194. goto no_mem;
  64195. }
  64196. u.aq.zNewRecord = (u8 *)pOut->z;
  64197. /* Write the record */
  64198. u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
  64199. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  64200. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  64201. u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type); /* serial type */
  64202. }
  64203. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){ /* serial data */
  64204. u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
  64205. }
  64206. assert( u.aq.i==u.aq.nByte );
  64207. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  64208. pOut->n = (int)u.aq.nByte;
  64209. pOut->flags = MEM_Blob | MEM_Dyn;
  64210. pOut->xDel = 0;
  64211. if( u.aq.nZero ){
  64212. pOut->u.nZero = u.aq.nZero;
  64213. pOut->flags |= MEM_Zero;
  64214. }
  64215. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  64216. REGISTER_TRACE(pOp->p3, pOut);
  64217. UPDATE_MAX_BLOBSIZE(pOut);
  64218. break;
  64219. }
  64220. /* Opcode: Count P1 P2 * * *
  64221. **
  64222. ** Store the number of entries (an integer value) in the table or index
  64223. ** opened by cursor P1 in register P2
  64224. */
  64225. #ifndef SQLITE_OMIT_BTREECOUNT
  64226. case OP_Count: { /* out2-prerelease */
  64227. #if 0 /* local variables moved into u.ar */
  64228. i64 nEntry;
  64229. BtCursor *pCrsr;
  64230. #endif /* local variables moved into u.ar */
  64231. u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
  64232. if( ALWAYS(u.ar.pCrsr) ){
  64233. rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
  64234. }else{
  64235. u.ar.nEntry = 0;
  64236. }
  64237. pOut->u.i = u.ar.nEntry;
  64238. break;
  64239. }
  64240. #endif
  64241. /* Opcode: Savepoint P1 * * P4 *
  64242. **
  64243. ** Open, release or rollback the savepoint named by parameter P4, depending
  64244. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  64245. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  64246. */
  64247. case OP_Savepoint: {
  64248. #if 0 /* local variables moved into u.as */
  64249. int p1; /* Value of P1 operand */
  64250. char *zName; /* Name of savepoint */
  64251. int nName;
  64252. Savepoint *pNew;
  64253. Savepoint *pSavepoint;
  64254. Savepoint *pTmp;
  64255. int iSavepoint;
  64256. int ii;
  64257. #endif /* local variables moved into u.as */
  64258. u.as.p1 = pOp->p1;
  64259. u.as.zName = pOp->p4.z;
  64260. /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
  64261. ** transaction, then there cannot be any savepoints.
  64262. */
  64263. assert( db->pSavepoint==0 || db->autoCommit==0 );
  64264. assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
  64265. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  64266. assert( checkSavepointCount(db) );
  64267. assert( p->bIsReader );
  64268. if( u.as.p1==SAVEPOINT_BEGIN ){
  64269. if( db->nVdbeWrite>0 ){
  64270. /* A new savepoint cannot be created if there are active write
  64271. ** statements (i.e. open read/write incremental blob handles).
  64272. */
  64273. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  64274. "SQL statements in progress");
  64275. rc = SQLITE_BUSY;
  64276. }else{
  64277. u.as.nName = sqlite3Strlen30(u.as.zName);
  64278. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64279. /* This call is Ok even if this savepoint is actually a transaction
  64280. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  64281. ** If this is a transaction savepoint being opened, it is guaranteed
  64282. ** that the db->aVTrans[] array is empty. */
  64283. assert( db->autoCommit==0 || db->nVTrans==0 );
  64284. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  64285. db->nStatement+db->nSavepoint);
  64286. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  64287. #endif
  64288. /* Create a new savepoint structure. */
  64289. u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
  64290. if( u.as.pNew ){
  64291. u.as.pNew->zName = (char *)&u.as.pNew[1];
  64292. memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
  64293. /* If there is no open transaction, then mark this as a special
  64294. ** "transaction savepoint". */
  64295. if( db->autoCommit ){
  64296. db->autoCommit = 0;
  64297. db->isTransactionSavepoint = 1;
  64298. }else{
  64299. db->nSavepoint++;
  64300. }
  64301. /* Link the new savepoint into the database handle's list. */
  64302. u.as.pNew->pNext = db->pSavepoint;
  64303. db->pSavepoint = u.as.pNew;
  64304. u.as.pNew->nDeferredCons = db->nDeferredCons;
  64305. u.as.pNew->nDeferredImmCons = db->nDeferredImmCons;
  64306. }
  64307. }
  64308. }else{
  64309. u.as.iSavepoint = 0;
  64310. /* Find the named savepoint. If there is no such savepoint, then an
  64311. ** an error is returned to the user. */
  64312. for(
  64313. u.as.pSavepoint = db->pSavepoint;
  64314. u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
  64315. u.as.pSavepoint = u.as.pSavepoint->pNext
  64316. ){
  64317. u.as.iSavepoint++;
  64318. }
  64319. if( !u.as.pSavepoint ){
  64320. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
  64321. rc = SQLITE_ERROR;
  64322. }else if( db->nVdbeWrite>0 && u.as.p1==SAVEPOINT_RELEASE ){
  64323. /* It is not possible to release (commit) a savepoint if there are
  64324. ** active write statements.
  64325. */
  64326. sqlite3SetString(&p->zErrMsg, db,
  64327. "cannot release savepoint - SQL statements in progress"
  64328. );
  64329. rc = SQLITE_BUSY;
  64330. }else{
  64331. /* Determine whether or not this is a transaction savepoint. If so,
  64332. ** and this is a RELEASE command, then the current transaction
  64333. ** is committed.
  64334. */
  64335. int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
  64336. if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
  64337. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  64338. goto vdbe_return;
  64339. }
  64340. db->autoCommit = 1;
  64341. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  64342. p->pc = pc;
  64343. db->autoCommit = 0;
  64344. p->rc = rc = SQLITE_BUSY;
  64345. goto vdbe_return;
  64346. }
  64347. db->isTransactionSavepoint = 0;
  64348. rc = p->rc;
  64349. }else{
  64350. u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
  64351. if( u.as.p1==SAVEPOINT_ROLLBACK ){
  64352. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  64353. sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
  64354. }
  64355. }
  64356. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  64357. rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
  64358. if( rc!=SQLITE_OK ){
  64359. goto abort_due_to_error;
  64360. }
  64361. }
  64362. if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
  64363. sqlite3ExpirePreparedStatements(db);
  64364. sqlite3ResetAllSchemasOfConnection(db);
  64365. db->flags = (db->flags | SQLITE_InternChanges);
  64366. }
  64367. }
  64368. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  64369. ** savepoints nested inside of the savepoint being operated on. */
  64370. while( db->pSavepoint!=u.as.pSavepoint ){
  64371. u.as.pTmp = db->pSavepoint;
  64372. db->pSavepoint = u.as.pTmp->pNext;
  64373. sqlite3DbFree(db, u.as.pTmp);
  64374. db->nSavepoint--;
  64375. }
  64376. /* If it is a RELEASE, then destroy the savepoint being operated on
  64377. ** too. If it is a ROLLBACK TO, then set the number of deferred
  64378. ** constraint violations present in the database to the value stored
  64379. ** when the savepoint was created. */
  64380. if( u.as.p1==SAVEPOINT_RELEASE ){
  64381. assert( u.as.pSavepoint==db->pSavepoint );
  64382. db->pSavepoint = u.as.pSavepoint->pNext;
  64383. sqlite3DbFree(db, u.as.pSavepoint);
  64384. if( !isTransaction ){
  64385. db->nSavepoint--;
  64386. }
  64387. }else{
  64388. db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
  64389. db->nDeferredImmCons = u.as.pSavepoint->nDeferredImmCons;
  64390. }
  64391. if( !isTransaction ){
  64392. rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
  64393. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  64394. }
  64395. }
  64396. }
  64397. break;
  64398. }
  64399. /* Opcode: AutoCommit P1 P2 * * *
  64400. **
  64401. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  64402. ** back any currently active btree transactions. If there are any active
  64403. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  64404. ** there are active writing VMs or active VMs that use shared cache.
  64405. **
  64406. ** This instruction causes the VM to halt.
  64407. */
  64408. case OP_AutoCommit: {
  64409. #if 0 /* local variables moved into u.at */
  64410. int desiredAutoCommit;
  64411. int iRollback;
  64412. int turnOnAC;
  64413. #endif /* local variables moved into u.at */
  64414. u.at.desiredAutoCommit = pOp->p1;
  64415. u.at.iRollback = pOp->p2;
  64416. u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
  64417. assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
  64418. assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
  64419. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  64420. assert( p->bIsReader );
  64421. #if 0
  64422. if( u.at.turnOnAC && u.at.iRollback && db->nVdbeActive>1 ){
  64423. /* If this instruction implements a ROLLBACK and other VMs are
  64424. ** still running, and a transaction is active, return an error indicating
  64425. ** that the other VMs must complete first.
  64426. */
  64427. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  64428. "SQL statements in progress");
  64429. rc = SQLITE_BUSY;
  64430. }else
  64431. #endif
  64432. if( u.at.turnOnAC && !u.at.iRollback && db->nVdbeWrite>0 ){
  64433. /* If this instruction implements a COMMIT and other VMs are writing
  64434. ** return an error indicating that the other VMs must complete first.
  64435. */
  64436. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  64437. "SQL statements in progress");
  64438. rc = SQLITE_BUSY;
  64439. }else if( u.at.desiredAutoCommit!=db->autoCommit ){
  64440. if( u.at.iRollback ){
  64441. assert( u.at.desiredAutoCommit==1 );
  64442. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  64443. db->autoCommit = 1;
  64444. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  64445. goto vdbe_return;
  64446. }else{
  64447. db->autoCommit = (u8)u.at.desiredAutoCommit;
  64448. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  64449. p->pc = pc;
  64450. db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
  64451. p->rc = rc = SQLITE_BUSY;
  64452. goto vdbe_return;
  64453. }
  64454. }
  64455. assert( db->nStatement==0 );
  64456. sqlite3CloseSavepoints(db);
  64457. if( p->rc==SQLITE_OK ){
  64458. rc = SQLITE_DONE;
  64459. }else{
  64460. rc = SQLITE_ERROR;
  64461. }
  64462. goto vdbe_return;
  64463. }else{
  64464. sqlite3SetString(&p->zErrMsg, db,
  64465. (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
  64466. (u.at.iRollback)?"cannot rollback - no transaction is active":
  64467. "cannot commit - no transaction is active"));
  64468. rc = SQLITE_ERROR;
  64469. }
  64470. break;
  64471. }
  64472. /* Opcode: Transaction P1 P2 * * *
  64473. **
  64474. ** Begin a transaction. The transaction ends when a Commit or Rollback
  64475. ** opcode is encountered. Depending on the ON CONFLICT setting, the
  64476. ** transaction might also be rolled back if an error is encountered.
  64477. **
  64478. ** P1 is the index of the database file on which the transaction is
  64479. ** started. Index 0 is the main database file and index 1 is the
  64480. ** file used for temporary tables. Indices of 2 or more are used for
  64481. ** attached databases.
  64482. **
  64483. ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
  64484. ** obtained on the database file when a write-transaction is started. No
  64485. ** other process can start another write transaction while this transaction is
  64486. ** underway. Starting a write transaction also creates a rollback journal. A
  64487. ** write transaction must be started before any changes can be made to the
  64488. ** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
  64489. ** also obtained on the file.
  64490. **
  64491. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  64492. ** true (this flag is set if the Vdbe may modify more than one row and may
  64493. ** throw an ABORT exception), a statement transaction may also be opened.
  64494. ** More specifically, a statement transaction is opened iff the database
  64495. ** connection is currently not in autocommit mode, or if there are other
  64496. ** active statements. A statement transaction allows the changes made by this
  64497. ** VDBE to be rolled back after an error without having to roll back the
  64498. ** entire transaction. If no error is encountered, the statement transaction
  64499. ** will automatically commit when the VDBE halts.
  64500. **
  64501. ** If P2 is zero, then a read-lock is obtained on the database file.
  64502. */
  64503. case OP_Transaction: {
  64504. #if 0 /* local variables moved into u.au */
  64505. Btree *pBt;
  64506. #endif /* local variables moved into u.au */
  64507. assert( p->bIsReader );
  64508. assert( p->readOnly==0 || pOp->p2==0 );
  64509. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  64510. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  64511. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  64512. rc = SQLITE_READONLY;
  64513. goto abort_due_to_error;
  64514. }
  64515. u.au.pBt = db->aDb[pOp->p1].pBt;
  64516. if( u.au.pBt ){
  64517. rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
  64518. if( rc==SQLITE_BUSY ){
  64519. p->pc = pc;
  64520. p->rc = rc = SQLITE_BUSY;
  64521. goto vdbe_return;
  64522. }
  64523. if( rc!=SQLITE_OK ){
  64524. goto abort_due_to_error;
  64525. }
  64526. if( pOp->p2 && p->usesStmtJournal
  64527. && (db->autoCommit==0 || db->nVdbeRead>1)
  64528. ){
  64529. assert( sqlite3BtreeIsInTrans(u.au.pBt) );
  64530. if( p->iStatement==0 ){
  64531. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  64532. db->nStatement++;
  64533. p->iStatement = db->nSavepoint + db->nStatement;
  64534. }
  64535. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  64536. if( rc==SQLITE_OK ){
  64537. rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
  64538. }
  64539. /* Store the current value of the database handles deferred constraint
  64540. ** counter. If the statement transaction needs to be rolled back,
  64541. ** the value of this counter needs to be restored too. */
  64542. p->nStmtDefCons = db->nDeferredCons;
  64543. p->nStmtDefImmCons = db->nDeferredImmCons;
  64544. }
  64545. }
  64546. break;
  64547. }
  64548. /* Opcode: ReadCookie P1 P2 P3 * *
  64549. **
  64550. ** Read cookie number P3 from database P1 and write it into register P2.
  64551. ** P3==1 is the schema version. P3==2 is the database format.
  64552. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  64553. ** the main database file and P1==1 is the database file used to store
  64554. ** temporary tables.
  64555. **
  64556. ** There must be a read-lock on the database (either a transaction
  64557. ** must be started or there must be an open cursor) before
  64558. ** executing this instruction.
  64559. */
  64560. case OP_ReadCookie: { /* out2-prerelease */
  64561. #if 0 /* local variables moved into u.av */
  64562. int iMeta;
  64563. int iDb;
  64564. int iCookie;
  64565. #endif /* local variables moved into u.av */
  64566. assert( p->bIsReader );
  64567. u.av.iDb = pOp->p1;
  64568. u.av.iCookie = pOp->p3;
  64569. assert( pOp->p3<SQLITE_N_BTREE_META );
  64570. assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
  64571. assert( db->aDb[u.av.iDb].pBt!=0 );
  64572. assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
  64573. sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
  64574. pOut->u.i = u.av.iMeta;
  64575. break;
  64576. }
  64577. /* Opcode: SetCookie P1 P2 P3 * *
  64578. **
  64579. ** Write the content of register P3 (interpreted as an integer)
  64580. ** into cookie number P2 of database P1. P2==1 is the schema version.
  64581. ** P2==2 is the database format. P2==3 is the recommended pager cache
  64582. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  64583. ** database file used to store temporary tables.
  64584. **
  64585. ** A transaction must be started before executing this opcode.
  64586. */
  64587. case OP_SetCookie: { /* in3 */
  64588. #if 0 /* local variables moved into u.aw */
  64589. Db *pDb;
  64590. #endif /* local variables moved into u.aw */
  64591. assert( pOp->p2<SQLITE_N_BTREE_META );
  64592. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  64593. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  64594. assert( p->readOnly==0 );
  64595. u.aw.pDb = &db->aDb[pOp->p1];
  64596. assert( u.aw.pDb->pBt!=0 );
  64597. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  64598. pIn3 = &aMem[pOp->p3];
  64599. sqlite3VdbeMemIntegerify(pIn3);
  64600. /* See note about index shifting on OP_ReadCookie */
  64601. rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
  64602. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  64603. /* When the schema cookie changes, record the new cookie internally */
  64604. u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  64605. db->flags |= SQLITE_InternChanges;
  64606. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  64607. /* Record changes in the file format */
  64608. u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
  64609. }
  64610. if( pOp->p1==1 ){
  64611. /* Invalidate all prepared statements whenever the TEMP database
  64612. ** schema is changed. Ticket #1644 */
  64613. sqlite3ExpirePreparedStatements(db);
  64614. p->expired = 0;
  64615. }
  64616. break;
  64617. }
  64618. /* Opcode: VerifyCookie P1 P2 P3 * *
  64619. **
  64620. ** Check the value of global database parameter number 0 (the
  64621. ** schema version) and make sure it is equal to P2 and that the
  64622. ** generation counter on the local schema parse equals P3.
  64623. **
  64624. ** P1 is the database number which is 0 for the main database file
  64625. ** and 1 for the file holding temporary tables and some higher number
  64626. ** for auxiliary databases.
  64627. **
  64628. ** The cookie changes its value whenever the database schema changes.
  64629. ** This operation is used to detect when that the cookie has changed
  64630. ** and that the current process needs to reread the schema.
  64631. **
  64632. ** Either a transaction needs to have been started or an OP_Open needs
  64633. ** to be executed (to establish a read lock) before this opcode is
  64634. ** invoked.
  64635. */
  64636. case OP_VerifyCookie: {
  64637. #if 0 /* local variables moved into u.ax */
  64638. int iMeta;
  64639. int iGen;
  64640. Btree *pBt;
  64641. #endif /* local variables moved into u.ax */
  64642. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  64643. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  64644. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  64645. assert( p->bIsReader );
  64646. u.ax.pBt = db->aDb[pOp->p1].pBt;
  64647. if( u.ax.pBt ){
  64648. sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
  64649. u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  64650. }else{
  64651. u.ax.iGen = u.ax.iMeta = 0;
  64652. }
  64653. if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
  64654. sqlite3DbFree(db, p->zErrMsg);
  64655. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  64656. /* If the schema-cookie from the database file matches the cookie
  64657. ** stored with the in-memory representation of the schema, do
  64658. ** not reload the schema from the database file.
  64659. **
  64660. ** If virtual-tables are in use, this is not just an optimization.
  64661. ** Often, v-tables store their data in other SQLite tables, which
  64662. ** are queried from within xNext() and other v-table methods using
  64663. ** prepared queries. If such a query is out-of-date, we do not want to
  64664. ** discard the database schema, as the user code implementing the
  64665. ** v-table would have to be ready for the sqlite3_vtab structure itself
  64666. ** to be invalidated whenever sqlite3_step() is called from within
  64667. ** a v-table method.
  64668. */
  64669. if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
  64670. sqlite3ResetOneSchema(db, pOp->p1);
  64671. }
  64672. p->expired = 1;
  64673. rc = SQLITE_SCHEMA;
  64674. }
  64675. break;
  64676. }
  64677. /* Opcode: OpenRead P1 P2 P3 P4 P5
  64678. **
  64679. ** Open a read-only cursor for the database table whose root page is
  64680. ** P2 in a database file. The database file is determined by P3.
  64681. ** P3==0 means the main database, P3==1 means the database used for
  64682. ** temporary tables, and P3>1 means used the corresponding attached
  64683. ** database. Give the new cursor an identifier of P1. The P1
  64684. ** values need not be contiguous but all P1 values should be small integers.
  64685. ** It is an error for P1 to be negative.
  64686. **
  64687. ** If P5!=0 then use the content of register P2 as the root page, not
  64688. ** the value of P2 itself.
  64689. **
  64690. ** There will be a read lock on the database whenever there is an
  64691. ** open cursor. If the database was unlocked prior to this instruction
  64692. ** then a read lock is acquired as part of this instruction. A read
  64693. ** lock allows other processes to read the database but prohibits
  64694. ** any other process from modifying the database. The read lock is
  64695. ** released when all cursors are closed. If this instruction attempts
  64696. ** to get a read lock but fails, the script terminates with an
  64697. ** SQLITE_BUSY error code.
  64698. **
  64699. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  64700. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  64701. ** structure, then said structure defines the content and collating
  64702. ** sequence of the index being opened. Otherwise, if P4 is an integer
  64703. ** value, it is set to the number of columns in the table.
  64704. **
  64705. ** See also OpenWrite.
  64706. */
  64707. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  64708. **
  64709. ** Open a read/write cursor named P1 on the table or index whose root
  64710. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  64711. ** root page.
  64712. **
  64713. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  64714. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  64715. ** structure, then said structure defines the content and collating
  64716. ** sequence of the index being opened. Otherwise, if P4 is an integer
  64717. ** value, it is set to the number of columns in the table, or to the
  64718. ** largest index of any column of the table that is actually used.
  64719. **
  64720. ** This instruction works just like OpenRead except that it opens the cursor
  64721. ** in read/write mode. For a given table, there can be one or more read-only
  64722. ** cursors or a single read/write cursor but not both.
  64723. **
  64724. ** See also OpenRead.
  64725. */
  64726. case OP_OpenRead:
  64727. case OP_OpenWrite: {
  64728. #if 0 /* local variables moved into u.ay */
  64729. int nField;
  64730. KeyInfo *pKeyInfo;
  64731. int p2;
  64732. int iDb;
  64733. int wrFlag;
  64734. Btree *pX;
  64735. VdbeCursor *pCur;
  64736. Db *pDb;
  64737. #endif /* local variables moved into u.ay */
  64738. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
  64739. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
  64740. assert( p->bIsReader );
  64741. assert( pOp->opcode==OP_OpenRead || p->readOnly==0 );
  64742. if( p->expired ){
  64743. rc = SQLITE_ABORT;
  64744. break;
  64745. }
  64746. u.ay.nField = 0;
  64747. u.ay.pKeyInfo = 0;
  64748. u.ay.p2 = pOp->p2;
  64749. u.ay.iDb = pOp->p3;
  64750. assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
  64751. assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
  64752. u.ay.pDb = &db->aDb[u.ay.iDb];
  64753. u.ay.pX = u.ay.pDb->pBt;
  64754. assert( u.ay.pX!=0 );
  64755. if( pOp->opcode==OP_OpenWrite ){
  64756. u.ay.wrFlag = 1;
  64757. assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
  64758. if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
  64759. p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
  64760. }
  64761. }else{
  64762. u.ay.wrFlag = 0;
  64763. }
  64764. if( pOp->p5 & OPFLAG_P2ISREG ){
  64765. assert( u.ay.p2>0 );
  64766. assert( u.ay.p2<=(p->nMem-p->nCursor) );
  64767. pIn2 = &aMem[u.ay.p2];
  64768. assert( memIsValid(pIn2) );
  64769. assert( (pIn2->flags & MEM_Int)!=0 );
  64770. sqlite3VdbeMemIntegerify(pIn2);
  64771. u.ay.p2 = (int)pIn2->u.i;
  64772. /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
  64773. ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
  64774. ** If there were a failure, the prepared statement would have halted
  64775. ** before reaching this instruction. */
  64776. if( NEVER(u.ay.p2<2) ) {
  64777. rc = SQLITE_CORRUPT_BKPT;
  64778. goto abort_due_to_error;
  64779. }
  64780. }
  64781. if( pOp->p4type==P4_KEYINFO ){
  64782. u.ay.pKeyInfo = pOp->p4.pKeyInfo;
  64783. u.ay.pKeyInfo->enc = ENC(p->db);
  64784. u.ay.nField = u.ay.pKeyInfo->nField+1;
  64785. }else if( pOp->p4type==P4_INT32 ){
  64786. u.ay.nField = pOp->p4.i;
  64787. }
  64788. assert( pOp->p1>=0 );
  64789. u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
  64790. if( u.ay.pCur==0 ) goto no_mem;
  64791. u.ay.pCur->nullRow = 1;
  64792. u.ay.pCur->isOrdered = 1;
  64793. rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
  64794. u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
  64795. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  64796. sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
  64797. /* Since it performs no memory allocation or IO, the only value that
  64798. ** sqlite3BtreeCursor() may return is SQLITE_OK. */
  64799. assert( rc==SQLITE_OK );
  64800. /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
  64801. ** SQLite used to check if the root-page flags were sane at this point
  64802. ** and report database corruption if they were not, but this check has
  64803. ** since moved into the btree layer. */
  64804. u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
  64805. u.ay.pCur->isIndex = !u.ay.pCur->isTable;
  64806. break;
  64807. }
  64808. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  64809. **
  64810. ** Open a new cursor P1 to a transient table.
  64811. ** The cursor is always opened read/write even if
  64812. ** the main database is read-only. The ephemeral
  64813. ** table is deleted automatically when the cursor is closed.
  64814. **
  64815. ** P2 is the number of columns in the ephemeral table.
  64816. ** The cursor points to a BTree table if P4==0 and to a BTree index
  64817. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  64818. ** that defines the format of keys in the index.
  64819. **
  64820. ** This opcode was once called OpenTemp. But that created
  64821. ** confusion because the term "temp table", might refer either
  64822. ** to a TEMP table at the SQL level, or to a table opened by
  64823. ** this opcode. Then this opcode was call OpenVirtual. But
  64824. ** that created confusion with the whole virtual-table idea.
  64825. **
  64826. ** The P5 parameter can be a mask of the BTREE_* flags defined
  64827. ** in btree.h. These flags control aspects of the operation of
  64828. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  64829. ** added automatically.
  64830. */
  64831. /* Opcode: OpenAutoindex P1 P2 * P4 *
  64832. **
  64833. ** This opcode works the same as OP_OpenEphemeral. It has a
  64834. ** different name to distinguish its use. Tables created using
  64835. ** by this opcode will be used for automatically created transient
  64836. ** indices in joins.
  64837. */
  64838. case OP_OpenAutoindex:
  64839. case OP_OpenEphemeral: {
  64840. #if 0 /* local variables moved into u.az */
  64841. VdbeCursor *pCx;
  64842. #endif /* local variables moved into u.az */
  64843. static const int vfsFlags =
  64844. SQLITE_OPEN_READWRITE |
  64845. SQLITE_OPEN_CREATE |
  64846. SQLITE_OPEN_EXCLUSIVE |
  64847. SQLITE_OPEN_DELETEONCLOSE |
  64848. SQLITE_OPEN_TRANSIENT_DB;
  64849. assert( pOp->p1>=0 );
  64850. u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  64851. if( u.az.pCx==0 ) goto no_mem;
  64852. u.az.pCx->nullRow = 1;
  64853. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
  64854. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  64855. if( rc==SQLITE_OK ){
  64856. rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
  64857. }
  64858. if( rc==SQLITE_OK ){
  64859. /* If a transient index is required, create it by calling
  64860. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  64861. ** opening it. If a transient table is required, just use the
  64862. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  64863. */
  64864. if( pOp->p4.pKeyInfo ){
  64865. int pgno;
  64866. assert( pOp->p4type==P4_KEYINFO );
  64867. rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  64868. if( rc==SQLITE_OK ){
  64869. assert( pgno==MASTER_ROOT+1 );
  64870. rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
  64871. (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
  64872. u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  64873. u.az.pCx->pKeyInfo->enc = ENC(p->db);
  64874. }
  64875. u.az.pCx->isTable = 0;
  64876. }else{
  64877. rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
  64878. u.az.pCx->isTable = 1;
  64879. }
  64880. }
  64881. u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  64882. u.az.pCx->isIndex = !u.az.pCx->isTable;
  64883. break;
  64884. }
  64885. /* Opcode: SorterOpen P1 P2 * P4 *
  64886. **
  64887. ** This opcode works like OP_OpenEphemeral except that it opens
  64888. ** a transient index that is specifically designed to sort large
  64889. ** tables using an external merge-sort algorithm.
  64890. */
  64891. case OP_SorterOpen: {
  64892. #if 0 /* local variables moved into u.ba */
  64893. VdbeCursor *pCx;
  64894. #endif /* local variables moved into u.ba */
  64895. u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  64896. if( u.ba.pCx==0 ) goto no_mem;
  64897. u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  64898. u.ba.pCx->pKeyInfo->enc = ENC(p->db);
  64899. u.ba.pCx->isSorter = 1;
  64900. rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
  64901. break;
  64902. }
  64903. /* Opcode: OpenPseudo P1 P2 P3 * P5
  64904. **
  64905. ** Open a new cursor that points to a fake table that contains a single
  64906. ** row of data. The content of that one row in the content of memory
  64907. ** register P2 when P5==0. In other words, cursor P1 becomes an alias for the
  64908. ** MEM_Blob content contained in register P2. When P5==1, then the
  64909. ** row is represented by P3 consecutive registers beginning with P2.
  64910. **
  64911. ** A pseudo-table created by this opcode is used to hold a single
  64912. ** row output from the sorter so that the row can be decomposed into
  64913. ** individual columns using the OP_Column opcode. The OP_Column opcode
  64914. ** is the only cursor opcode that works with a pseudo-table.
  64915. **
  64916. ** P3 is the number of fields in the records that will be stored by
  64917. ** the pseudo-table.
  64918. */
  64919. case OP_OpenPseudo: {
  64920. #if 0 /* local variables moved into u.bb */
  64921. VdbeCursor *pCx;
  64922. #endif /* local variables moved into u.bb */
  64923. assert( pOp->p1>=0 );
  64924. u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  64925. if( u.bb.pCx==0 ) goto no_mem;
  64926. u.bb.pCx->nullRow = 1;
  64927. u.bb.pCx->pseudoTableReg = pOp->p2;
  64928. u.bb.pCx->isTable = 1;
  64929. u.bb.pCx->isIndex = 0;
  64930. u.bb.pCx->multiPseudo = pOp->p5;
  64931. break;
  64932. }
  64933. /* Opcode: Close P1 * * * *
  64934. **
  64935. ** Close a cursor previously opened as P1. If P1 is not
  64936. ** currently open, this instruction is a no-op.
  64937. */
  64938. case OP_Close: {
  64939. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64940. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  64941. p->apCsr[pOp->p1] = 0;
  64942. break;
  64943. }
  64944. /* Opcode: SeekGe P1 P2 P3 P4 *
  64945. **
  64946. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  64947. ** use the value in register P3 as the key. If cursor P1 refers
  64948. ** to an SQL index, then P3 is the first in an array of P4 registers
  64949. ** that are used as an unpacked index key.
  64950. **
  64951. ** Reposition cursor P1 so that it points to the smallest entry that
  64952. ** is greater than or equal to the key value. If there are no records
  64953. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  64954. **
  64955. ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
  64956. */
  64957. /* Opcode: SeekGt P1 P2 P3 P4 *
  64958. **
  64959. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  64960. ** use the value in register P3 as a key. If cursor P1 refers
  64961. ** to an SQL index, then P3 is the first in an array of P4 registers
  64962. ** that are used as an unpacked index key.
  64963. **
  64964. ** Reposition cursor P1 so that it points to the smallest entry that
  64965. ** is greater than the key value. If there are no records greater than
  64966. ** the key and P2 is not zero, then jump to P2.
  64967. **
  64968. ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
  64969. */
  64970. /* Opcode: SeekLt P1 P2 P3 P4 *
  64971. **
  64972. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  64973. ** use the value in register P3 as a key. If cursor P1 refers
  64974. ** to an SQL index, then P3 is the first in an array of P4 registers
  64975. ** that are used as an unpacked index key.
  64976. **
  64977. ** Reposition cursor P1 so that it points to the largest entry that
  64978. ** is less than the key value. If there are no records less than
  64979. ** the key and P2 is not zero, then jump to P2.
  64980. **
  64981. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
  64982. */
  64983. /* Opcode: SeekLe P1 P2 P3 P4 *
  64984. **
  64985. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  64986. ** use the value in register P3 as a key. If cursor P1 refers
  64987. ** to an SQL index, then P3 is the first in an array of P4 registers
  64988. ** that are used as an unpacked index key.
  64989. **
  64990. ** Reposition cursor P1 so that it points to the largest entry that
  64991. ** is less than or equal to the key value. If there are no records
  64992. ** less than or equal to the key and P2 is not zero, then jump to P2.
  64993. **
  64994. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
  64995. */
  64996. case OP_SeekLt: /* jump, in3 */
  64997. case OP_SeekLe: /* jump, in3 */
  64998. case OP_SeekGe: /* jump, in3 */
  64999. case OP_SeekGt: { /* jump, in3 */
  65000. #if 0 /* local variables moved into u.bc */
  65001. int res;
  65002. int oc;
  65003. VdbeCursor *pC;
  65004. UnpackedRecord r;
  65005. int nField;
  65006. i64 iKey; /* The rowid we are to seek to */
  65007. #endif /* local variables moved into u.bc */
  65008. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65009. assert( pOp->p2!=0 );
  65010. u.bc.pC = p->apCsr[pOp->p1];
  65011. assert( u.bc.pC!=0 );
  65012. assert( u.bc.pC->pseudoTableReg==0 );
  65013. assert( OP_SeekLe == OP_SeekLt+1 );
  65014. assert( OP_SeekGe == OP_SeekLt+2 );
  65015. assert( OP_SeekGt == OP_SeekLt+3 );
  65016. assert( u.bc.pC->isOrdered );
  65017. if( ALWAYS(u.bc.pC->pCursor!=0) ){
  65018. u.bc.oc = pOp->opcode;
  65019. u.bc.pC->nullRow = 0;
  65020. if( u.bc.pC->isTable ){
  65021. /* The input value in P3 might be of any type: integer, real, string,
  65022. ** blob, or NULL. But it needs to be an integer before we can do
  65023. ** the seek, so covert it. */
  65024. pIn3 = &aMem[pOp->p3];
  65025. applyNumericAffinity(pIn3);
  65026. u.bc.iKey = sqlite3VdbeIntValue(pIn3);
  65027. u.bc.pC->rowidIsValid = 0;
  65028. /* If the P3 value could not be converted into an integer without
  65029. ** loss of information, then special processing is required... */
  65030. if( (pIn3->flags & MEM_Int)==0 ){
  65031. if( (pIn3->flags & MEM_Real)==0 ){
  65032. /* If the P3 value cannot be converted into any kind of a number,
  65033. ** then the seek is not possible, so jump to P2 */
  65034. pc = pOp->p2 - 1;
  65035. break;
  65036. }
  65037. /* If we reach this point, then the P3 value must be a floating
  65038. ** point number. */
  65039. assert( (pIn3->flags & MEM_Real)!=0 );
  65040. if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
  65041. /* The P3 value is too large in magnitude to be expressed as an
  65042. ** integer. */
  65043. u.bc.res = 1;
  65044. if( pIn3->r<0 ){
  65045. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  65046. rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
  65047. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  65048. }
  65049. }else{
  65050. if( u.bc.oc<=OP_SeekLe ){ assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  65051. rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
  65052. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  65053. }
  65054. }
  65055. if( u.bc.res ){
  65056. pc = pOp->p2 - 1;
  65057. }
  65058. break;
  65059. }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
  65060. /* Use the ceiling() function to convert real->int */
  65061. if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
  65062. }else{
  65063. /* Use the floor() function to convert real->int */
  65064. assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
  65065. if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
  65066. }
  65067. }
  65068. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
  65069. if( rc!=SQLITE_OK ){
  65070. goto abort_due_to_error;
  65071. }
  65072. if( u.bc.res==0 ){
  65073. u.bc.pC->rowidIsValid = 1;
  65074. u.bc.pC->lastRowid = u.bc.iKey;
  65075. }
  65076. }else{
  65077. u.bc.nField = pOp->p4.i;
  65078. assert( pOp->p4type==P4_INT32 );
  65079. assert( u.bc.nField>0 );
  65080. u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
  65081. u.bc.r.nField = (u16)u.bc.nField;
  65082. /* The next line of code computes as follows, only faster:
  65083. ** if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
  65084. ** u.bc.r.flags = UNPACKED_INCRKEY;
  65085. ** }else{
  65086. ** u.bc.r.flags = 0;
  65087. ** }
  65088. */
  65089. u.bc.r.flags = (u8)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
  65090. assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
  65091. assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
  65092. assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
  65093. assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
  65094. u.bc.r.aMem = &aMem[pOp->p3];
  65095. #ifdef SQLITE_DEBUG
  65096. { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
  65097. #endif
  65098. ExpandBlob(u.bc.r.aMem);
  65099. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
  65100. if( rc!=SQLITE_OK ){
  65101. goto abort_due_to_error;
  65102. }
  65103. u.bc.pC->rowidIsValid = 0;
  65104. }
  65105. u.bc.pC->deferredMoveto = 0;
  65106. u.bc.pC->cacheStatus = CACHE_STALE;
  65107. #ifdef SQLITE_TEST
  65108. sqlite3_search_count++;
  65109. #endif
  65110. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  65111. if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
  65112. rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
  65113. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  65114. u.bc.pC->rowidIsValid = 0;
  65115. }else{
  65116. u.bc.res = 0;
  65117. }
  65118. }else{
  65119. assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  65120. if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
  65121. rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
  65122. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  65123. u.bc.pC->rowidIsValid = 0;
  65124. }else{
  65125. /* u.bc.res might be negative because the table is empty. Check to
  65126. ** see if this is the case.
  65127. */
  65128. u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
  65129. }
  65130. }
  65131. assert( pOp->p2>0 );
  65132. if( u.bc.res ){
  65133. pc = pOp->p2 - 1;
  65134. }
  65135. }else{
  65136. /* This happens when attempting to open the sqlite3_master table
  65137. ** for read access returns SQLITE_EMPTY. In this case always
  65138. ** take the jump (since there are no records in the table).
  65139. */
  65140. pc = pOp->p2 - 1;
  65141. }
  65142. break;
  65143. }
  65144. /* Opcode: Seek P1 P2 * * *
  65145. **
  65146. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  65147. ** for P1 to move so that it points to the rowid given by P2.
  65148. **
  65149. ** This is actually a deferred seek. Nothing actually happens until
  65150. ** the cursor is used to read a record. That way, if no reads
  65151. ** occur, no unnecessary I/O happens.
  65152. */
  65153. case OP_Seek: { /* in2 */
  65154. #if 0 /* local variables moved into u.bd */
  65155. VdbeCursor *pC;
  65156. #endif /* local variables moved into u.bd */
  65157. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65158. u.bd.pC = p->apCsr[pOp->p1];
  65159. assert( u.bd.pC!=0 );
  65160. if( ALWAYS(u.bd.pC->pCursor!=0) ){
  65161. assert( u.bd.pC->isTable );
  65162. u.bd.pC->nullRow = 0;
  65163. pIn2 = &aMem[pOp->p2];
  65164. u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  65165. u.bd.pC->rowidIsValid = 0;
  65166. u.bd.pC->deferredMoveto = 1;
  65167. }
  65168. break;
  65169. }
  65170. /* Opcode: Found P1 P2 P3 P4 *
  65171. **
  65172. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  65173. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  65174. ** record.
  65175. **
  65176. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  65177. ** is a prefix of any entry in P1 then a jump is made to P2 and
  65178. ** P1 is left pointing at the matching entry.
  65179. */
  65180. /* Opcode: NotFound P1 P2 P3 P4 *
  65181. **
  65182. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  65183. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  65184. ** record.
  65185. **
  65186. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  65187. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  65188. ** does contain an entry whose prefix matches the P3/P4 record then control
  65189. ** falls through to the next instruction and P1 is left pointing at the
  65190. ** matching entry.
  65191. **
  65192. ** See also: Found, NotExists, IsUnique
  65193. */
  65194. case OP_NotFound: /* jump, in3 */
  65195. case OP_Found: { /* jump, in3 */
  65196. #if 0 /* local variables moved into u.be */
  65197. int alreadyExists;
  65198. VdbeCursor *pC;
  65199. int res;
  65200. char *pFree;
  65201. UnpackedRecord *pIdxKey;
  65202. UnpackedRecord r;
  65203. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  65204. #endif /* local variables moved into u.be */
  65205. #ifdef SQLITE_TEST
  65206. sqlite3_found_count++;
  65207. #endif
  65208. u.be.alreadyExists = 0;
  65209. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65210. assert( pOp->p4type==P4_INT32 );
  65211. u.be.pC = p->apCsr[pOp->p1];
  65212. assert( u.be.pC!=0 );
  65213. pIn3 = &aMem[pOp->p3];
  65214. if( ALWAYS(u.be.pC->pCursor!=0) ){
  65215. assert( u.be.pC->isTable==0 );
  65216. if( pOp->p4.i>0 ){
  65217. u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
  65218. u.be.r.nField = (u16)pOp->p4.i;
  65219. u.be.r.aMem = pIn3;
  65220. #ifdef SQLITE_DEBUG
  65221. { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
  65222. #endif
  65223. u.be.r.flags = UNPACKED_PREFIX_MATCH;
  65224. u.be.pIdxKey = &u.be.r;
  65225. }else{
  65226. u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  65227. u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
  65228. );
  65229. if( u.be.pIdxKey==0 ) goto no_mem;
  65230. assert( pIn3->flags & MEM_Blob );
  65231. assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
  65232. sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
  65233. u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
  65234. }
  65235. rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
  65236. if( pOp->p4.i==0 ){
  65237. sqlite3DbFree(db, u.be.pFree);
  65238. }
  65239. if( rc!=SQLITE_OK ){
  65240. break;
  65241. }
  65242. u.be.alreadyExists = (u.be.res==0);
  65243. u.be.pC->deferredMoveto = 0;
  65244. u.be.pC->cacheStatus = CACHE_STALE;
  65245. }
  65246. if( pOp->opcode==OP_Found ){
  65247. if( u.be.alreadyExists ) pc = pOp->p2 - 1;
  65248. }else{
  65249. if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
  65250. }
  65251. break;
  65252. }
  65253. /* Opcode: IsUnique P1 P2 P3 P4 *
  65254. **
  65255. ** Cursor P1 is open on an index b-tree - that is to say, a btree which
  65256. ** no data and where the key are records generated by OP_MakeRecord with
  65257. ** the list field being the integer ROWID of the entry that the index
  65258. ** entry refers to.
  65259. **
  65260. ** The P3 register contains an integer record number. Call this record
  65261. ** number R. Register P4 is the first in a set of N contiguous registers
  65262. ** that make up an unpacked index key that can be used with cursor P1.
  65263. ** The value of N can be inferred from the cursor. N includes the rowid
  65264. ** value appended to the end of the index record. This rowid value may
  65265. ** or may not be the same as R.
  65266. **
  65267. ** If any of the N registers beginning with register P4 contains a NULL
  65268. ** value, jump immediately to P2.
  65269. **
  65270. ** Otherwise, this instruction checks if cursor P1 contains an entry
  65271. ** where the first (N-1) fields match but the rowid value at the end
  65272. ** of the index entry is not R. If there is no such entry, control jumps
  65273. ** to instruction P2. Otherwise, the rowid of the conflicting index
  65274. ** entry is copied to register P3 and control falls through to the next
  65275. ** instruction.
  65276. **
  65277. ** See also: NotFound, NotExists, Found
  65278. */
  65279. case OP_IsUnique: { /* jump, in3 */
  65280. #if 0 /* local variables moved into u.bf */
  65281. u16 ii;
  65282. VdbeCursor *pCx;
  65283. BtCursor *pCrsr;
  65284. u16 nField;
  65285. Mem *aMx;
  65286. UnpackedRecord r; /* B-Tree index search key */
  65287. i64 R; /* Rowid stored in register P3 */
  65288. #endif /* local variables moved into u.bf */
  65289. pIn3 = &aMem[pOp->p3];
  65290. u.bf.aMx = &aMem[pOp->p4.i];
  65291. /* Assert that the values of parameters P1 and P4 are in range. */
  65292. assert( pOp->p4type==P4_INT32 );
  65293. assert( pOp->p4.i>0 && pOp->p4.i<=(p->nMem-p->nCursor) );
  65294. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65295. /* Find the index cursor. */
  65296. u.bf.pCx = p->apCsr[pOp->p1];
  65297. assert( u.bf.pCx->deferredMoveto==0 );
  65298. u.bf.pCx->seekResult = 0;
  65299. u.bf.pCx->cacheStatus = CACHE_STALE;
  65300. u.bf.pCrsr = u.bf.pCx->pCursor;
  65301. /* If any of the values are NULL, take the jump. */
  65302. u.bf.nField = u.bf.pCx->pKeyInfo->nField;
  65303. for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
  65304. if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
  65305. pc = pOp->p2 - 1;
  65306. u.bf.pCrsr = 0;
  65307. break;
  65308. }
  65309. }
  65310. assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
  65311. if( u.bf.pCrsr!=0 ){
  65312. /* Populate the index search key. */
  65313. u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
  65314. u.bf.r.nField = u.bf.nField + 1;
  65315. u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
  65316. u.bf.r.aMem = u.bf.aMx;
  65317. #ifdef SQLITE_DEBUG
  65318. { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
  65319. #endif
  65320. /* Extract the value of u.bf.R from register P3. */
  65321. sqlite3VdbeMemIntegerify(pIn3);
  65322. u.bf.R = pIn3->u.i;
  65323. /* Search the B-Tree index. If no conflicting record is found, jump
  65324. ** to P2. Otherwise, copy the rowid of the conflicting record to
  65325. ** register P3 and fall through to the next instruction. */
  65326. rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
  65327. if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
  65328. pc = pOp->p2 - 1;
  65329. }else{
  65330. pIn3->u.i = u.bf.r.rowid;
  65331. }
  65332. }
  65333. break;
  65334. }
  65335. /* Opcode: NotExists P1 P2 P3 * *
  65336. **
  65337. ** Use the content of register P3 as an integer key. If a record
  65338. ** with that key does not exist in table of P1, then jump to P2.
  65339. ** If the record does exist, then fall through. The cursor is left
  65340. ** pointing to the record if it exists.
  65341. **
  65342. ** The difference between this operation and NotFound is that this
  65343. ** operation assumes the key is an integer and that P1 is a table whereas
  65344. ** NotFound assumes key is a blob constructed from MakeRecord and
  65345. ** P1 is an index.
  65346. **
  65347. ** See also: Found, NotFound, IsUnique
  65348. */
  65349. case OP_NotExists: { /* jump, in3 */
  65350. #if 0 /* local variables moved into u.bg */
  65351. VdbeCursor *pC;
  65352. BtCursor *pCrsr;
  65353. int res;
  65354. u64 iKey;
  65355. #endif /* local variables moved into u.bg */
  65356. pIn3 = &aMem[pOp->p3];
  65357. assert( pIn3->flags & MEM_Int );
  65358. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65359. u.bg.pC = p->apCsr[pOp->p1];
  65360. assert( u.bg.pC!=0 );
  65361. assert( u.bg.pC->isTable );
  65362. assert( u.bg.pC->pseudoTableReg==0 );
  65363. u.bg.pCrsr = u.bg.pC->pCursor;
  65364. if( ALWAYS(u.bg.pCrsr!=0) ){
  65365. u.bg.res = 0;
  65366. u.bg.iKey = pIn3->u.i;
  65367. rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
  65368. u.bg.pC->lastRowid = pIn3->u.i;
  65369. u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
  65370. u.bg.pC->nullRow = 0;
  65371. u.bg.pC->cacheStatus = CACHE_STALE;
  65372. u.bg.pC->deferredMoveto = 0;
  65373. if( u.bg.res!=0 ){
  65374. pc = pOp->p2 - 1;
  65375. assert( u.bg.pC->rowidIsValid==0 );
  65376. }
  65377. u.bg.pC->seekResult = u.bg.res;
  65378. }else{
  65379. /* This happens when an attempt to open a read cursor on the
  65380. ** sqlite_master table returns SQLITE_EMPTY.
  65381. */
  65382. pc = pOp->p2 - 1;
  65383. assert( u.bg.pC->rowidIsValid==0 );
  65384. u.bg.pC->seekResult = 0;
  65385. }
  65386. break;
  65387. }
  65388. /* Opcode: Sequence P1 P2 * * *
  65389. **
  65390. ** Find the next available sequence number for cursor P1.
  65391. ** Write the sequence number into register P2.
  65392. ** The sequence number on the cursor is incremented after this
  65393. ** instruction.
  65394. */
  65395. case OP_Sequence: { /* out2-prerelease */
  65396. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65397. assert( p->apCsr[pOp->p1]!=0 );
  65398. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  65399. break;
  65400. }
  65401. /* Opcode: NewRowid P1 P2 P3 * *
  65402. **
  65403. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  65404. ** The record number is not previously used as a key in the database
  65405. ** table that cursor P1 points to. The new record number is written
  65406. ** written to register P2.
  65407. **
  65408. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  65409. ** the largest previously generated record number. No new record numbers are
  65410. ** allowed to be less than this value. When this value reaches its maximum,
  65411. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  65412. ** generated record number. This P3 mechanism is used to help implement the
  65413. ** AUTOINCREMENT feature.
  65414. */
  65415. case OP_NewRowid: { /* out2-prerelease */
  65416. #if 0 /* local variables moved into u.bh */
  65417. i64 v; /* The new rowid */
  65418. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  65419. int res; /* Result of an sqlite3BtreeLast() */
  65420. int cnt; /* Counter to limit the number of searches */
  65421. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  65422. VdbeFrame *pFrame; /* Root frame of VDBE */
  65423. #endif /* local variables moved into u.bh */
  65424. u.bh.v = 0;
  65425. u.bh.res = 0;
  65426. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65427. u.bh.pC = p->apCsr[pOp->p1];
  65428. assert( u.bh.pC!=0 );
  65429. if( NEVER(u.bh.pC->pCursor==0) ){
  65430. /* The zero initialization above is all that is needed */
  65431. }else{
  65432. /* The next rowid or record number (different terms for the same
  65433. ** thing) is obtained in a two-step algorithm.
  65434. **
  65435. ** First we attempt to find the largest existing rowid and add one
  65436. ** to that. But if the largest existing rowid is already the maximum
  65437. ** positive integer, we have to fall through to the second
  65438. ** probabilistic algorithm
  65439. **
  65440. ** The second algorithm is to select a rowid at random and see if
  65441. ** it already exists in the table. If it does not exist, we have
  65442. ** succeeded. If the random rowid does exist, we select a new one
  65443. ** and try again, up to 100 times.
  65444. */
  65445. assert( u.bh.pC->isTable );
  65446. #ifdef SQLITE_32BIT_ROWID
  65447. # define MAX_ROWID 0x7fffffff
  65448. #else
  65449. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  65450. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  65451. ** to provide the constant while making all compilers happy.
  65452. */
  65453. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  65454. #endif
  65455. if( !u.bh.pC->useRandomRowid ){
  65456. u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
  65457. if( u.bh.v==0 ){
  65458. rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
  65459. if( rc!=SQLITE_OK ){
  65460. goto abort_due_to_error;
  65461. }
  65462. if( u.bh.res ){
  65463. u.bh.v = 1; /* IMP: R-61914-48074 */
  65464. }else{
  65465. assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
  65466. rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
  65467. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  65468. if( u.bh.v>=MAX_ROWID ){
  65469. u.bh.pC->useRandomRowid = 1;
  65470. }else{
  65471. u.bh.v++; /* IMP: R-29538-34987 */
  65472. }
  65473. }
  65474. }
  65475. #ifndef SQLITE_OMIT_AUTOINCREMENT
  65476. if( pOp->p3 ){
  65477. /* Assert that P3 is a valid memory cell. */
  65478. assert( pOp->p3>0 );
  65479. if( p->pFrame ){
  65480. for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
  65481. /* Assert that P3 is a valid memory cell. */
  65482. assert( pOp->p3<=u.bh.pFrame->nMem );
  65483. u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
  65484. }else{
  65485. /* Assert that P3 is a valid memory cell. */
  65486. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65487. u.bh.pMem = &aMem[pOp->p3];
  65488. memAboutToChange(p, u.bh.pMem);
  65489. }
  65490. assert( memIsValid(u.bh.pMem) );
  65491. REGISTER_TRACE(pOp->p3, u.bh.pMem);
  65492. sqlite3VdbeMemIntegerify(u.bh.pMem);
  65493. assert( (u.bh.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  65494. if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
  65495. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  65496. goto abort_due_to_error;
  65497. }
  65498. if( u.bh.v<u.bh.pMem->u.i+1 ){
  65499. u.bh.v = u.bh.pMem->u.i + 1;
  65500. }
  65501. u.bh.pMem->u.i = u.bh.v;
  65502. }
  65503. #endif
  65504. sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
  65505. }
  65506. if( u.bh.pC->useRandomRowid ){
  65507. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  65508. ** largest possible integer (9223372036854775807) then the database
  65509. ** engine starts picking positive candidate ROWIDs at random until
  65510. ** it finds one that is not previously used. */
  65511. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  65512. ** an AUTOINCREMENT table. */
  65513. /* on the first attempt, simply do one more than previous */
  65514. u.bh.v = lastRowid;
  65515. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  65516. u.bh.v++; /* ensure non-zero */
  65517. u.bh.cnt = 0;
  65518. while( ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
  65519. 0, &u.bh.res))==SQLITE_OK)
  65520. && (u.bh.res==0)
  65521. && (++u.bh.cnt<100)){
  65522. /* collision - try another random rowid */
  65523. sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
  65524. if( u.bh.cnt<5 ){
  65525. /* try "small" random rowids for the initial attempts */
  65526. u.bh.v &= 0xffffff;
  65527. }else{
  65528. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  65529. }
  65530. u.bh.v++; /* ensure non-zero */
  65531. }
  65532. if( rc==SQLITE_OK && u.bh.res==0 ){
  65533. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  65534. goto abort_due_to_error;
  65535. }
  65536. assert( u.bh.v>0 ); /* EV: R-40812-03570 */
  65537. }
  65538. u.bh.pC->rowidIsValid = 0;
  65539. u.bh.pC->deferredMoveto = 0;
  65540. u.bh.pC->cacheStatus = CACHE_STALE;
  65541. }
  65542. pOut->u.i = u.bh.v;
  65543. break;
  65544. }
  65545. /* Opcode: Insert P1 P2 P3 P4 P5
  65546. **
  65547. ** Write an entry into the table of cursor P1. A new entry is
  65548. ** created if it doesn't already exist or the data for an existing
  65549. ** entry is overwritten. The data is the value MEM_Blob stored in register
  65550. ** number P2. The key is stored in register P3. The key must
  65551. ** be a MEM_Int.
  65552. **
  65553. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  65554. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  65555. ** then rowid is stored for subsequent return by the
  65556. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  65557. **
  65558. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  65559. ** the last seek operation (OP_NotExists) was a success, then this
  65560. ** operation will not attempt to find the appropriate row before doing
  65561. ** the insert but will instead overwrite the row that the cursor is
  65562. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  65563. ** has already positioned the cursor correctly. This is an optimization
  65564. ** that boosts performance by avoiding redundant seeks.
  65565. **
  65566. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  65567. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  65568. ** is part of an INSERT operation. The difference is only important to
  65569. ** the update hook.
  65570. **
  65571. ** Parameter P4 may point to a string containing the table-name, or
  65572. ** may be NULL. If it is not NULL, then the update-hook
  65573. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  65574. **
  65575. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  65576. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  65577. ** and register P2 becomes ephemeral. If the cursor is changed, the
  65578. ** value of register P2 will then change. Make sure this does not
  65579. ** cause any problems.)
  65580. **
  65581. ** This instruction only works on tables. The equivalent instruction
  65582. ** for indices is OP_IdxInsert.
  65583. */
  65584. /* Opcode: InsertInt P1 P2 P3 P4 P5
  65585. **
  65586. ** This works exactly like OP_Insert except that the key is the
  65587. ** integer value P3, not the value of the integer stored in register P3.
  65588. */
  65589. case OP_Insert:
  65590. case OP_InsertInt: {
  65591. #if 0 /* local variables moved into u.bi */
  65592. Mem *pData; /* MEM cell holding data for the record to be inserted */
  65593. Mem *pKey; /* MEM cell holding key for the record */
  65594. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  65595. VdbeCursor *pC; /* Cursor to table into which insert is written */
  65596. int nZero; /* Number of zero-bytes to append */
  65597. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  65598. const char *zDb; /* database name - used by the update hook */
  65599. const char *zTbl; /* Table name - used by the opdate hook */
  65600. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  65601. #endif /* local variables moved into u.bi */
  65602. u.bi.pData = &aMem[pOp->p2];
  65603. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65604. assert( memIsValid(u.bi.pData) );
  65605. u.bi.pC = p->apCsr[pOp->p1];
  65606. assert( u.bi.pC!=0 );
  65607. assert( u.bi.pC->pCursor!=0 );
  65608. assert( u.bi.pC->pseudoTableReg==0 );
  65609. assert( u.bi.pC->isTable );
  65610. REGISTER_TRACE(pOp->p2, u.bi.pData);
  65611. if( pOp->opcode==OP_Insert ){
  65612. u.bi.pKey = &aMem[pOp->p3];
  65613. assert( u.bi.pKey->flags & MEM_Int );
  65614. assert( memIsValid(u.bi.pKey) );
  65615. REGISTER_TRACE(pOp->p3, u.bi.pKey);
  65616. u.bi.iKey = u.bi.pKey->u.i;
  65617. }else{
  65618. assert( pOp->opcode==OP_InsertInt );
  65619. u.bi.iKey = pOp->p3;
  65620. }
  65621. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  65622. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
  65623. if( u.bi.pData->flags & MEM_Null ){
  65624. u.bi.pData->z = 0;
  65625. u.bi.pData->n = 0;
  65626. }else{
  65627. assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
  65628. }
  65629. u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
  65630. if( u.bi.pData->flags & MEM_Zero ){
  65631. u.bi.nZero = u.bi.pData->u.nZero;
  65632. }else{
  65633. u.bi.nZero = 0;
  65634. }
  65635. sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
  65636. rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
  65637. u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
  65638. pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
  65639. );
  65640. u.bi.pC->rowidIsValid = 0;
  65641. u.bi.pC->deferredMoveto = 0;
  65642. u.bi.pC->cacheStatus = CACHE_STALE;
  65643. /* Invoke the update-hook if required. */
  65644. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  65645. u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
  65646. u.bi.zTbl = pOp->p4.z;
  65647. u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  65648. assert( u.bi.pC->isTable );
  65649. db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
  65650. assert( u.bi.pC->iDb>=0 );
  65651. }
  65652. break;
  65653. }
  65654. /* Opcode: Delete P1 P2 * P4 *
  65655. **
  65656. ** Delete the record at which the P1 cursor is currently pointing.
  65657. **
  65658. ** The cursor will be left pointing at either the next or the previous
  65659. ** record in the table. If it is left pointing at the next record, then
  65660. ** the next Next instruction will be a no-op. Hence it is OK to delete
  65661. ** a record from within an Next loop.
  65662. **
  65663. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  65664. ** incremented (otherwise not).
  65665. **
  65666. ** P1 must not be pseudo-table. It has to be a real table with
  65667. ** multiple rows.
  65668. **
  65669. ** If P4 is not NULL, then it is the name of the table that P1 is
  65670. ** pointing to. The update hook will be invoked, if it exists.
  65671. ** If P4 is not NULL then the P1 cursor must have been positioned
  65672. ** using OP_NotFound prior to invoking this opcode.
  65673. */
  65674. case OP_Delete: {
  65675. #if 0 /* local variables moved into u.bj */
  65676. i64 iKey;
  65677. VdbeCursor *pC;
  65678. #endif /* local variables moved into u.bj */
  65679. u.bj.iKey = 0;
  65680. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65681. u.bj.pC = p->apCsr[pOp->p1];
  65682. assert( u.bj.pC!=0 );
  65683. assert( u.bj.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  65684. /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
  65685. ** row being deleted.
  65686. */
  65687. if( db->xUpdateCallback && pOp->p4.z ){
  65688. assert( u.bj.pC->isTable );
  65689. assert( u.bj.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
  65690. u.bj.iKey = u.bj.pC->lastRowid;
  65691. }
  65692. /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
  65693. ** OP_Column on the same table without any intervening operations that
  65694. ** might move or invalidate the cursor. Hence cursor u.bj.pC is always pointing
  65695. ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
  65696. ** below is always a no-op and cannot fail. We will run it anyhow, though,
  65697. ** to guard against future changes to the code generator.
  65698. **/
  65699. assert( u.bj.pC->deferredMoveto==0 );
  65700. rc = sqlite3VdbeCursorMoveto(u.bj.pC);
  65701. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  65702. sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
  65703. rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
  65704. u.bj.pC->cacheStatus = CACHE_STALE;
  65705. /* Invoke the update-hook if required. */
  65706. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  65707. const char *zDb = db->aDb[u.bj.pC->iDb].zName;
  65708. const char *zTbl = pOp->p4.z;
  65709. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
  65710. assert( u.bj.pC->iDb>=0 );
  65711. }
  65712. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  65713. break;
  65714. }
  65715. /* Opcode: ResetCount * * * * *
  65716. **
  65717. ** The value of the change counter is copied to the database handle
  65718. ** change counter (returned by subsequent calls to sqlite3_changes()).
  65719. ** Then the VMs internal change counter resets to 0.
  65720. ** This is used by trigger programs.
  65721. */
  65722. case OP_ResetCount: {
  65723. sqlite3VdbeSetChanges(db, p->nChange);
  65724. p->nChange = 0;
  65725. break;
  65726. }
  65727. /* Opcode: SorterCompare P1 P2 P3
  65728. **
  65729. ** P1 is a sorter cursor. This instruction compares the record blob in
  65730. ** register P3 with the entry that the sorter cursor currently points to.
  65731. ** If, excluding the rowid fields at the end, the two records are a match,
  65732. ** fall through to the next instruction. Otherwise, jump to instruction P2.
  65733. */
  65734. case OP_SorterCompare: {
  65735. #if 0 /* local variables moved into u.bk */
  65736. VdbeCursor *pC;
  65737. int res;
  65738. #endif /* local variables moved into u.bk */
  65739. u.bk.pC = p->apCsr[pOp->p1];
  65740. assert( isSorter(u.bk.pC) );
  65741. pIn3 = &aMem[pOp->p3];
  65742. rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
  65743. if( u.bk.res ){
  65744. pc = pOp->p2-1;
  65745. }
  65746. break;
  65747. };
  65748. /* Opcode: SorterData P1 P2 * * *
  65749. **
  65750. ** Write into register P2 the current sorter data for sorter cursor P1.
  65751. */
  65752. case OP_SorterData: {
  65753. #if 0 /* local variables moved into u.bl */
  65754. VdbeCursor *pC;
  65755. #endif /* local variables moved into u.bl */
  65756. pOut = &aMem[pOp->p2];
  65757. u.bl.pC = p->apCsr[pOp->p1];
  65758. assert( u.bl.pC->isSorter );
  65759. rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
  65760. break;
  65761. }
  65762. /* Opcode: RowData P1 P2 * * *
  65763. **
  65764. ** Write into register P2 the complete row data for cursor P1.
  65765. ** There is no interpretation of the data.
  65766. ** It is just copied onto the P2 register exactly as
  65767. ** it is found in the database file.
  65768. **
  65769. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  65770. ** of a real table, not a pseudo-table.
  65771. */
  65772. /* Opcode: RowKey P1 P2 * * *
  65773. **
  65774. ** Write into register P2 the complete row key for cursor P1.
  65775. ** There is no interpretation of the data.
  65776. ** The key is copied onto the P3 register exactly as
  65777. ** it is found in the database file.
  65778. **
  65779. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  65780. ** of a real table, not a pseudo-table.
  65781. */
  65782. case OP_RowKey:
  65783. case OP_RowData: {
  65784. #if 0 /* local variables moved into u.bm */
  65785. VdbeCursor *pC;
  65786. BtCursor *pCrsr;
  65787. u32 n;
  65788. i64 n64;
  65789. #endif /* local variables moved into u.bm */
  65790. pOut = &aMem[pOp->p2];
  65791. memAboutToChange(p, pOut);
  65792. /* Note that RowKey and RowData are really exactly the same instruction */
  65793. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65794. u.bm.pC = p->apCsr[pOp->p1];
  65795. assert( u.bm.pC->isSorter==0 );
  65796. assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
  65797. assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
  65798. assert( u.bm.pC!=0 );
  65799. assert( u.bm.pC->nullRow==0 );
  65800. assert( u.bm.pC->pseudoTableReg==0 );
  65801. assert( u.bm.pC->pCursor!=0 );
  65802. u.bm.pCrsr = u.bm.pC->pCursor;
  65803. assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
  65804. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  65805. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  65806. ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
  65807. ** a no-op and can never fail. But we leave it in place as a safety.
  65808. */
  65809. assert( u.bm.pC->deferredMoveto==0 );
  65810. rc = sqlite3VdbeCursorMoveto(u.bm.pC);
  65811. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  65812. if( u.bm.pC->isIndex ){
  65813. assert( !u.bm.pC->isTable );
  65814. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
  65815. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  65816. if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65817. goto too_big;
  65818. }
  65819. u.bm.n = (u32)u.bm.n64;
  65820. }else{
  65821. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
  65822. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  65823. if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65824. goto too_big;
  65825. }
  65826. }
  65827. if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
  65828. goto no_mem;
  65829. }
  65830. pOut->n = u.bm.n;
  65831. MemSetTypeFlag(pOut, MEM_Blob);
  65832. if( u.bm.pC->isIndex ){
  65833. rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  65834. }else{
  65835. rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  65836. }
  65837. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  65838. UPDATE_MAX_BLOBSIZE(pOut);
  65839. break;
  65840. }
  65841. /* Opcode: Rowid P1 P2 * * *
  65842. **
  65843. ** Store in register P2 an integer which is the key of the table entry that
  65844. ** P1 is currently point to.
  65845. **
  65846. ** P1 can be either an ordinary table or a virtual table. There used to
  65847. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  65848. ** one opcode now works for both table types.
  65849. */
  65850. case OP_Rowid: { /* out2-prerelease */
  65851. #if 0 /* local variables moved into u.bn */
  65852. VdbeCursor *pC;
  65853. i64 v;
  65854. sqlite3_vtab *pVtab;
  65855. const sqlite3_module *pModule;
  65856. #endif /* local variables moved into u.bn */
  65857. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65858. u.bn.pC = p->apCsr[pOp->p1];
  65859. assert( u.bn.pC!=0 );
  65860. assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
  65861. if( u.bn.pC->nullRow ){
  65862. pOut->flags = MEM_Null;
  65863. break;
  65864. }else if( u.bn.pC->deferredMoveto ){
  65865. u.bn.v = u.bn.pC->movetoTarget;
  65866. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65867. }else if( u.bn.pC->pVtabCursor ){
  65868. u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
  65869. u.bn.pModule = u.bn.pVtab->pModule;
  65870. assert( u.bn.pModule->xRowid );
  65871. rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
  65872. sqlite3VtabImportErrmsg(p, u.bn.pVtab);
  65873. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  65874. }else{
  65875. assert( u.bn.pC->pCursor!=0 );
  65876. rc = sqlite3VdbeCursorMoveto(u.bn.pC);
  65877. if( rc ) goto abort_due_to_error;
  65878. if( u.bn.pC->rowidIsValid ){
  65879. u.bn.v = u.bn.pC->lastRowid;
  65880. }else{
  65881. rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
  65882. assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
  65883. }
  65884. }
  65885. pOut->u.i = u.bn.v;
  65886. break;
  65887. }
  65888. /* Opcode: NullRow P1 * * * *
  65889. **
  65890. ** Move the cursor P1 to a null row. Any OP_Column operations
  65891. ** that occur while the cursor is on the null row will always
  65892. ** write a NULL.
  65893. */
  65894. case OP_NullRow: {
  65895. #if 0 /* local variables moved into u.bo */
  65896. VdbeCursor *pC;
  65897. #endif /* local variables moved into u.bo */
  65898. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65899. u.bo.pC = p->apCsr[pOp->p1];
  65900. assert( u.bo.pC!=0 );
  65901. u.bo.pC->nullRow = 1;
  65902. u.bo.pC->rowidIsValid = 0;
  65903. assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
  65904. if( u.bo.pC->pCursor ){
  65905. sqlite3BtreeClearCursor(u.bo.pC->pCursor);
  65906. }
  65907. break;
  65908. }
  65909. /* Opcode: Last P1 P2 * * *
  65910. **
  65911. ** The next use of the Rowid or Column or Next instruction for P1
  65912. ** will refer to the last entry in the database table or index.
  65913. ** If the table or index is empty and P2>0, then jump immediately to P2.
  65914. ** If P2 is 0 or if the table or index is not empty, fall through
  65915. ** to the following instruction.
  65916. */
  65917. case OP_Last: { /* jump */
  65918. #if 0 /* local variables moved into u.bp */
  65919. VdbeCursor *pC;
  65920. BtCursor *pCrsr;
  65921. int res;
  65922. #endif /* local variables moved into u.bp */
  65923. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65924. u.bp.pC = p->apCsr[pOp->p1];
  65925. assert( u.bp.pC!=0 );
  65926. u.bp.pCrsr = u.bp.pC->pCursor;
  65927. u.bp.res = 0;
  65928. if( ALWAYS(u.bp.pCrsr!=0) ){
  65929. rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
  65930. }
  65931. u.bp.pC->nullRow = (u8)u.bp.res;
  65932. u.bp.pC->deferredMoveto = 0;
  65933. u.bp.pC->rowidIsValid = 0;
  65934. u.bp.pC->cacheStatus = CACHE_STALE;
  65935. if( pOp->p2>0 && u.bp.res ){
  65936. pc = pOp->p2 - 1;
  65937. }
  65938. break;
  65939. }
  65940. /* Opcode: Sort P1 P2 * * *
  65941. **
  65942. ** This opcode does exactly the same thing as OP_Rewind except that
  65943. ** it increments an undocumented global variable used for testing.
  65944. **
  65945. ** Sorting is accomplished by writing records into a sorting index,
  65946. ** then rewinding that index and playing it back from beginning to
  65947. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  65948. ** rewinding so that the global variable will be incremented and
  65949. ** regression tests can determine whether or not the optimizer is
  65950. ** correctly optimizing out sorts.
  65951. */
  65952. case OP_SorterSort: /* jump */
  65953. case OP_Sort: { /* jump */
  65954. #ifdef SQLITE_TEST
  65955. sqlite3_sort_count++;
  65956. sqlite3_search_count--;
  65957. #endif
  65958. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  65959. /* Fall through into OP_Rewind */
  65960. }
  65961. /* Opcode: Rewind P1 P2 * * *
  65962. **
  65963. ** The next use of the Rowid or Column or Next instruction for P1
  65964. ** will refer to the first entry in the database table or index.
  65965. ** If the table or index is empty and P2>0, then jump immediately to P2.
  65966. ** If P2 is 0 or if the table or index is not empty, fall through
  65967. ** to the following instruction.
  65968. */
  65969. case OP_Rewind: { /* jump */
  65970. #if 0 /* local variables moved into u.bq */
  65971. VdbeCursor *pC;
  65972. BtCursor *pCrsr;
  65973. int res;
  65974. #endif /* local variables moved into u.bq */
  65975. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65976. u.bq.pC = p->apCsr[pOp->p1];
  65977. assert( u.bq.pC!=0 );
  65978. assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
  65979. u.bq.res = 1;
  65980. if( isSorter(u.bq.pC) ){
  65981. rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
  65982. }else{
  65983. u.bq.pCrsr = u.bq.pC->pCursor;
  65984. assert( u.bq.pCrsr );
  65985. rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
  65986. u.bq.pC->atFirst = u.bq.res==0 ?1:0;
  65987. u.bq.pC->deferredMoveto = 0;
  65988. u.bq.pC->cacheStatus = CACHE_STALE;
  65989. u.bq.pC->rowidIsValid = 0;
  65990. }
  65991. u.bq.pC->nullRow = (u8)u.bq.res;
  65992. assert( pOp->p2>0 && pOp->p2<p->nOp );
  65993. if( u.bq.res ){
  65994. pc = pOp->p2 - 1;
  65995. }
  65996. break;
  65997. }
  65998. /* Opcode: Next P1 P2 * P4 P5
  65999. **
  66000. ** Advance cursor P1 so that it points to the next key/data pair in its
  66001. ** table or index. If there are no more key/value pairs then fall through
  66002. ** to the following instruction. But if the cursor advance was successful,
  66003. ** jump immediately to P2.
  66004. **
  66005. ** The P1 cursor must be for a real table, not a pseudo-table.
  66006. **
  66007. ** P4 is always of type P4_ADVANCE. The function pointer points to
  66008. ** sqlite3BtreeNext().
  66009. **
  66010. ** If P5 is positive and the jump is taken, then event counter
  66011. ** number P5-1 in the prepared statement is incremented.
  66012. **
  66013. ** See also: Prev
  66014. */
  66015. /* Opcode: Prev P1 P2 * * P5
  66016. **
  66017. ** Back up cursor P1 so that it points to the previous key/data pair in its
  66018. ** table or index. If there is no previous key/value pairs then fall through
  66019. ** to the following instruction. But if the cursor backup was successful,
  66020. ** jump immediately to P2.
  66021. **
  66022. ** The P1 cursor must be for a real table, not a pseudo-table.
  66023. **
  66024. ** P4 is always of type P4_ADVANCE. The function pointer points to
  66025. ** sqlite3BtreePrevious().
  66026. **
  66027. ** If P5 is positive and the jump is taken, then event counter
  66028. ** number P5-1 in the prepared statement is incremented.
  66029. */
  66030. case OP_SorterNext: /* jump */
  66031. case OP_Prev: /* jump */
  66032. case OP_Next: { /* jump */
  66033. #if 0 /* local variables moved into u.br */
  66034. VdbeCursor *pC;
  66035. int res;
  66036. #endif /* local variables moved into u.br */
  66037. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  66038. assert( pOp->p5<ArraySize(p->aCounter) );
  66039. u.br.pC = p->apCsr[pOp->p1];
  66040. if( u.br.pC==0 ){
  66041. break; /* See ticket #2273 */
  66042. }
  66043. assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
  66044. if( isSorter(u.br.pC) ){
  66045. assert( pOp->opcode==OP_SorterNext );
  66046. rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
  66047. }else{
  66048. /* u.br.res = 1; // Always initialized by the xAdvance() call */
  66049. assert( u.br.pC->deferredMoveto==0 );
  66050. assert( u.br.pC->pCursor );
  66051. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  66052. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  66053. rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
  66054. }
  66055. u.br.pC->nullRow = (u8)u.br.res;
  66056. u.br.pC->cacheStatus = CACHE_STALE;
  66057. if( u.br.res==0 ){
  66058. pc = pOp->p2 - 1;
  66059. p->aCounter[pOp->p5]++;
  66060. #ifdef SQLITE_TEST
  66061. sqlite3_search_count++;
  66062. #endif
  66063. }
  66064. u.br.pC->rowidIsValid = 0;
  66065. goto check_for_interrupt;
  66066. }
  66067. /* Opcode: IdxInsert P1 P2 P3 * P5
  66068. **
  66069. ** Register P2 holds an SQL index key made using the
  66070. ** MakeRecord instructions. This opcode writes that key
  66071. ** into the index P1. Data for the entry is nil.
  66072. **
  66073. ** P3 is a flag that provides a hint to the b-tree layer that this
  66074. ** insert is likely to be an append.
  66075. **
  66076. ** This instruction only works for indices. The equivalent instruction
  66077. ** for tables is OP_Insert.
  66078. */
  66079. case OP_SorterInsert: /* in2 */
  66080. case OP_IdxInsert: { /* in2 */
  66081. #if 0 /* local variables moved into u.bs */
  66082. VdbeCursor *pC;
  66083. BtCursor *pCrsr;
  66084. int nKey;
  66085. const char *zKey;
  66086. #endif /* local variables moved into u.bs */
  66087. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  66088. u.bs.pC = p->apCsr[pOp->p1];
  66089. assert( u.bs.pC!=0 );
  66090. assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
  66091. pIn2 = &aMem[pOp->p2];
  66092. assert( pIn2->flags & MEM_Blob );
  66093. u.bs.pCrsr = u.bs.pC->pCursor;
  66094. if( ALWAYS(u.bs.pCrsr!=0) ){
  66095. assert( u.bs.pC->isTable==0 );
  66096. rc = ExpandBlob(pIn2);
  66097. if( rc==SQLITE_OK ){
  66098. if( isSorter(u.bs.pC) ){
  66099. rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
  66100. }else{
  66101. u.bs.nKey = pIn2->n;
  66102. u.bs.zKey = pIn2->z;
  66103. rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
  66104. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
  66105. );
  66106. assert( u.bs.pC->deferredMoveto==0 );
  66107. u.bs.pC->cacheStatus = CACHE_STALE;
  66108. }
  66109. }
  66110. }
  66111. break;
  66112. }
  66113. /* Opcode: IdxDelete P1 P2 P3 * *
  66114. **
  66115. ** The content of P3 registers starting at register P2 form
  66116. ** an unpacked index key. This opcode removes that entry from the
  66117. ** index opened by cursor P1.
  66118. */
  66119. case OP_IdxDelete: {
  66120. #if 0 /* local variables moved into u.bt */
  66121. VdbeCursor *pC;
  66122. BtCursor *pCrsr;
  66123. int res;
  66124. UnpackedRecord r;
  66125. #endif /* local variables moved into u.bt */
  66126. assert( pOp->p3>0 );
  66127. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
  66128. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  66129. u.bt.pC = p->apCsr[pOp->p1];
  66130. assert( u.bt.pC!=0 );
  66131. u.bt.pCrsr = u.bt.pC->pCursor;
  66132. if( ALWAYS(u.bt.pCrsr!=0) ){
  66133. u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
  66134. u.bt.r.nField = (u16)pOp->p3;
  66135. u.bt.r.flags = 0;
  66136. u.bt.r.aMem = &aMem[pOp->p2];
  66137. #ifdef SQLITE_DEBUG
  66138. { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
  66139. #endif
  66140. rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
  66141. if( rc==SQLITE_OK && u.bt.res==0 ){
  66142. rc = sqlite3BtreeDelete(u.bt.pCrsr);
  66143. }
  66144. assert( u.bt.pC->deferredMoveto==0 );
  66145. u.bt.pC->cacheStatus = CACHE_STALE;
  66146. }
  66147. break;
  66148. }
  66149. /* Opcode: IdxRowid P1 P2 * * *
  66150. **
  66151. ** Write into register P2 an integer which is the last entry in the record at
  66152. ** the end of the index key pointed to by cursor P1. This integer should be
  66153. ** the rowid of the table entry to which this index entry points.
  66154. **
  66155. ** See also: Rowid, MakeRecord.
  66156. */
  66157. case OP_IdxRowid: { /* out2-prerelease */
  66158. #if 0 /* local variables moved into u.bu */
  66159. BtCursor *pCrsr;
  66160. VdbeCursor *pC;
  66161. i64 rowid;
  66162. #endif /* local variables moved into u.bu */
  66163. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  66164. u.bu.pC = p->apCsr[pOp->p1];
  66165. assert( u.bu.pC!=0 );
  66166. u.bu.pCrsr = u.bu.pC->pCursor;
  66167. pOut->flags = MEM_Null;
  66168. if( ALWAYS(u.bu.pCrsr!=0) ){
  66169. rc = sqlite3VdbeCursorMoveto(u.bu.pC);
  66170. if( NEVER(rc) ) goto abort_due_to_error;
  66171. assert( u.bu.pC->deferredMoveto==0 );
  66172. assert( u.bu.pC->isTable==0 );
  66173. if( !u.bu.pC->nullRow ){
  66174. rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
  66175. if( rc!=SQLITE_OK ){
  66176. goto abort_due_to_error;
  66177. }
  66178. pOut->u.i = u.bu.rowid;
  66179. pOut->flags = MEM_Int;
  66180. }
  66181. }
  66182. break;
  66183. }
  66184. /* Opcode: IdxGE P1 P2 P3 P4 P5
  66185. **
  66186. ** The P4 register values beginning with P3 form an unpacked index
  66187. ** key that omits the ROWID. Compare this key value against the index
  66188. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  66189. **
  66190. ** If the P1 index entry is greater than or equal to the key value
  66191. ** then jump to P2. Otherwise fall through to the next instruction.
  66192. **
  66193. ** If P5 is non-zero then the key value is increased by an epsilon
  66194. ** prior to the comparison. This make the opcode work like IdxGT except
  66195. ** that if the key from register P3 is a prefix of the key in the cursor,
  66196. ** the result is false whereas it would be true with IdxGT.
  66197. */
  66198. /* Opcode: IdxLT P1 P2 P3 P4 P5
  66199. **
  66200. ** The P4 register values beginning with P3 form an unpacked index
  66201. ** key that omits the ROWID. Compare this key value against the index
  66202. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  66203. **
  66204. ** If the P1 index entry is less than the key value then jump to P2.
  66205. ** Otherwise fall through to the next instruction.
  66206. **
  66207. ** If P5 is non-zero then the key value is increased by an epsilon prior
  66208. ** to the comparison. This makes the opcode work like IdxLE.
  66209. */
  66210. case OP_IdxLT: /* jump */
  66211. case OP_IdxGE: { /* jump */
  66212. #if 0 /* local variables moved into u.bv */
  66213. VdbeCursor *pC;
  66214. int res;
  66215. UnpackedRecord r;
  66216. #endif /* local variables moved into u.bv */
  66217. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  66218. u.bv.pC = p->apCsr[pOp->p1];
  66219. assert( u.bv.pC!=0 );
  66220. assert( u.bv.pC->isOrdered );
  66221. if( ALWAYS(u.bv.pC->pCursor!=0) ){
  66222. assert( u.bv.pC->deferredMoveto==0 );
  66223. assert( pOp->p5==0 || pOp->p5==1 );
  66224. assert( pOp->p4type==P4_INT32 );
  66225. u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
  66226. u.bv.r.nField = (u16)pOp->p4.i;
  66227. if( pOp->p5 ){
  66228. u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
  66229. }else{
  66230. u.bv.r.flags = UNPACKED_PREFIX_MATCH;
  66231. }
  66232. u.bv.r.aMem = &aMem[pOp->p3];
  66233. #ifdef SQLITE_DEBUG
  66234. { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
  66235. #endif
  66236. rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
  66237. if( pOp->opcode==OP_IdxLT ){
  66238. u.bv.res = -u.bv.res;
  66239. }else{
  66240. assert( pOp->opcode==OP_IdxGE );
  66241. u.bv.res++;
  66242. }
  66243. if( u.bv.res>0 ){
  66244. pc = pOp->p2 - 1 ;
  66245. }
  66246. }
  66247. break;
  66248. }
  66249. /* Opcode: Destroy P1 P2 P3 * *
  66250. **
  66251. ** Delete an entire database table or index whose root page in the database
  66252. ** file is given by P1.
  66253. **
  66254. ** The table being destroyed is in the main database file if P3==0. If
  66255. ** P3==1 then the table to be clear is in the auxiliary database file
  66256. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  66257. **
  66258. ** If AUTOVACUUM is enabled then it is possible that another root page
  66259. ** might be moved into the newly deleted root page in order to keep all
  66260. ** root pages contiguous at the beginning of the database. The former
  66261. ** value of the root page that moved - its value before the move occurred -
  66262. ** is stored in register P2. If no page
  66263. ** movement was required (because the table being dropped was already
  66264. ** the last one in the database) then a zero is stored in register P2.
  66265. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  66266. **
  66267. ** See also: Clear
  66268. */
  66269. case OP_Destroy: { /* out2-prerelease */
  66270. #if 0 /* local variables moved into u.bw */
  66271. int iMoved;
  66272. int iCnt;
  66273. Vdbe *pVdbe;
  66274. int iDb;
  66275. #endif /* local variables moved into u.bw */
  66276. assert( p->readOnly==0 );
  66277. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66278. u.bw.iCnt = 0;
  66279. for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
  66280. if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->bIsReader
  66281. && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0
  66282. ){
  66283. u.bw.iCnt++;
  66284. }
  66285. }
  66286. #else
  66287. u.bw.iCnt = db->nVdbeRead;
  66288. #endif
  66289. pOut->flags = MEM_Null;
  66290. if( u.bw.iCnt>1 ){
  66291. rc = SQLITE_LOCKED;
  66292. p->errorAction = OE_Abort;
  66293. }else{
  66294. u.bw.iDb = pOp->p3;
  66295. assert( u.bw.iCnt==1 );
  66296. assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
  66297. rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
  66298. pOut->flags = MEM_Int;
  66299. pOut->u.i = u.bw.iMoved;
  66300. #ifndef SQLITE_OMIT_AUTOVACUUM
  66301. if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
  66302. sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
  66303. /* All OP_Destroy operations occur on the same btree */
  66304. assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
  66305. resetSchemaOnFault = u.bw.iDb+1;
  66306. }
  66307. #endif
  66308. }
  66309. break;
  66310. }
  66311. /* Opcode: Clear P1 P2 P3
  66312. **
  66313. ** Delete all contents of the database table or index whose root page
  66314. ** in the database file is given by P1. But, unlike Destroy, do not
  66315. ** remove the table or index from the database file.
  66316. **
  66317. ** The table being clear is in the main database file if P2==0. If
  66318. ** P2==1 then the table to be clear is in the auxiliary database file
  66319. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  66320. **
  66321. ** If the P3 value is non-zero, then the table referred to must be an
  66322. ** intkey table (an SQL table, not an index). In this case the row change
  66323. ** count is incremented by the number of rows in the table being cleared.
  66324. ** If P3 is greater than zero, then the value stored in register P3 is
  66325. ** also incremented by the number of rows in the table being cleared.
  66326. **
  66327. ** See also: Destroy
  66328. */
  66329. case OP_Clear: {
  66330. #if 0 /* local variables moved into u.bx */
  66331. int nChange;
  66332. #endif /* local variables moved into u.bx */
  66333. u.bx.nChange = 0;
  66334. assert( p->readOnly==0 );
  66335. assert( pOp->p1!=1 );
  66336. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
  66337. rc = sqlite3BtreeClearTable(
  66338. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
  66339. );
  66340. if( pOp->p3 ){
  66341. p->nChange += u.bx.nChange;
  66342. if( pOp->p3>0 ){
  66343. assert( memIsValid(&aMem[pOp->p3]) );
  66344. memAboutToChange(p, &aMem[pOp->p3]);
  66345. aMem[pOp->p3].u.i += u.bx.nChange;
  66346. }
  66347. }
  66348. break;
  66349. }
  66350. /* Opcode: CreateTable P1 P2 * * *
  66351. **
  66352. ** Allocate a new table in the main database file if P1==0 or in the
  66353. ** auxiliary database file if P1==1 or in an attached database if
  66354. ** P1>1. Write the root page number of the new table into
  66355. ** register P2
  66356. **
  66357. ** The difference between a table and an index is this: A table must
  66358. ** have a 4-byte integer key and can have arbitrary data. An index
  66359. ** has an arbitrary key but no data.
  66360. **
  66361. ** See also: CreateIndex
  66362. */
  66363. /* Opcode: CreateIndex P1 P2 * * *
  66364. **
  66365. ** Allocate a new index in the main database file if P1==0 or in the
  66366. ** auxiliary database file if P1==1 or in an attached database if
  66367. ** P1>1. Write the root page number of the new table into
  66368. ** register P2.
  66369. **
  66370. ** See documentation on OP_CreateTable for additional information.
  66371. */
  66372. case OP_CreateIndex: /* out2-prerelease */
  66373. case OP_CreateTable: { /* out2-prerelease */
  66374. #if 0 /* local variables moved into u.by */
  66375. int pgno;
  66376. int flags;
  66377. Db *pDb;
  66378. #endif /* local variables moved into u.by */
  66379. u.by.pgno = 0;
  66380. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  66381. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  66382. assert( p->readOnly==0 );
  66383. u.by.pDb = &db->aDb[pOp->p1];
  66384. assert( u.by.pDb->pBt!=0 );
  66385. if( pOp->opcode==OP_CreateTable ){
  66386. /* u.by.flags = BTREE_INTKEY; */
  66387. u.by.flags = BTREE_INTKEY;
  66388. }else{
  66389. u.by.flags = BTREE_BLOBKEY;
  66390. }
  66391. rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
  66392. pOut->u.i = u.by.pgno;
  66393. break;
  66394. }
  66395. /* Opcode: ParseSchema P1 * * P4 *
  66396. **
  66397. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  66398. ** that match the WHERE clause P4.
  66399. **
  66400. ** This opcode invokes the parser to create a new virtual machine,
  66401. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  66402. */
  66403. case OP_ParseSchema: {
  66404. #if 0 /* local variables moved into u.bz */
  66405. int iDb;
  66406. const char *zMaster;
  66407. char *zSql;
  66408. InitData initData;
  66409. #endif /* local variables moved into u.bz */
  66410. /* Any prepared statement that invokes this opcode will hold mutexes
  66411. ** on every btree. This is a prerequisite for invoking
  66412. ** sqlite3InitCallback().
  66413. */
  66414. #ifdef SQLITE_DEBUG
  66415. for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
  66416. assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
  66417. }
  66418. #endif
  66419. u.bz.iDb = pOp->p1;
  66420. assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
  66421. assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
  66422. /* Used to be a conditional */ {
  66423. u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
  66424. u.bz.initData.db = db;
  66425. u.bz.initData.iDb = pOp->p1;
  66426. u.bz.initData.pzErrMsg = &p->zErrMsg;
  66427. u.bz.zSql = sqlite3MPrintf(db,
  66428. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  66429. db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
  66430. if( u.bz.zSql==0 ){
  66431. rc = SQLITE_NOMEM;
  66432. }else{
  66433. assert( db->init.busy==0 );
  66434. db->init.busy = 1;
  66435. u.bz.initData.rc = SQLITE_OK;
  66436. assert( !db->mallocFailed );
  66437. rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
  66438. if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
  66439. sqlite3DbFree(db, u.bz.zSql);
  66440. db->init.busy = 0;
  66441. }
  66442. }
  66443. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  66444. if( rc==SQLITE_NOMEM ){
  66445. goto no_mem;
  66446. }
  66447. break;
  66448. }
  66449. #if !defined(SQLITE_OMIT_ANALYZE)
  66450. /* Opcode: LoadAnalysis P1 * * * *
  66451. **
  66452. ** Read the sqlite_stat1 table for database P1 and load the content
  66453. ** of that table into the internal index hash table. This will cause
  66454. ** the analysis to be used when preparing all subsequent queries.
  66455. */
  66456. case OP_LoadAnalysis: {
  66457. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  66458. rc = sqlite3AnalysisLoad(db, pOp->p1);
  66459. break;
  66460. }
  66461. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  66462. /* Opcode: DropTable P1 * * P4 *
  66463. **
  66464. ** Remove the internal (in-memory) data structures that describe
  66465. ** the table named P4 in database P1. This is called after a table
  66466. ** is dropped in order to keep the internal representation of the
  66467. ** schema consistent with what is on disk.
  66468. */
  66469. case OP_DropTable: {
  66470. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  66471. break;
  66472. }
  66473. /* Opcode: DropIndex P1 * * P4 *
  66474. **
  66475. ** Remove the internal (in-memory) data structures that describe
  66476. ** the index named P4 in database P1. This is called after an index
  66477. ** is dropped in order to keep the internal representation of the
  66478. ** schema consistent with what is on disk.
  66479. */
  66480. case OP_DropIndex: {
  66481. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  66482. break;
  66483. }
  66484. /* Opcode: DropTrigger P1 * * P4 *
  66485. **
  66486. ** Remove the internal (in-memory) data structures that describe
  66487. ** the trigger named P4 in database P1. This is called after a trigger
  66488. ** is dropped in order to keep the internal representation of the
  66489. ** schema consistent with what is on disk.
  66490. */
  66491. case OP_DropTrigger: {
  66492. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  66493. break;
  66494. }
  66495. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  66496. /* Opcode: IntegrityCk P1 P2 P3 * P5
  66497. **
  66498. ** Do an analysis of the currently open database. Store in
  66499. ** register P1 the text of an error message describing any problems.
  66500. ** If no problems are found, store a NULL in register P1.
  66501. **
  66502. ** The register P3 contains the maximum number of allowed errors.
  66503. ** At most reg(P3) errors will be reported.
  66504. ** In other words, the analysis stops as soon as reg(P1) errors are
  66505. ** seen. Reg(P1) is updated with the number of errors remaining.
  66506. **
  66507. ** The root page numbers of all tables in the database are integer
  66508. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  66509. ** total.
  66510. **
  66511. ** If P5 is not zero, the check is done on the auxiliary database
  66512. ** file, not the main database file.
  66513. **
  66514. ** This opcode is used to implement the integrity_check pragma.
  66515. */
  66516. case OP_IntegrityCk: {
  66517. #if 0 /* local variables moved into u.ca */
  66518. int nRoot; /* Number of tables to check. (Number of root pages.) */
  66519. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  66520. int j; /* Loop counter */
  66521. int nErr; /* Number of errors reported */
  66522. char *z; /* Text of the error report */
  66523. Mem *pnErr; /* Register keeping track of errors remaining */
  66524. #endif /* local variables moved into u.ca */
  66525. assert( p->bIsReader );
  66526. u.ca.nRoot = pOp->p2;
  66527. assert( u.ca.nRoot>0 );
  66528. u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
  66529. if( u.ca.aRoot==0 ) goto no_mem;
  66530. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  66531. u.ca.pnErr = &aMem[pOp->p3];
  66532. assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
  66533. assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  66534. pIn1 = &aMem[pOp->p1];
  66535. for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
  66536. u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
  66537. }
  66538. u.ca.aRoot[u.ca.j] = 0;
  66539. assert( pOp->p5<db->nDb );
  66540. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
  66541. u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
  66542. (int)u.ca.pnErr->u.i, &u.ca.nErr);
  66543. sqlite3DbFree(db, u.ca.aRoot);
  66544. u.ca.pnErr->u.i -= u.ca.nErr;
  66545. sqlite3VdbeMemSetNull(pIn1);
  66546. if( u.ca.nErr==0 ){
  66547. assert( u.ca.z==0 );
  66548. }else if( u.ca.z==0 ){
  66549. goto no_mem;
  66550. }else{
  66551. sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
  66552. }
  66553. UPDATE_MAX_BLOBSIZE(pIn1);
  66554. sqlite3VdbeChangeEncoding(pIn1, encoding);
  66555. break;
  66556. }
  66557. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  66558. /* Opcode: RowSetAdd P1 P2 * * *
  66559. **
  66560. ** Insert the integer value held by register P2 into a boolean index
  66561. ** held in register P1.
  66562. **
  66563. ** An assertion fails if P2 is not an integer.
  66564. */
  66565. case OP_RowSetAdd: { /* in1, in2 */
  66566. pIn1 = &aMem[pOp->p1];
  66567. pIn2 = &aMem[pOp->p2];
  66568. assert( (pIn2->flags & MEM_Int)!=0 );
  66569. if( (pIn1->flags & MEM_RowSet)==0 ){
  66570. sqlite3VdbeMemSetRowSet(pIn1);
  66571. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  66572. }
  66573. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  66574. break;
  66575. }
  66576. /* Opcode: RowSetRead P1 P2 P3 * *
  66577. **
  66578. ** Extract the smallest value from boolean index P1 and put that value into
  66579. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  66580. ** unchanged and jump to instruction P2.
  66581. */
  66582. case OP_RowSetRead: { /* jump, in1, out3 */
  66583. #if 0 /* local variables moved into u.cb */
  66584. i64 val;
  66585. #endif /* local variables moved into u.cb */
  66586. pIn1 = &aMem[pOp->p1];
  66587. if( (pIn1->flags & MEM_RowSet)==0
  66588. || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
  66589. ){
  66590. /* The boolean index is empty */
  66591. sqlite3VdbeMemSetNull(pIn1);
  66592. pc = pOp->p2 - 1;
  66593. }else{
  66594. /* A value was pulled from the index */
  66595. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
  66596. }
  66597. goto check_for_interrupt;
  66598. }
  66599. /* Opcode: RowSetTest P1 P2 P3 P4
  66600. **
  66601. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  66602. ** contains a RowSet object and that RowSet object contains
  66603. ** the value held in P3, jump to register P2. Otherwise, insert the
  66604. ** integer in P3 into the RowSet and continue on to the
  66605. ** next opcode.
  66606. **
  66607. ** The RowSet object is optimized for the case where successive sets
  66608. ** of integers, where each set contains no duplicates. Each set
  66609. ** of values is identified by a unique P4 value. The first set
  66610. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  66611. ** non-negative. For non-negative values of P4 only the lower 4
  66612. ** bits are significant.
  66613. **
  66614. ** This allows optimizations: (a) when P4==0 there is no need to test
  66615. ** the rowset object for P3, as it is guaranteed not to contain it,
  66616. ** (b) when P4==-1 there is no need to insert the value, as it will
  66617. ** never be tested for, and (c) when a value that is part of set X is
  66618. ** inserted, there is no need to search to see if the same value was
  66619. ** previously inserted as part of set X (only if it was previously
  66620. ** inserted as part of some other set).
  66621. */
  66622. case OP_RowSetTest: { /* jump, in1, in3 */
  66623. #if 0 /* local variables moved into u.cc */
  66624. int iSet;
  66625. int exists;
  66626. #endif /* local variables moved into u.cc */
  66627. pIn1 = &aMem[pOp->p1];
  66628. pIn3 = &aMem[pOp->p3];
  66629. u.cc.iSet = pOp->p4.i;
  66630. assert( pIn3->flags&MEM_Int );
  66631. /* If there is anything other than a rowset object in memory cell P1,
  66632. ** delete it now and initialize P1 with an empty rowset
  66633. */
  66634. if( (pIn1->flags & MEM_RowSet)==0 ){
  66635. sqlite3VdbeMemSetRowSet(pIn1);
  66636. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  66637. }
  66638. assert( pOp->p4type==P4_INT32 );
  66639. assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
  66640. if( u.cc.iSet ){
  66641. u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
  66642. (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
  66643. pIn3->u.i);
  66644. if( u.cc.exists ){
  66645. pc = pOp->p2 - 1;
  66646. break;
  66647. }
  66648. }
  66649. if( u.cc.iSet>=0 ){
  66650. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  66651. }
  66652. break;
  66653. }
  66654. #ifndef SQLITE_OMIT_TRIGGER
  66655. /* Opcode: Program P1 P2 P3 P4 *
  66656. **
  66657. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  66658. **
  66659. ** P1 contains the address of the memory cell that contains the first memory
  66660. ** cell in an array of values used as arguments to the sub-program. P2
  66661. ** contains the address to jump to if the sub-program throws an IGNORE
  66662. ** exception using the RAISE() function. Register P3 contains the address
  66663. ** of a memory cell in this (the parent) VM that is used to allocate the
  66664. ** memory required by the sub-vdbe at runtime.
  66665. **
  66666. ** P4 is a pointer to the VM containing the trigger program.
  66667. */
  66668. case OP_Program: { /* jump */
  66669. #if 0 /* local variables moved into u.cd */
  66670. int nMem; /* Number of memory registers for sub-program */
  66671. int nByte; /* Bytes of runtime space required for sub-program */
  66672. Mem *pRt; /* Register to allocate runtime space */
  66673. Mem *pMem; /* Used to iterate through memory cells */
  66674. Mem *pEnd; /* Last memory cell in new array */
  66675. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  66676. SubProgram *pProgram; /* Sub-program to execute */
  66677. void *t; /* Token identifying trigger */
  66678. #endif /* local variables moved into u.cd */
  66679. u.cd.pProgram = pOp->p4.pProgram;
  66680. u.cd.pRt = &aMem[pOp->p3];
  66681. assert( u.cd.pProgram->nOp>0 );
  66682. /* If the p5 flag is clear, then recursive invocation of triggers is
  66683. ** disabled for backwards compatibility (p5 is set if this sub-program
  66684. ** is really a trigger, not a foreign key action, and the flag set
  66685. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  66686. **
  66687. ** It is recursive invocation of triggers, at the SQL level, that is
  66688. ** disabled. In some cases a single trigger may generate more than one
  66689. ** SubProgram (if the trigger may be executed with more than one different
  66690. ** ON CONFLICT algorithm). SubProgram structures associated with a
  66691. ** single trigger all have the same value for the SubProgram.token
  66692. ** variable. */
  66693. if( pOp->p5 ){
  66694. u.cd.t = u.cd.pProgram->token;
  66695. for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
  66696. if( u.cd.pFrame ) break;
  66697. }
  66698. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  66699. rc = SQLITE_ERROR;
  66700. sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
  66701. break;
  66702. }
  66703. /* Register u.cd.pRt is used to store the memory required to save the state
  66704. ** of the current program, and the memory required at runtime to execute
  66705. ** the trigger program. If this trigger has been fired before, then u.cd.pRt
  66706. ** is already allocated. Otherwise, it must be initialized. */
  66707. if( (u.cd.pRt->flags&MEM_Frame)==0 ){
  66708. /* SubProgram.nMem is set to the number of memory cells used by the
  66709. ** program stored in SubProgram.aOp. As well as these, one memory
  66710. ** cell is required for each cursor used by the program. Set local
  66711. ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
  66712. */
  66713. u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
  66714. u.cd.nByte = ROUND8(sizeof(VdbeFrame))
  66715. + u.cd.nMem * sizeof(Mem)
  66716. + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
  66717. + u.cd.pProgram->nOnce * sizeof(u8);
  66718. u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
  66719. if( !u.cd.pFrame ){
  66720. goto no_mem;
  66721. }
  66722. sqlite3VdbeMemRelease(u.cd.pRt);
  66723. u.cd.pRt->flags = MEM_Frame;
  66724. u.cd.pRt->u.pFrame = u.cd.pFrame;
  66725. u.cd.pFrame->v = p;
  66726. u.cd.pFrame->nChildMem = u.cd.nMem;
  66727. u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
  66728. u.cd.pFrame->pc = pc;
  66729. u.cd.pFrame->aMem = p->aMem;
  66730. u.cd.pFrame->nMem = p->nMem;
  66731. u.cd.pFrame->apCsr = p->apCsr;
  66732. u.cd.pFrame->nCursor = p->nCursor;
  66733. u.cd.pFrame->aOp = p->aOp;
  66734. u.cd.pFrame->nOp = p->nOp;
  66735. u.cd.pFrame->token = u.cd.pProgram->token;
  66736. u.cd.pFrame->aOnceFlag = p->aOnceFlag;
  66737. u.cd.pFrame->nOnceFlag = p->nOnceFlag;
  66738. u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
  66739. for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
  66740. u.cd.pMem->flags = MEM_Invalid;
  66741. u.cd.pMem->db = db;
  66742. }
  66743. }else{
  66744. u.cd.pFrame = u.cd.pRt->u.pFrame;
  66745. assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
  66746. assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
  66747. assert( pc==u.cd.pFrame->pc );
  66748. }
  66749. p->nFrame++;
  66750. u.cd.pFrame->pParent = p->pFrame;
  66751. u.cd.pFrame->lastRowid = lastRowid;
  66752. u.cd.pFrame->nChange = p->nChange;
  66753. p->nChange = 0;
  66754. p->pFrame = u.cd.pFrame;
  66755. p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
  66756. p->nMem = u.cd.pFrame->nChildMem;
  66757. p->nCursor = (u16)u.cd.pFrame->nChildCsr;
  66758. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  66759. p->aOp = aOp = u.cd.pProgram->aOp;
  66760. p->nOp = u.cd.pProgram->nOp;
  66761. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  66762. p->nOnceFlag = u.cd.pProgram->nOnce;
  66763. pc = -1;
  66764. memset(p->aOnceFlag, 0, p->nOnceFlag);
  66765. break;
  66766. }
  66767. /* Opcode: Param P1 P2 * * *
  66768. **
  66769. ** This opcode is only ever present in sub-programs called via the
  66770. ** OP_Program instruction. Copy a value currently stored in a memory
  66771. ** cell of the calling (parent) frame to cell P2 in the current frames
  66772. ** address space. This is used by trigger programs to access the new.*
  66773. ** and old.* values.
  66774. **
  66775. ** The address of the cell in the parent frame is determined by adding
  66776. ** the value of the P1 argument to the value of the P1 argument to the
  66777. ** calling OP_Program instruction.
  66778. */
  66779. case OP_Param: { /* out2-prerelease */
  66780. #if 0 /* local variables moved into u.ce */
  66781. VdbeFrame *pFrame;
  66782. Mem *pIn;
  66783. #endif /* local variables moved into u.ce */
  66784. u.ce.pFrame = p->pFrame;
  66785. u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
  66786. sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
  66787. break;
  66788. }
  66789. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  66790. #ifndef SQLITE_OMIT_FOREIGN_KEY
  66791. /* Opcode: FkCounter P1 P2 * * *
  66792. **
  66793. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  66794. ** If P1 is non-zero, the database constraint counter is incremented
  66795. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  66796. ** statement counter is incremented (immediate foreign key constraints).
  66797. */
  66798. case OP_FkCounter: {
  66799. if( db->flags & SQLITE_DeferFKs ){
  66800. db->nDeferredImmCons += pOp->p2;
  66801. }else if( pOp->p1 ){
  66802. db->nDeferredCons += pOp->p2;
  66803. }else{
  66804. p->nFkConstraint += pOp->p2;
  66805. }
  66806. break;
  66807. }
  66808. /* Opcode: FkIfZero P1 P2 * * *
  66809. **
  66810. ** This opcode tests if a foreign key constraint-counter is currently zero.
  66811. ** If so, jump to instruction P2. Otherwise, fall through to the next
  66812. ** instruction.
  66813. **
  66814. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  66815. ** is zero (the one that counts deferred constraint violations). If P1 is
  66816. ** zero, the jump is taken if the statement constraint-counter is zero
  66817. ** (immediate foreign key constraint violations).
  66818. */
  66819. case OP_FkIfZero: { /* jump */
  66820. if( pOp->p1 ){
  66821. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  66822. }else{
  66823. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  66824. }
  66825. break;
  66826. }
  66827. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  66828. #ifndef SQLITE_OMIT_AUTOINCREMENT
  66829. /* Opcode: MemMax P1 P2 * * *
  66830. **
  66831. ** P1 is a register in the root frame of this VM (the root frame is
  66832. ** different from the current frame if this instruction is being executed
  66833. ** within a sub-program). Set the value of register P1 to the maximum of
  66834. ** its current value and the value in register P2.
  66835. **
  66836. ** This instruction throws an error if the memory cell is not initially
  66837. ** an integer.
  66838. */
  66839. case OP_MemMax: { /* in2 */
  66840. #if 0 /* local variables moved into u.cf */
  66841. Mem *pIn1;
  66842. VdbeFrame *pFrame;
  66843. #endif /* local variables moved into u.cf */
  66844. if( p->pFrame ){
  66845. for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
  66846. u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
  66847. }else{
  66848. u.cf.pIn1 = &aMem[pOp->p1];
  66849. }
  66850. assert( memIsValid(u.cf.pIn1) );
  66851. sqlite3VdbeMemIntegerify(u.cf.pIn1);
  66852. pIn2 = &aMem[pOp->p2];
  66853. sqlite3VdbeMemIntegerify(pIn2);
  66854. if( u.cf.pIn1->u.i<pIn2->u.i){
  66855. u.cf.pIn1->u.i = pIn2->u.i;
  66856. }
  66857. break;
  66858. }
  66859. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  66860. /* Opcode: IfPos P1 P2 * * *
  66861. **
  66862. ** If the value of register P1 is 1 or greater, jump to P2.
  66863. **
  66864. ** It is illegal to use this instruction on a register that does
  66865. ** not contain an integer. An assertion fault will result if you try.
  66866. */
  66867. case OP_IfPos: { /* jump, in1 */
  66868. pIn1 = &aMem[pOp->p1];
  66869. assert( pIn1->flags&MEM_Int );
  66870. if( pIn1->u.i>0 ){
  66871. pc = pOp->p2 - 1;
  66872. }
  66873. break;
  66874. }
  66875. /* Opcode: IfNeg P1 P2 * * *
  66876. **
  66877. ** If the value of register P1 is less than zero, jump to P2.
  66878. **
  66879. ** It is illegal to use this instruction on a register that does
  66880. ** not contain an integer. An assertion fault will result if you try.
  66881. */
  66882. case OP_IfNeg: { /* jump, in1 */
  66883. pIn1 = &aMem[pOp->p1];
  66884. assert( pIn1->flags&MEM_Int );
  66885. if( pIn1->u.i<0 ){
  66886. pc = pOp->p2 - 1;
  66887. }
  66888. break;
  66889. }
  66890. /* Opcode: IfZero P1 P2 P3 * *
  66891. **
  66892. ** The register P1 must contain an integer. Add literal P3 to the
  66893. ** value in register P1. If the result is exactly 0, jump to P2.
  66894. **
  66895. ** It is illegal to use this instruction on a register that does
  66896. ** not contain an integer. An assertion fault will result if you try.
  66897. */
  66898. case OP_IfZero: { /* jump, in1 */
  66899. pIn1 = &aMem[pOp->p1];
  66900. assert( pIn1->flags&MEM_Int );
  66901. pIn1->u.i += pOp->p3;
  66902. if( pIn1->u.i==0 ){
  66903. pc = pOp->p2 - 1;
  66904. }
  66905. break;
  66906. }
  66907. /* Opcode: AggStep * P2 P3 P4 P5
  66908. **
  66909. ** Execute the step function for an aggregate. The
  66910. ** function has P5 arguments. P4 is a pointer to the FuncDef
  66911. ** structure that specifies the function. Use register
  66912. ** P3 as the accumulator.
  66913. **
  66914. ** The P5 arguments are taken from register P2 and its
  66915. ** successors.
  66916. */
  66917. case OP_AggStep: {
  66918. #if 0 /* local variables moved into u.cg */
  66919. int n;
  66920. int i;
  66921. Mem *pMem;
  66922. Mem *pRec;
  66923. sqlite3_context ctx;
  66924. sqlite3_value **apVal;
  66925. #endif /* local variables moved into u.cg */
  66926. u.cg.n = pOp->p5;
  66927. assert( u.cg.n>=0 );
  66928. u.cg.pRec = &aMem[pOp->p2];
  66929. u.cg.apVal = p->apArg;
  66930. assert( u.cg.apVal || u.cg.n==0 );
  66931. for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
  66932. assert( memIsValid(u.cg.pRec) );
  66933. u.cg.apVal[u.cg.i] = u.cg.pRec;
  66934. memAboutToChange(p, u.cg.pRec);
  66935. sqlite3VdbeMemStoreType(u.cg.pRec);
  66936. }
  66937. u.cg.ctx.pFunc = pOp->p4.pFunc;
  66938. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  66939. u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
  66940. u.cg.pMem->n++;
  66941. u.cg.ctx.s.flags = MEM_Null;
  66942. u.cg.ctx.s.z = 0;
  66943. u.cg.ctx.s.zMalloc = 0;
  66944. u.cg.ctx.s.xDel = 0;
  66945. u.cg.ctx.s.db = db;
  66946. u.cg.ctx.isError = 0;
  66947. u.cg.ctx.pColl = 0;
  66948. u.cg.ctx.skipFlag = 0;
  66949. if( u.cg.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  66950. assert( pOp>p->aOp );
  66951. assert( pOp[-1].p4type==P4_COLLSEQ );
  66952. assert( pOp[-1].opcode==OP_CollSeq );
  66953. u.cg.ctx.pColl = pOp[-1].p4.pColl;
  66954. }
  66955. (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
  66956. if( u.cg.ctx.isError ){
  66957. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
  66958. rc = u.cg.ctx.isError;
  66959. }
  66960. if( u.cg.ctx.skipFlag ){
  66961. assert( pOp[-1].opcode==OP_CollSeq );
  66962. u.cg.i = pOp[-1].p1;
  66963. if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
  66964. }
  66965. sqlite3VdbeMemRelease(&u.cg.ctx.s);
  66966. break;
  66967. }
  66968. /* Opcode: AggFinal P1 P2 * P4 *
  66969. **
  66970. ** Execute the finalizer function for an aggregate. P1 is
  66971. ** the memory location that is the accumulator for the aggregate.
  66972. **
  66973. ** P2 is the number of arguments that the step function takes and
  66974. ** P4 is a pointer to the FuncDef for this function. The P2
  66975. ** argument is not used by this opcode. It is only there to disambiguate
  66976. ** functions that can take varying numbers of arguments. The
  66977. ** P4 argument is only needed for the degenerate case where
  66978. ** the step function was not previously called.
  66979. */
  66980. case OP_AggFinal: {
  66981. #if 0 /* local variables moved into u.ch */
  66982. Mem *pMem;
  66983. #endif /* local variables moved into u.ch */
  66984. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  66985. u.ch.pMem = &aMem[pOp->p1];
  66986. assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  66987. rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
  66988. if( rc ){
  66989. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
  66990. }
  66991. sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
  66992. UPDATE_MAX_BLOBSIZE(u.ch.pMem);
  66993. if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
  66994. goto too_big;
  66995. }
  66996. break;
  66997. }
  66998. #ifndef SQLITE_OMIT_WAL
  66999. /* Opcode: Checkpoint P1 P2 P3 * *
  67000. **
  67001. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  67002. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
  67003. ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
  67004. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  67005. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  67006. ** in the WAL that have been checkpointed after the checkpoint
  67007. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  67008. ** mem[P3+2] are initialized to -1.
  67009. */
  67010. case OP_Checkpoint: {
  67011. #if 0 /* local variables moved into u.ci */
  67012. int i; /* Loop counter */
  67013. int aRes[3]; /* Results */
  67014. Mem *pMem; /* Write results here */
  67015. #endif /* local variables moved into u.ci */
  67016. assert( p->readOnly==0 );
  67017. u.ci.aRes[0] = 0;
  67018. u.ci.aRes[1] = u.ci.aRes[2] = -1;
  67019. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  67020. || pOp->p2==SQLITE_CHECKPOINT_FULL
  67021. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  67022. );
  67023. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
  67024. if( rc==SQLITE_BUSY ){
  67025. rc = SQLITE_OK;
  67026. u.ci.aRes[0] = 1;
  67027. }
  67028. for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
  67029. sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
  67030. }
  67031. break;
  67032. };
  67033. #endif
  67034. #ifndef SQLITE_OMIT_PRAGMA
  67035. /* Opcode: JournalMode P1 P2 P3 * P5
  67036. **
  67037. ** Change the journal mode of database P1 to P3. P3 must be one of the
  67038. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  67039. ** modes (delete, truncate, persist, off and memory), this is a simple
  67040. ** operation. No IO is required.
  67041. **
  67042. ** If changing into or out of WAL mode the procedure is more complicated.
  67043. **
  67044. ** Write a string containing the final journal-mode to register P2.
  67045. */
  67046. case OP_JournalMode: { /* out2-prerelease */
  67047. #if 0 /* local variables moved into u.cj */
  67048. Btree *pBt; /* Btree to change journal mode of */
  67049. Pager *pPager; /* Pager associated with pBt */
  67050. int eNew; /* New journal mode */
  67051. int eOld; /* The old journal mode */
  67052. #ifndef SQLITE_OMIT_WAL
  67053. const char *zFilename; /* Name of database file for pPager */
  67054. #endif
  67055. #endif /* local variables moved into u.cj */
  67056. u.cj.eNew = pOp->p3;
  67057. assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
  67058. || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
  67059. || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
  67060. || u.cj.eNew==PAGER_JOURNALMODE_OFF
  67061. || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
  67062. || u.cj.eNew==PAGER_JOURNALMODE_WAL
  67063. || u.cj.eNew==PAGER_JOURNALMODE_QUERY
  67064. );
  67065. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67066. assert( p->readOnly==0 );
  67067. u.cj.pBt = db->aDb[pOp->p1].pBt;
  67068. u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
  67069. u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
  67070. if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
  67071. if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
  67072. #ifndef SQLITE_OMIT_WAL
  67073. u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
  67074. /* Do not allow a transition to journal_mode=WAL for a database
  67075. ** in temporary storage or if the VFS does not support shared memory
  67076. */
  67077. if( u.cj.eNew==PAGER_JOURNALMODE_WAL
  67078. && (sqlite3Strlen30(u.cj.zFilename)==0 /* Temp file */
  67079. || !sqlite3PagerWalSupported(u.cj.pPager)) /* No shared-memory support */
  67080. ){
  67081. u.cj.eNew = u.cj.eOld;
  67082. }
  67083. if( (u.cj.eNew!=u.cj.eOld)
  67084. && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
  67085. ){
  67086. if( !db->autoCommit || db->nVdbeRead>1 ){
  67087. rc = SQLITE_ERROR;
  67088. sqlite3SetString(&p->zErrMsg, db,
  67089. "cannot change %s wal mode from within a transaction",
  67090. (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  67091. );
  67092. break;
  67093. }else{
  67094. if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
  67095. /* If leaving WAL mode, close the log file. If successful, the call
  67096. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  67097. ** file. An EXCLUSIVE lock may still be held on the database file
  67098. ** after a successful return.
  67099. */
  67100. rc = sqlite3PagerCloseWal(u.cj.pPager);
  67101. if( rc==SQLITE_OK ){
  67102. sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  67103. }
  67104. }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
  67105. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  67106. ** as an intermediate */
  67107. sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
  67108. }
  67109. /* Open a transaction on the database file. Regardless of the journal
  67110. ** mode, this transaction always uses a rollback journal.
  67111. */
  67112. assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
  67113. if( rc==SQLITE_OK ){
  67114. rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  67115. }
  67116. }
  67117. }
  67118. #endif /* ifndef SQLITE_OMIT_WAL */
  67119. if( rc ){
  67120. u.cj.eNew = u.cj.eOld;
  67121. }
  67122. u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  67123. pOut = &aMem[pOp->p2];
  67124. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  67125. pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
  67126. pOut->n = sqlite3Strlen30(pOut->z);
  67127. pOut->enc = SQLITE_UTF8;
  67128. sqlite3VdbeChangeEncoding(pOut, encoding);
  67129. break;
  67130. };
  67131. #endif /* SQLITE_OMIT_PRAGMA */
  67132. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  67133. /* Opcode: Vacuum * * * * *
  67134. **
  67135. ** Vacuum the entire database. This opcode will cause other virtual
  67136. ** machines to be created and run. It may not be called from within
  67137. ** a transaction.
  67138. */
  67139. case OP_Vacuum: {
  67140. assert( p->readOnly==0 );
  67141. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  67142. break;
  67143. }
  67144. #endif
  67145. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  67146. /* Opcode: IncrVacuum P1 P2 * * *
  67147. **
  67148. ** Perform a single step of the incremental vacuum procedure on
  67149. ** the P1 database. If the vacuum has finished, jump to instruction
  67150. ** P2. Otherwise, fall through to the next instruction.
  67151. */
  67152. case OP_IncrVacuum: { /* jump */
  67153. #if 0 /* local variables moved into u.ck */
  67154. Btree *pBt;
  67155. #endif /* local variables moved into u.ck */
  67156. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67157. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  67158. assert( p->readOnly==0 );
  67159. u.ck.pBt = db->aDb[pOp->p1].pBt;
  67160. rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
  67161. if( rc==SQLITE_DONE ){
  67162. pc = pOp->p2 - 1;
  67163. rc = SQLITE_OK;
  67164. }
  67165. break;
  67166. }
  67167. #endif
  67168. /* Opcode: Expire P1 * * * *
  67169. **
  67170. ** Cause precompiled statements to become expired. An expired statement
  67171. ** fails with an error code of SQLITE_SCHEMA if it is ever executed
  67172. ** (via sqlite3_step()).
  67173. **
  67174. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  67175. ** then only the currently executing statement is affected.
  67176. */
  67177. case OP_Expire: {
  67178. if( !pOp->p1 ){
  67179. sqlite3ExpirePreparedStatements(db);
  67180. }else{
  67181. p->expired = 1;
  67182. }
  67183. break;
  67184. }
  67185. #ifndef SQLITE_OMIT_SHARED_CACHE
  67186. /* Opcode: TableLock P1 P2 P3 P4 *
  67187. **
  67188. ** Obtain a lock on a particular table. This instruction is only used when
  67189. ** the shared-cache feature is enabled.
  67190. **
  67191. ** P1 is the index of the database in sqlite3.aDb[] of the database
  67192. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  67193. ** a write lock if P3==1.
  67194. **
  67195. ** P2 contains the root-page of the table to lock.
  67196. **
  67197. ** P4 contains a pointer to the name of the table being locked. This is only
  67198. ** used to generate an error message if the lock cannot be obtained.
  67199. */
  67200. case OP_TableLock: {
  67201. u8 isWriteLock = (u8)pOp->p3;
  67202. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  67203. int p1 = pOp->p1;
  67204. assert( p1>=0 && p1<db->nDb );
  67205. assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
  67206. assert( isWriteLock==0 || isWriteLock==1 );
  67207. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  67208. if( (rc&0xFF)==SQLITE_LOCKED ){
  67209. const char *z = pOp->p4.z;
  67210. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  67211. }
  67212. }
  67213. break;
  67214. }
  67215. #endif /* SQLITE_OMIT_SHARED_CACHE */
  67216. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67217. /* Opcode: VBegin * * * P4 *
  67218. **
  67219. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  67220. ** xBegin method for that table.
  67221. **
  67222. ** Also, whether or not P4 is set, check that this is not being called from
  67223. ** within a callback to a virtual table xSync() method. If it is, the error
  67224. ** code will be set to SQLITE_LOCKED.
  67225. */
  67226. case OP_VBegin: {
  67227. #if 0 /* local variables moved into u.cl */
  67228. VTable *pVTab;
  67229. #endif /* local variables moved into u.cl */
  67230. u.cl.pVTab = pOp->p4.pVtab;
  67231. rc = sqlite3VtabBegin(db, u.cl.pVTab);
  67232. if( u.cl.pVTab ) sqlite3VtabImportErrmsg(p, u.cl.pVTab->pVtab);
  67233. break;
  67234. }
  67235. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  67236. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67237. /* Opcode: VCreate P1 * * P4 *
  67238. **
  67239. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  67240. ** for that table.
  67241. */
  67242. case OP_VCreate: {
  67243. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  67244. break;
  67245. }
  67246. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  67247. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67248. /* Opcode: VDestroy P1 * * P4 *
  67249. **
  67250. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  67251. ** of that table.
  67252. */
  67253. case OP_VDestroy: {
  67254. p->inVtabMethod = 2;
  67255. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  67256. p->inVtabMethod = 0;
  67257. break;
  67258. }
  67259. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  67260. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67261. /* Opcode: VOpen P1 * * P4 *
  67262. **
  67263. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  67264. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  67265. ** table and stores that cursor in P1.
  67266. */
  67267. case OP_VOpen: {
  67268. #if 0 /* local variables moved into u.cm */
  67269. VdbeCursor *pCur;
  67270. sqlite3_vtab_cursor *pVtabCursor;
  67271. sqlite3_vtab *pVtab;
  67272. sqlite3_module *pModule;
  67273. #endif /* local variables moved into u.cm */
  67274. assert( p->bIsReader );
  67275. u.cm.pCur = 0;
  67276. u.cm.pVtabCursor = 0;
  67277. u.cm.pVtab = pOp->p4.pVtab->pVtab;
  67278. u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
  67279. assert(u.cm.pVtab && u.cm.pModule);
  67280. rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
  67281. sqlite3VtabImportErrmsg(p, u.cm.pVtab);
  67282. if( SQLITE_OK==rc ){
  67283. /* Initialize sqlite3_vtab_cursor base class */
  67284. u.cm.pVtabCursor->pVtab = u.cm.pVtab;
  67285. /* Initialize vdbe cursor object */
  67286. u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  67287. if( u.cm.pCur ){
  67288. u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
  67289. u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
  67290. }else{
  67291. db->mallocFailed = 1;
  67292. u.cm.pModule->xClose(u.cm.pVtabCursor);
  67293. }
  67294. }
  67295. break;
  67296. }
  67297. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  67298. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67299. /* Opcode: VFilter P1 P2 P3 P4 *
  67300. **
  67301. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  67302. ** the filtered result set is empty.
  67303. **
  67304. ** P4 is either NULL or a string that was generated by the xBestIndex
  67305. ** method of the module. The interpretation of the P4 string is left
  67306. ** to the module implementation.
  67307. **
  67308. ** This opcode invokes the xFilter method on the virtual table specified
  67309. ** by P1. The integer query plan parameter to xFilter is stored in register
  67310. ** P3. Register P3+1 stores the argc parameter to be passed to the
  67311. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  67312. ** additional parameters which are passed to
  67313. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  67314. **
  67315. ** A jump is made to P2 if the result set after filtering would be empty.
  67316. */
  67317. case OP_VFilter: { /* jump */
  67318. #if 0 /* local variables moved into u.cn */
  67319. int nArg;
  67320. int iQuery;
  67321. const sqlite3_module *pModule;
  67322. Mem *pQuery;
  67323. Mem *pArgc;
  67324. sqlite3_vtab_cursor *pVtabCursor;
  67325. sqlite3_vtab *pVtab;
  67326. VdbeCursor *pCur;
  67327. int res;
  67328. int i;
  67329. Mem **apArg;
  67330. #endif /* local variables moved into u.cn */
  67331. u.cn.pQuery = &aMem[pOp->p3];
  67332. u.cn.pArgc = &u.cn.pQuery[1];
  67333. u.cn.pCur = p->apCsr[pOp->p1];
  67334. assert( memIsValid(u.cn.pQuery) );
  67335. REGISTER_TRACE(pOp->p3, u.cn.pQuery);
  67336. assert( u.cn.pCur->pVtabCursor );
  67337. u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
  67338. u.cn.pVtab = u.cn.pVtabCursor->pVtab;
  67339. u.cn.pModule = u.cn.pVtab->pModule;
  67340. /* Grab the index number and argc parameters */
  67341. assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
  67342. u.cn.nArg = (int)u.cn.pArgc->u.i;
  67343. u.cn.iQuery = (int)u.cn.pQuery->u.i;
  67344. /* Invoke the xFilter method */
  67345. {
  67346. u.cn.res = 0;
  67347. u.cn.apArg = p->apArg;
  67348. for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
  67349. u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
  67350. sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
  67351. }
  67352. p->inVtabMethod = 1;
  67353. rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
  67354. p->inVtabMethod = 0;
  67355. sqlite3VtabImportErrmsg(p, u.cn.pVtab);
  67356. if( rc==SQLITE_OK ){
  67357. u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
  67358. }
  67359. if( u.cn.res ){
  67360. pc = pOp->p2 - 1;
  67361. }
  67362. }
  67363. u.cn.pCur->nullRow = 0;
  67364. break;
  67365. }
  67366. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  67367. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67368. /* Opcode: VColumn P1 P2 P3 * *
  67369. **
  67370. ** Store the value of the P2-th column of
  67371. ** the row of the virtual-table that the
  67372. ** P1 cursor is pointing to into register P3.
  67373. */
  67374. case OP_VColumn: {
  67375. #if 0 /* local variables moved into u.co */
  67376. sqlite3_vtab *pVtab;
  67377. const sqlite3_module *pModule;
  67378. Mem *pDest;
  67379. sqlite3_context sContext;
  67380. #endif /* local variables moved into u.co */
  67381. VdbeCursor *pCur = p->apCsr[pOp->p1];
  67382. assert( pCur->pVtabCursor );
  67383. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  67384. u.co.pDest = &aMem[pOp->p3];
  67385. memAboutToChange(p, u.co.pDest);
  67386. if( pCur->nullRow ){
  67387. sqlite3VdbeMemSetNull(u.co.pDest);
  67388. break;
  67389. }
  67390. u.co.pVtab = pCur->pVtabCursor->pVtab;
  67391. u.co.pModule = u.co.pVtab->pModule;
  67392. assert( u.co.pModule->xColumn );
  67393. memset(&u.co.sContext, 0, sizeof(u.co.sContext));
  67394. /* The output cell may already have a buffer allocated. Move
  67395. ** the current contents to u.co.sContext.s so in case the user-function
  67396. ** can use the already allocated buffer instead of allocating a
  67397. ** new one.
  67398. */
  67399. sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
  67400. MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
  67401. rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
  67402. sqlite3VtabImportErrmsg(p, u.co.pVtab);
  67403. if( u.co.sContext.isError ){
  67404. rc = u.co.sContext.isError;
  67405. }
  67406. /* Copy the result of the function to the P3 register. We
  67407. ** do this regardless of whether or not an error occurred to ensure any
  67408. ** dynamic allocation in u.co.sContext.s (a Mem struct) is released.
  67409. */
  67410. sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
  67411. sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
  67412. REGISTER_TRACE(pOp->p3, u.co.pDest);
  67413. UPDATE_MAX_BLOBSIZE(u.co.pDest);
  67414. if( sqlite3VdbeMemTooBig(u.co.pDest) ){
  67415. goto too_big;
  67416. }
  67417. break;
  67418. }
  67419. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  67420. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67421. /* Opcode: VNext P1 P2 * * *
  67422. **
  67423. ** Advance virtual table P1 to the next row in its result set and
  67424. ** jump to instruction P2. Or, if the virtual table has reached
  67425. ** the end of its result set, then fall through to the next instruction.
  67426. */
  67427. case OP_VNext: { /* jump */
  67428. #if 0 /* local variables moved into u.cp */
  67429. sqlite3_vtab *pVtab;
  67430. const sqlite3_module *pModule;
  67431. int res;
  67432. VdbeCursor *pCur;
  67433. #endif /* local variables moved into u.cp */
  67434. u.cp.res = 0;
  67435. u.cp.pCur = p->apCsr[pOp->p1];
  67436. assert( u.cp.pCur->pVtabCursor );
  67437. if( u.cp.pCur->nullRow ){
  67438. break;
  67439. }
  67440. u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
  67441. u.cp.pModule = u.cp.pVtab->pModule;
  67442. assert( u.cp.pModule->xNext );
  67443. /* Invoke the xNext() method of the module. There is no way for the
  67444. ** underlying implementation to return an error if one occurs during
  67445. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  67446. ** data is available) and the error code returned when xColumn or
  67447. ** some other method is next invoked on the save virtual table cursor.
  67448. */
  67449. p->inVtabMethod = 1;
  67450. rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
  67451. p->inVtabMethod = 0;
  67452. sqlite3VtabImportErrmsg(p, u.cp.pVtab);
  67453. if( rc==SQLITE_OK ){
  67454. u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
  67455. }
  67456. if( !u.cp.res ){
  67457. /* If there is data, jump to P2 */
  67458. pc = pOp->p2 - 1;
  67459. }
  67460. goto check_for_interrupt;
  67461. }
  67462. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  67463. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67464. /* Opcode: VRename P1 * * P4 *
  67465. **
  67466. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  67467. ** This opcode invokes the corresponding xRename method. The value
  67468. ** in register P1 is passed as the zName argument to the xRename method.
  67469. */
  67470. case OP_VRename: {
  67471. #if 0 /* local variables moved into u.cq */
  67472. sqlite3_vtab *pVtab;
  67473. Mem *pName;
  67474. #endif /* local variables moved into u.cq */
  67475. u.cq.pVtab = pOp->p4.pVtab->pVtab;
  67476. u.cq.pName = &aMem[pOp->p1];
  67477. assert( u.cq.pVtab->pModule->xRename );
  67478. assert( memIsValid(u.cq.pName) );
  67479. assert( p->readOnly==0 );
  67480. REGISTER_TRACE(pOp->p1, u.cq.pName);
  67481. assert( u.cq.pName->flags & MEM_Str );
  67482. testcase( u.cq.pName->enc==SQLITE_UTF8 );
  67483. testcase( u.cq.pName->enc==SQLITE_UTF16BE );
  67484. testcase( u.cq.pName->enc==SQLITE_UTF16LE );
  67485. rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
  67486. if( rc==SQLITE_OK ){
  67487. rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
  67488. sqlite3VtabImportErrmsg(p, u.cq.pVtab);
  67489. p->expired = 0;
  67490. }
  67491. break;
  67492. }
  67493. #endif
  67494. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67495. /* Opcode: VUpdate P1 P2 P3 P4 *
  67496. **
  67497. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  67498. ** This opcode invokes the corresponding xUpdate method. P2 values
  67499. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  67500. ** invocation. The value in register (P3+P2-1) corresponds to the
  67501. ** p2th element of the argv array passed to xUpdate.
  67502. **
  67503. ** The xUpdate method will do a DELETE or an INSERT or both.
  67504. ** The argv[0] element (which corresponds to memory cell P3)
  67505. ** is the rowid of a row to delete. If argv[0] is NULL then no
  67506. ** deletion occurs. The argv[1] element is the rowid of the new
  67507. ** row. This can be NULL to have the virtual table select the new
  67508. ** rowid for itself. The subsequent elements in the array are
  67509. ** the values of columns in the new row.
  67510. **
  67511. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  67512. ** a row to delete.
  67513. **
  67514. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  67515. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  67516. ** is set to the value of the rowid for the row just inserted.
  67517. */
  67518. case OP_VUpdate: {
  67519. #if 0 /* local variables moved into u.cr */
  67520. sqlite3_vtab *pVtab;
  67521. sqlite3_module *pModule;
  67522. int nArg;
  67523. int i;
  67524. sqlite_int64 rowid;
  67525. Mem **apArg;
  67526. Mem *pX;
  67527. #endif /* local variables moved into u.cr */
  67528. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  67529. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  67530. );
  67531. assert( p->readOnly==0 );
  67532. u.cr.pVtab = pOp->p4.pVtab->pVtab;
  67533. u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
  67534. u.cr.nArg = pOp->p2;
  67535. assert( pOp->p4type==P4_VTAB );
  67536. if( ALWAYS(u.cr.pModule->xUpdate) ){
  67537. u8 vtabOnConflict = db->vtabOnConflict;
  67538. u.cr.apArg = p->apArg;
  67539. u.cr.pX = &aMem[pOp->p3];
  67540. for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
  67541. assert( memIsValid(u.cr.pX) );
  67542. memAboutToChange(p, u.cr.pX);
  67543. sqlite3VdbeMemStoreType(u.cr.pX);
  67544. u.cr.apArg[u.cr.i] = u.cr.pX;
  67545. u.cr.pX++;
  67546. }
  67547. db->vtabOnConflict = pOp->p5;
  67548. rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
  67549. db->vtabOnConflict = vtabOnConflict;
  67550. sqlite3VtabImportErrmsg(p, u.cr.pVtab);
  67551. if( rc==SQLITE_OK && pOp->p1 ){
  67552. assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
  67553. db->lastRowid = lastRowid = u.cr.rowid;
  67554. }
  67555. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  67556. if( pOp->p5==OE_Ignore ){
  67557. rc = SQLITE_OK;
  67558. }else{
  67559. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  67560. }
  67561. }else{
  67562. p->nChange++;
  67563. }
  67564. }
  67565. break;
  67566. }
  67567. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  67568. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  67569. /* Opcode: Pagecount P1 P2 * * *
  67570. **
  67571. ** Write the current number of pages in database P1 to memory cell P2.
  67572. */
  67573. case OP_Pagecount: { /* out2-prerelease */
  67574. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  67575. break;
  67576. }
  67577. #endif
  67578. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  67579. /* Opcode: MaxPgcnt P1 P2 P3 * *
  67580. **
  67581. ** Try to set the maximum page count for database P1 to the value in P3.
  67582. ** Do not let the maximum page count fall below the current page count and
  67583. ** do not change the maximum page count value if P3==0.
  67584. **
  67585. ** Store the maximum page count after the change in register P2.
  67586. */
  67587. case OP_MaxPgcnt: { /* out2-prerelease */
  67588. unsigned int newMax;
  67589. Btree *pBt;
  67590. pBt = db->aDb[pOp->p1].pBt;
  67591. newMax = 0;
  67592. if( pOp->p3 ){
  67593. newMax = sqlite3BtreeLastPage(pBt);
  67594. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  67595. }
  67596. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  67597. break;
  67598. }
  67599. #endif
  67600. #ifndef SQLITE_OMIT_TRACE
  67601. /* Opcode: Trace * * * P4 *
  67602. **
  67603. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  67604. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  67605. */
  67606. case OP_Trace: {
  67607. #if 0 /* local variables moved into u.cs */
  67608. char *zTrace;
  67609. char *z;
  67610. #endif /* local variables moved into u.cs */
  67611. if( db->xTrace
  67612. && !p->doingRerun
  67613. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  67614. ){
  67615. u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
  67616. db->xTrace(db->pTraceArg, u.cs.z);
  67617. sqlite3DbFree(db, u.cs.z);
  67618. }
  67619. #ifdef SQLITE_DEBUG
  67620. if( (db->flags & SQLITE_SqlTrace)!=0
  67621. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  67622. ){
  67623. sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
  67624. }
  67625. #endif /* SQLITE_DEBUG */
  67626. break;
  67627. }
  67628. #endif
  67629. /* Opcode: Noop * * * * *
  67630. **
  67631. ** Do nothing. This instruction is often useful as a jump
  67632. ** destination.
  67633. */
  67634. /*
  67635. ** The magic Explain opcode are only inserted when explain==2 (which
  67636. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  67637. ** This opcode records information from the optimizer. It is the
  67638. ** the same as a no-op. This opcodesnever appears in a real VM program.
  67639. */
  67640. default: { /* This is really OP_Noop and OP_Explain */
  67641. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  67642. break;
  67643. }
  67644. /*****************************************************************************
  67645. ** The cases of the switch statement above this line should all be indented
  67646. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  67647. ** readability. From this point on down, the normal indentation rules are
  67648. ** restored.
  67649. *****************************************************************************/
  67650. }
  67651. #ifdef VDBE_PROFILE
  67652. {
  67653. u64 elapsed = sqlite3Hwtime() - start;
  67654. pOp->cycles += elapsed;
  67655. pOp->cnt++;
  67656. #if 0
  67657. fprintf(stdout, "%10llu ", elapsed);
  67658. sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
  67659. #endif
  67660. }
  67661. #endif
  67662. /* The following code adds nothing to the actual functionality
  67663. ** of the program. It is only here for testing and debugging.
  67664. ** On the other hand, it does burn CPU cycles every time through
  67665. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  67666. */
  67667. #ifndef NDEBUG
  67668. assert( pc>=-1 && pc<p->nOp );
  67669. #ifdef SQLITE_DEBUG
  67670. if( p->trace ){
  67671. if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
  67672. if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
  67673. registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
  67674. }
  67675. if( pOp->opflags & OPFLG_OUT3 ){
  67676. registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
  67677. }
  67678. }
  67679. #endif /* SQLITE_DEBUG */
  67680. #endif /* NDEBUG */
  67681. } /* The end of the for(;;) loop the loops through opcodes */
  67682. /* If we reach this point, it means that execution is finished with
  67683. ** an error of some kind.
  67684. */
  67685. vdbe_error_halt:
  67686. assert( rc );
  67687. p->rc = rc;
  67688. testcase( sqlite3GlobalConfig.xLog!=0 );
  67689. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  67690. pc, p->zSql, p->zErrMsg);
  67691. sqlite3VdbeHalt(p);
  67692. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  67693. rc = SQLITE_ERROR;
  67694. if( resetSchemaOnFault>0 ){
  67695. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  67696. }
  67697. /* This is the only way out of this procedure. We have to
  67698. ** release the mutexes on btrees that were acquired at the
  67699. ** top. */
  67700. vdbe_return:
  67701. db->lastRowid = lastRowid;
  67702. testcase( nVmStep>0 );
  67703. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  67704. sqlite3VdbeLeave(p);
  67705. return rc;
  67706. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  67707. ** is encountered.
  67708. */
  67709. too_big:
  67710. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  67711. rc = SQLITE_TOOBIG;
  67712. goto vdbe_error_halt;
  67713. /* Jump to here if a malloc() fails.
  67714. */
  67715. no_mem:
  67716. db->mallocFailed = 1;
  67717. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  67718. rc = SQLITE_NOMEM;
  67719. goto vdbe_error_halt;
  67720. /* Jump to here for any other kind of fatal error. The "rc" variable
  67721. ** should hold the error number.
  67722. */
  67723. abort_due_to_error:
  67724. assert( p->zErrMsg==0 );
  67725. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  67726. if( rc!=SQLITE_IOERR_NOMEM ){
  67727. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  67728. }
  67729. goto vdbe_error_halt;
  67730. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  67731. ** flag.
  67732. */
  67733. abort_due_to_interrupt:
  67734. assert( db->u1.isInterrupted );
  67735. rc = SQLITE_INTERRUPT;
  67736. p->rc = rc;
  67737. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  67738. goto vdbe_error_halt;
  67739. }
  67740. /************** End of vdbe.c ************************************************/
  67741. /************** Begin file vdbeblob.c ****************************************/
  67742. /*
  67743. ** 2007 May 1
  67744. **
  67745. ** The author disclaims copyright to this source code. In place of
  67746. ** a legal notice, here is a blessing:
  67747. **
  67748. ** May you do good and not evil.
  67749. ** May you find forgiveness for yourself and forgive others.
  67750. ** May you share freely, never taking more than you give.
  67751. **
  67752. *************************************************************************
  67753. **
  67754. ** This file contains code used to implement incremental BLOB I/O.
  67755. */
  67756. #ifndef SQLITE_OMIT_INCRBLOB
  67757. /*
  67758. ** Valid sqlite3_blob* handles point to Incrblob structures.
  67759. */
  67760. typedef struct Incrblob Incrblob;
  67761. struct Incrblob {
  67762. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  67763. int nByte; /* Size of open blob, in bytes */
  67764. int iOffset; /* Byte offset of blob in cursor data */
  67765. int iCol; /* Table column this handle is open on */
  67766. BtCursor *pCsr; /* Cursor pointing at blob row */
  67767. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  67768. sqlite3 *db; /* The associated database */
  67769. };
  67770. /*
  67771. ** This function is used by both blob_open() and blob_reopen(). It seeks
  67772. ** the b-tree cursor associated with blob handle p to point to row iRow.
  67773. ** If successful, SQLITE_OK is returned and subsequent calls to
  67774. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  67775. **
  67776. ** If an error occurs, or if the specified row does not exist or does not
  67777. ** contain a value of type TEXT or BLOB in the column nominated when the
  67778. ** blob handle was opened, then an error code is returned and *pzErr may
  67779. ** be set to point to a buffer containing an error message. It is the
  67780. ** responsibility of the caller to free the error message buffer using
  67781. ** sqlite3DbFree().
  67782. **
  67783. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  67784. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  67785. ** immediately return SQLITE_ABORT.
  67786. */
  67787. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  67788. int rc; /* Error code */
  67789. char *zErr = 0; /* Error message */
  67790. Vdbe *v = (Vdbe *)p->pStmt;
  67791. /* Set the value of the SQL statements only variable to integer iRow.
  67792. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  67793. ** triggering asserts related to mutexes.
  67794. */
  67795. assert( v->aVar[0].flags&MEM_Int );
  67796. v->aVar[0].u.i = iRow;
  67797. rc = sqlite3_step(p->pStmt);
  67798. if( rc==SQLITE_ROW ){
  67799. u32 type = v->apCsr[0]->aType[p->iCol];
  67800. if( type<12 ){
  67801. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  67802. type==0?"null": type==7?"real": "integer"
  67803. );
  67804. rc = SQLITE_ERROR;
  67805. sqlite3_finalize(p->pStmt);
  67806. p->pStmt = 0;
  67807. }else{
  67808. p->iOffset = v->apCsr[0]->aOffset[p->iCol];
  67809. p->nByte = sqlite3VdbeSerialTypeLen(type);
  67810. p->pCsr = v->apCsr[0]->pCursor;
  67811. sqlite3BtreeEnterCursor(p->pCsr);
  67812. sqlite3BtreeCacheOverflow(p->pCsr);
  67813. sqlite3BtreeLeaveCursor(p->pCsr);
  67814. }
  67815. }
  67816. if( rc==SQLITE_ROW ){
  67817. rc = SQLITE_OK;
  67818. }else if( p->pStmt ){
  67819. rc = sqlite3_finalize(p->pStmt);
  67820. p->pStmt = 0;
  67821. if( rc==SQLITE_OK ){
  67822. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  67823. rc = SQLITE_ERROR;
  67824. }else{
  67825. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  67826. }
  67827. }
  67828. assert( rc!=SQLITE_OK || zErr==0 );
  67829. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  67830. *pzErr = zErr;
  67831. return rc;
  67832. }
  67833. /*
  67834. ** Open a blob handle.
  67835. */
  67836. SQLITE_API int sqlite3_blob_open(
  67837. sqlite3* db, /* The database connection */
  67838. const char *zDb, /* The attached database containing the blob */
  67839. const char *zTable, /* The table containing the blob */
  67840. const char *zColumn, /* The column containing the blob */
  67841. sqlite_int64 iRow, /* The row containing the glob */
  67842. int flags, /* True -> read/write access, false -> read-only */
  67843. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  67844. ){
  67845. int nAttempt = 0;
  67846. int iCol; /* Index of zColumn in row-record */
  67847. /* This VDBE program seeks a btree cursor to the identified
  67848. ** db/table/row entry. The reason for using a vdbe program instead
  67849. ** of writing code to use the b-tree layer directly is that the
  67850. ** vdbe program will take advantage of the various transaction,
  67851. ** locking and error handling infrastructure built into the vdbe.
  67852. **
  67853. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  67854. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  67855. ** uses it to implement the blob_read(), blob_write() and
  67856. ** blob_bytes() functions.
  67857. **
  67858. ** The sqlite3_blob_close() function finalizes the vdbe program,
  67859. ** which closes the b-tree cursor and (possibly) commits the
  67860. ** transaction.
  67861. */
  67862. static const VdbeOpList openBlob[] = {
  67863. {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
  67864. {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
  67865. {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
  67866. /* One of the following two instructions is replaced by an OP_Noop. */
  67867. {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
  67868. {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
  67869. {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
  67870. {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
  67871. {OP_Column, 0, 0, 1}, /* 7 */
  67872. {OP_ResultRow, 1, 0, 0}, /* 8 */
  67873. {OP_Goto, 0, 5, 0}, /* 9 */
  67874. {OP_Close, 0, 0, 0}, /* 10 */
  67875. {OP_Halt, 0, 0, 0}, /* 11 */
  67876. };
  67877. int rc = SQLITE_OK;
  67878. char *zErr = 0;
  67879. Table *pTab;
  67880. Parse *pParse = 0;
  67881. Incrblob *pBlob = 0;
  67882. flags = !!flags; /* flags = (flags ? 1 : 0); */
  67883. *ppBlob = 0;
  67884. sqlite3_mutex_enter(db->mutex);
  67885. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  67886. if( !pBlob ) goto blob_open_out;
  67887. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  67888. if( !pParse ) goto blob_open_out;
  67889. do {
  67890. memset(pParse, 0, sizeof(Parse));
  67891. pParse->db = db;
  67892. sqlite3DbFree(db, zErr);
  67893. zErr = 0;
  67894. sqlite3BtreeEnterAll(db);
  67895. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  67896. if( pTab && IsVirtual(pTab) ){
  67897. pTab = 0;
  67898. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  67899. }
  67900. #ifndef SQLITE_OMIT_VIEW
  67901. if( pTab && pTab->pSelect ){
  67902. pTab = 0;
  67903. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  67904. }
  67905. #endif
  67906. if( !pTab ){
  67907. if( pParse->zErrMsg ){
  67908. sqlite3DbFree(db, zErr);
  67909. zErr = pParse->zErrMsg;
  67910. pParse->zErrMsg = 0;
  67911. }
  67912. rc = SQLITE_ERROR;
  67913. sqlite3BtreeLeaveAll(db);
  67914. goto blob_open_out;
  67915. }
  67916. /* Now search pTab for the exact column. */
  67917. for(iCol=0; iCol<pTab->nCol; iCol++) {
  67918. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  67919. break;
  67920. }
  67921. }
  67922. if( iCol==pTab->nCol ){
  67923. sqlite3DbFree(db, zErr);
  67924. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  67925. rc = SQLITE_ERROR;
  67926. sqlite3BtreeLeaveAll(db);
  67927. goto blob_open_out;
  67928. }
  67929. /* If the value is being opened for writing, check that the
  67930. ** column is not indexed, and that it is not part of a foreign key.
  67931. ** It is against the rules to open a column to which either of these
  67932. ** descriptions applies for writing. */
  67933. if( flags ){
  67934. const char *zFault = 0;
  67935. Index *pIdx;
  67936. #ifndef SQLITE_OMIT_FOREIGN_KEY
  67937. if( db->flags&SQLITE_ForeignKeys ){
  67938. /* Check that the column is not part of an FK child key definition. It
  67939. ** is not necessary to check if it is part of a parent key, as parent
  67940. ** key columns must be indexed. The check below will pick up this
  67941. ** case. */
  67942. FKey *pFKey;
  67943. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  67944. int j;
  67945. for(j=0; j<pFKey->nCol; j++){
  67946. if( pFKey->aCol[j].iFrom==iCol ){
  67947. zFault = "foreign key";
  67948. }
  67949. }
  67950. }
  67951. }
  67952. #endif
  67953. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  67954. int j;
  67955. for(j=0; j<pIdx->nColumn; j++){
  67956. if( pIdx->aiColumn[j]==iCol ){
  67957. zFault = "indexed";
  67958. }
  67959. }
  67960. }
  67961. if( zFault ){
  67962. sqlite3DbFree(db, zErr);
  67963. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  67964. rc = SQLITE_ERROR;
  67965. sqlite3BtreeLeaveAll(db);
  67966. goto blob_open_out;
  67967. }
  67968. }
  67969. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
  67970. assert( pBlob->pStmt || db->mallocFailed );
  67971. if( pBlob->pStmt ){
  67972. Vdbe *v = (Vdbe *)pBlob->pStmt;
  67973. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  67974. sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
  67975. /* Configure the OP_Transaction */
  67976. sqlite3VdbeChangeP1(v, 0, iDb);
  67977. sqlite3VdbeChangeP2(v, 0, flags);
  67978. /* Configure the OP_VerifyCookie */
  67979. sqlite3VdbeChangeP1(v, 1, iDb);
  67980. sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
  67981. sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
  67982. /* Make sure a mutex is held on the table to be accessed */
  67983. sqlite3VdbeUsesBtree(v, iDb);
  67984. /* Configure the OP_TableLock instruction */
  67985. #ifdef SQLITE_OMIT_SHARED_CACHE
  67986. sqlite3VdbeChangeToNoop(v, 2);
  67987. #else
  67988. sqlite3VdbeChangeP1(v, 2, iDb);
  67989. sqlite3VdbeChangeP2(v, 2, pTab->tnum);
  67990. sqlite3VdbeChangeP3(v, 2, flags);
  67991. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  67992. #endif
  67993. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  67994. ** parameter of the other to pTab->tnum. */
  67995. sqlite3VdbeChangeToNoop(v, 4 - flags);
  67996. sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
  67997. sqlite3VdbeChangeP3(v, 3 + flags, iDb);
  67998. /* Configure the number of columns. Configure the cursor to
  67999. ** think that the table has one more column than it really
  68000. ** does. An OP_Column to retrieve this imaginary column will
  68001. ** always return an SQL NULL. This is useful because it means
  68002. ** we can invoke OP_Column to fill in the vdbe cursors type
  68003. ** and offset cache without causing any IO.
  68004. */
  68005. sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  68006. sqlite3VdbeChangeP2(v, 7, pTab->nCol);
  68007. if( !db->mallocFailed ){
  68008. pParse->nVar = 1;
  68009. pParse->nMem = 1;
  68010. pParse->nTab = 1;
  68011. sqlite3VdbeMakeReady(v, pParse);
  68012. }
  68013. }
  68014. pBlob->flags = flags;
  68015. pBlob->iCol = iCol;
  68016. pBlob->db = db;
  68017. sqlite3BtreeLeaveAll(db);
  68018. if( db->mallocFailed ){
  68019. goto blob_open_out;
  68020. }
  68021. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  68022. rc = blobSeekToRow(pBlob, iRow, &zErr);
  68023. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  68024. blob_open_out:
  68025. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  68026. *ppBlob = (sqlite3_blob *)pBlob;
  68027. }else{
  68028. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  68029. sqlite3DbFree(db, pBlob);
  68030. }
  68031. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  68032. sqlite3DbFree(db, zErr);
  68033. sqlite3StackFree(db, pParse);
  68034. rc = sqlite3ApiExit(db, rc);
  68035. sqlite3_mutex_leave(db->mutex);
  68036. return rc;
  68037. }
  68038. /*
  68039. ** Close a blob handle that was previously created using
  68040. ** sqlite3_blob_open().
  68041. */
  68042. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  68043. Incrblob *p = (Incrblob *)pBlob;
  68044. int rc;
  68045. sqlite3 *db;
  68046. if( p ){
  68047. db = p->db;
  68048. sqlite3_mutex_enter(db->mutex);
  68049. rc = sqlite3_finalize(p->pStmt);
  68050. sqlite3DbFree(db, p);
  68051. sqlite3_mutex_leave(db->mutex);
  68052. }else{
  68053. rc = SQLITE_OK;
  68054. }
  68055. return rc;
  68056. }
  68057. /*
  68058. ** Perform a read or write operation on a blob
  68059. */
  68060. static int blobReadWrite(
  68061. sqlite3_blob *pBlob,
  68062. void *z,
  68063. int n,
  68064. int iOffset,
  68065. int (*xCall)(BtCursor*, u32, u32, void*)
  68066. ){
  68067. int rc;
  68068. Incrblob *p = (Incrblob *)pBlob;
  68069. Vdbe *v;
  68070. sqlite3 *db;
  68071. if( p==0 ) return SQLITE_MISUSE_BKPT;
  68072. db = p->db;
  68073. sqlite3_mutex_enter(db->mutex);
  68074. v = (Vdbe*)p->pStmt;
  68075. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  68076. /* Request is out of range. Return a transient error. */
  68077. rc = SQLITE_ERROR;
  68078. sqlite3Error(db, SQLITE_ERROR, 0);
  68079. }else if( v==0 ){
  68080. /* If there is no statement handle, then the blob-handle has
  68081. ** already been invalidated. Return SQLITE_ABORT in this case.
  68082. */
  68083. rc = SQLITE_ABORT;
  68084. }else{
  68085. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  68086. ** returned, clean-up the statement handle.
  68087. */
  68088. assert( db == v->db );
  68089. sqlite3BtreeEnterCursor(p->pCsr);
  68090. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  68091. sqlite3BtreeLeaveCursor(p->pCsr);
  68092. if( rc==SQLITE_ABORT ){
  68093. sqlite3VdbeFinalize(v);
  68094. p->pStmt = 0;
  68095. }else{
  68096. db->errCode = rc;
  68097. v->rc = rc;
  68098. }
  68099. }
  68100. rc = sqlite3ApiExit(db, rc);
  68101. sqlite3_mutex_leave(db->mutex);
  68102. return rc;
  68103. }
  68104. /*
  68105. ** Read data from a blob handle.
  68106. */
  68107. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  68108. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  68109. }
  68110. /*
  68111. ** Write data to a blob handle.
  68112. */
  68113. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  68114. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  68115. }
  68116. /*
  68117. ** Query a blob handle for the size of the data.
  68118. **
  68119. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  68120. ** so no mutex is required for access.
  68121. */
  68122. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  68123. Incrblob *p = (Incrblob *)pBlob;
  68124. return (p && p->pStmt) ? p->nByte : 0;
  68125. }
  68126. /*
  68127. ** Move an existing blob handle to point to a different row of the same
  68128. ** database table.
  68129. **
  68130. ** If an error occurs, or if the specified row does not exist or does not
  68131. ** contain a blob or text value, then an error code is returned and the
  68132. ** database handle error code and message set. If this happens, then all
  68133. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  68134. ** immediately return SQLITE_ABORT.
  68135. */
  68136. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  68137. int rc;
  68138. Incrblob *p = (Incrblob *)pBlob;
  68139. sqlite3 *db;
  68140. if( p==0 ) return SQLITE_MISUSE_BKPT;
  68141. db = p->db;
  68142. sqlite3_mutex_enter(db->mutex);
  68143. if( p->pStmt==0 ){
  68144. /* If there is no statement handle, then the blob-handle has
  68145. ** already been invalidated. Return SQLITE_ABORT in this case.
  68146. */
  68147. rc = SQLITE_ABORT;
  68148. }else{
  68149. char *zErr;
  68150. rc = blobSeekToRow(p, iRow, &zErr);
  68151. if( rc!=SQLITE_OK ){
  68152. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  68153. sqlite3DbFree(db, zErr);
  68154. }
  68155. assert( rc!=SQLITE_SCHEMA );
  68156. }
  68157. rc = sqlite3ApiExit(db, rc);
  68158. assert( rc==SQLITE_OK || p->pStmt==0 );
  68159. sqlite3_mutex_leave(db->mutex);
  68160. return rc;
  68161. }
  68162. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  68163. /************** End of vdbeblob.c ********************************************/
  68164. /************** Begin file vdbesort.c ****************************************/
  68165. /*
  68166. ** 2011 July 9
  68167. **
  68168. ** The author disclaims copyright to this source code. In place of
  68169. ** a legal notice, here is a blessing:
  68170. **
  68171. ** May you do good and not evil.
  68172. ** May you find forgiveness for yourself and forgive others.
  68173. ** May you share freely, never taking more than you give.
  68174. **
  68175. *************************************************************************
  68176. ** This file contains code for the VdbeSorter object, used in concert with
  68177. ** a VdbeCursor to sort large numbers of keys (as may be required, for
  68178. ** example, by CREATE INDEX statements on tables too large to fit in main
  68179. ** memory).
  68180. */
  68181. typedef struct VdbeSorterIter VdbeSorterIter;
  68182. typedef struct SorterRecord SorterRecord;
  68183. typedef struct FileWriter FileWriter;
  68184. /*
  68185. ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
  68186. **
  68187. ** As keys are added to the sorter, they are written to disk in a series
  68188. ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
  68189. ** the same as the cache-size allowed for temporary databases. In order
  68190. ** to allow the caller to extract keys from the sorter in sorted order,
  68191. ** all PMAs currently stored on disk must be merged together. This comment
  68192. ** describes the data structure used to do so. The structure supports
  68193. ** merging any number of arrays in a single pass with no redundant comparison
  68194. ** operations.
  68195. **
  68196. ** The aIter[] array contains an iterator for each of the PMAs being merged.
  68197. ** An aIter[] iterator either points to a valid key or else is at EOF. For
  68198. ** the purposes of the paragraphs below, we assume that the array is actually
  68199. ** N elements in size, where N is the smallest power of 2 greater to or equal
  68200. ** to the number of iterators being merged. The extra aIter[] elements are
  68201. ** treated as if they are empty (always at EOF).
  68202. **
  68203. ** The aTree[] array is also N elements in size. The value of N is stored in
  68204. ** the VdbeSorter.nTree variable.
  68205. **
  68206. ** The final (N/2) elements of aTree[] contain the results of comparing
  68207. ** pairs of iterator keys together. Element i contains the result of
  68208. ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
  68209. ** aTree element is set to the index of it.
  68210. **
  68211. ** For the purposes of this comparison, EOF is considered greater than any
  68212. ** other key value. If the keys are equal (only possible with two EOF
  68213. ** values), it doesn't matter which index is stored.
  68214. **
  68215. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  68216. ** above contains the index of the smallest of each block of 4 iterators.
  68217. ** And so on. So that aTree[1] contains the index of the iterator that
  68218. ** currently points to the smallest key value. aTree[0] is unused.
  68219. **
  68220. ** Example:
  68221. **
  68222. ** aIter[0] -> Banana
  68223. ** aIter[1] -> Feijoa
  68224. ** aIter[2] -> Elderberry
  68225. ** aIter[3] -> Currant
  68226. ** aIter[4] -> Grapefruit
  68227. ** aIter[5] -> Apple
  68228. ** aIter[6] -> Durian
  68229. ** aIter[7] -> EOF
  68230. **
  68231. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  68232. **
  68233. ** The current element is "Apple" (the value of the key indicated by
  68234. ** iterator 5). When the Next() operation is invoked, iterator 5 will
  68235. ** be advanced to the next key in its segment. Say the next key is
  68236. ** "Eggplant":
  68237. **
  68238. ** aIter[5] -> Eggplant
  68239. **
  68240. ** The contents of aTree[] are updated first by comparing the new iterator
  68241. ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
  68242. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  68243. ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
  68244. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  68245. ** so the value written into element 1 of the array is 0. As follows:
  68246. **
  68247. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  68248. **
  68249. ** In other words, each time we advance to the next sorter element, log2(N)
  68250. ** key comparison operations are required, where N is the number of segments
  68251. ** being merged (rounded up to the next power of 2).
  68252. */
  68253. struct VdbeSorter {
  68254. i64 iWriteOff; /* Current write offset within file pTemp1 */
  68255. i64 iReadOff; /* Current read offset within file pTemp1 */
  68256. int nInMemory; /* Current size of pRecord list as PMA */
  68257. int nTree; /* Used size of aTree/aIter (power of 2) */
  68258. int nPMA; /* Number of PMAs stored in pTemp1 */
  68259. int mnPmaSize; /* Minimum PMA size, in bytes */
  68260. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  68261. VdbeSorterIter *aIter; /* Array of iterators to merge */
  68262. int *aTree; /* Current state of incremental merge */
  68263. sqlite3_file *pTemp1; /* PMA file 1 */
  68264. SorterRecord *pRecord; /* Head of in-memory record list */
  68265. UnpackedRecord *pUnpacked; /* Used to unpack keys */
  68266. };
  68267. /*
  68268. ** The following type is an iterator for a PMA. It caches the current key in
  68269. ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
  68270. */
  68271. struct VdbeSorterIter {
  68272. i64 iReadOff; /* Current read offset */
  68273. i64 iEof; /* 1 byte past EOF for this iterator */
  68274. int nAlloc; /* Bytes of space at aAlloc */
  68275. int nKey; /* Number of bytes in key */
  68276. sqlite3_file *pFile; /* File iterator is reading from */
  68277. u8 *aAlloc; /* Allocated space */
  68278. u8 *aKey; /* Pointer to current key */
  68279. u8 *aBuffer; /* Current read buffer */
  68280. int nBuffer; /* Size of read buffer in bytes */
  68281. };
  68282. /*
  68283. ** An instance of this structure is used to organize the stream of records
  68284. ** being written to files by the merge-sort code into aligned, page-sized
  68285. ** blocks. Doing all I/O in aligned page-sized blocks helps I/O to go
  68286. ** faster on many operating systems.
  68287. */
  68288. struct FileWriter {
  68289. int eFWErr; /* Non-zero if in an error state */
  68290. u8 *aBuffer; /* Pointer to write buffer */
  68291. int nBuffer; /* Size of write buffer in bytes */
  68292. int iBufStart; /* First byte of buffer to write */
  68293. int iBufEnd; /* Last byte of buffer to write */
  68294. i64 iWriteOff; /* Offset of start of buffer in file */
  68295. sqlite3_file *pFile; /* File to write to */
  68296. };
  68297. /*
  68298. ** A structure to store a single record. All in-memory records are connected
  68299. ** together into a linked list headed at VdbeSorter.pRecord using the
  68300. ** SorterRecord.pNext pointer.
  68301. */
  68302. struct SorterRecord {
  68303. void *pVal;
  68304. int nVal;
  68305. SorterRecord *pNext;
  68306. };
  68307. /* Minimum allowable value for the VdbeSorter.nWorking variable */
  68308. #define SORTER_MIN_WORKING 10
  68309. /* Maximum number of segments to merge in a single pass. */
  68310. #define SORTER_MAX_MERGE_COUNT 16
  68311. /*
  68312. ** Free all memory belonging to the VdbeSorterIter object passed as the second
  68313. ** argument. All structure fields are set to zero before returning.
  68314. */
  68315. static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
  68316. sqlite3DbFree(db, pIter->aAlloc);
  68317. sqlite3DbFree(db, pIter->aBuffer);
  68318. memset(pIter, 0, sizeof(VdbeSorterIter));
  68319. }
  68320. /*
  68321. ** Read nByte bytes of data from the stream of data iterated by object p.
  68322. ** If successful, set *ppOut to point to a buffer containing the data
  68323. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  68324. ** error code.
  68325. **
  68326. ** The buffer indicated by *ppOut may only be considered valid until the
  68327. ** next call to this function.
  68328. */
  68329. static int vdbeSorterIterRead(
  68330. sqlite3 *db, /* Database handle (for malloc) */
  68331. VdbeSorterIter *p, /* Iterator */
  68332. int nByte, /* Bytes of data to read */
  68333. u8 **ppOut /* OUT: Pointer to buffer containing data */
  68334. ){
  68335. int iBuf; /* Offset within buffer to read from */
  68336. int nAvail; /* Bytes of data available in buffer */
  68337. assert( p->aBuffer );
  68338. /* If there is no more data to be read from the buffer, read the next
  68339. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  68340. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  68341. iBuf = p->iReadOff % p->nBuffer;
  68342. if( iBuf==0 ){
  68343. int nRead; /* Bytes to read from disk */
  68344. int rc; /* sqlite3OsRead() return code */
  68345. /* Determine how many bytes of data to read. */
  68346. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  68347. nRead = p->nBuffer;
  68348. }else{
  68349. nRead = (int)(p->iEof - p->iReadOff);
  68350. }
  68351. assert( nRead>0 );
  68352. /* Read data from the file. Return early if an error occurs. */
  68353. rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
  68354. assert( rc!=SQLITE_IOERR_SHORT_READ );
  68355. if( rc!=SQLITE_OK ) return rc;
  68356. }
  68357. nAvail = p->nBuffer - iBuf;
  68358. if( nByte<=nAvail ){
  68359. /* The requested data is available in the in-memory buffer. In this
  68360. ** case there is no need to make a copy of the data, just return a
  68361. ** pointer into the buffer to the caller. */
  68362. *ppOut = &p->aBuffer[iBuf];
  68363. p->iReadOff += nByte;
  68364. }else{
  68365. /* The requested data is not all available in the in-memory buffer.
  68366. ** In this case, allocate space at p->aAlloc[] to copy the requested
  68367. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  68368. int nRem; /* Bytes remaining to copy */
  68369. /* Extend the p->aAlloc[] allocation if required. */
  68370. if( p->nAlloc<nByte ){
  68371. int nNew = p->nAlloc*2;
  68372. while( nByte>nNew ) nNew = nNew*2;
  68373. p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
  68374. if( !p->aAlloc ) return SQLITE_NOMEM;
  68375. p->nAlloc = nNew;
  68376. }
  68377. /* Copy as much data as is available in the buffer into the start of
  68378. ** p->aAlloc[]. */
  68379. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  68380. p->iReadOff += nAvail;
  68381. nRem = nByte - nAvail;
  68382. /* The following loop copies up to p->nBuffer bytes per iteration into
  68383. ** the p->aAlloc[] buffer. */
  68384. while( nRem>0 ){
  68385. int rc; /* vdbeSorterIterRead() return code */
  68386. int nCopy; /* Number of bytes to copy */
  68387. u8 *aNext; /* Pointer to buffer to copy data from */
  68388. nCopy = nRem;
  68389. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  68390. rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
  68391. if( rc!=SQLITE_OK ) return rc;
  68392. assert( aNext!=p->aAlloc );
  68393. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  68394. nRem -= nCopy;
  68395. }
  68396. *ppOut = p->aAlloc;
  68397. }
  68398. return SQLITE_OK;
  68399. }
  68400. /*
  68401. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  68402. ** the value read.
  68403. */
  68404. static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
  68405. int iBuf;
  68406. iBuf = p->iReadOff % p->nBuffer;
  68407. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  68408. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  68409. }else{
  68410. u8 aVarint[16], *a;
  68411. int i = 0, rc;
  68412. do{
  68413. rc = vdbeSorterIterRead(db, p, 1, &a);
  68414. if( rc ) return rc;
  68415. aVarint[(i++)&0xf] = a[0];
  68416. }while( (a[0]&0x80)!=0 );
  68417. sqlite3GetVarint(aVarint, pnOut);
  68418. }
  68419. return SQLITE_OK;
  68420. }
  68421. /*
  68422. ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
  68423. ** no error occurs, or an SQLite error code if one does.
  68424. */
  68425. static int vdbeSorterIterNext(
  68426. sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */
  68427. VdbeSorterIter *pIter /* Iterator to advance */
  68428. ){
  68429. int rc; /* Return Code */
  68430. u64 nRec = 0; /* Size of record in bytes */
  68431. if( pIter->iReadOff>=pIter->iEof ){
  68432. /* This is an EOF condition */
  68433. vdbeSorterIterZero(db, pIter);
  68434. return SQLITE_OK;
  68435. }
  68436. rc = vdbeSorterIterVarint(db, pIter, &nRec);
  68437. if( rc==SQLITE_OK ){
  68438. pIter->nKey = (int)nRec;
  68439. rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
  68440. }
  68441. return rc;
  68442. }
  68443. /*
  68444. ** Initialize iterator pIter to scan through the PMA stored in file pFile
  68445. ** starting at offset iStart and ending at offset iEof-1. This function
  68446. ** leaves the iterator pointing to the first key in the PMA (or EOF if the
  68447. ** PMA is empty).
  68448. */
  68449. static int vdbeSorterIterInit(
  68450. sqlite3 *db, /* Database handle */
  68451. const VdbeSorter *pSorter, /* Sorter object */
  68452. i64 iStart, /* Start offset in pFile */
  68453. VdbeSorterIter *pIter, /* Iterator to populate */
  68454. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  68455. ){
  68456. int rc = SQLITE_OK;
  68457. int nBuf;
  68458. nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  68459. assert( pSorter->iWriteOff>iStart );
  68460. assert( pIter->aAlloc==0 );
  68461. assert( pIter->aBuffer==0 );
  68462. pIter->pFile = pSorter->pTemp1;
  68463. pIter->iReadOff = iStart;
  68464. pIter->nAlloc = 128;
  68465. pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
  68466. pIter->nBuffer = nBuf;
  68467. pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  68468. if( !pIter->aBuffer ){
  68469. rc = SQLITE_NOMEM;
  68470. }else{
  68471. int iBuf;
  68472. iBuf = iStart % nBuf;
  68473. if( iBuf ){
  68474. int nRead = nBuf - iBuf;
  68475. if( (iStart + nRead) > pSorter->iWriteOff ){
  68476. nRead = (int)(pSorter->iWriteOff - iStart);
  68477. }
  68478. rc = sqlite3OsRead(
  68479. pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
  68480. );
  68481. assert( rc!=SQLITE_IOERR_SHORT_READ );
  68482. }
  68483. if( rc==SQLITE_OK ){
  68484. u64 nByte; /* Size of PMA in bytes */
  68485. pIter->iEof = pSorter->iWriteOff;
  68486. rc = vdbeSorterIterVarint(db, pIter, &nByte);
  68487. pIter->iEof = pIter->iReadOff + nByte;
  68488. *pnByte += nByte;
  68489. }
  68490. }
  68491. if( rc==SQLITE_OK ){
  68492. rc = vdbeSorterIterNext(db, pIter);
  68493. }
  68494. return rc;
  68495. }
  68496. /*
  68497. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  68498. ** size nKey2 bytes). Argument pKeyInfo supplies the collation functions
  68499. ** used by the comparison. If an error occurs, return an SQLite error code.
  68500. ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
  68501. ** value, depending on whether key1 is smaller, equal to or larger than key2.
  68502. **
  68503. ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
  68504. ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
  68505. ** is true and key1 contains even a single NULL value, it is considered to
  68506. ** be less than key2. Even if key2 also contains NULL values.
  68507. **
  68508. ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
  68509. ** has been allocated and contains an unpacked record that is used as key2.
  68510. */
  68511. static void vdbeSorterCompare(
  68512. const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */
  68513. int bOmitRowid, /* Ignore rowid field at end of keys */
  68514. const void *pKey1, int nKey1, /* Left side of comparison */
  68515. const void *pKey2, int nKey2, /* Right side of comparison */
  68516. int *pRes /* OUT: Result of comparison */
  68517. ){
  68518. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  68519. VdbeSorter *pSorter = pCsr->pSorter;
  68520. UnpackedRecord *r2 = pSorter->pUnpacked;
  68521. int i;
  68522. if( pKey2 ){
  68523. sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
  68524. }
  68525. if( bOmitRowid ){
  68526. r2->nField = pKeyInfo->nField;
  68527. assert( r2->nField>0 );
  68528. for(i=0; i<r2->nField; i++){
  68529. if( r2->aMem[i].flags & MEM_Null ){
  68530. *pRes = -1;
  68531. return;
  68532. }
  68533. }
  68534. r2->flags |= UNPACKED_PREFIX_MATCH;
  68535. }
  68536. *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  68537. }
  68538. /*
  68539. ** This function is called to compare two iterator keys when merging
  68540. ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
  68541. ** value to recalculate.
  68542. */
  68543. static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
  68544. VdbeSorter *pSorter = pCsr->pSorter;
  68545. int i1;
  68546. int i2;
  68547. int iRes;
  68548. VdbeSorterIter *p1;
  68549. VdbeSorterIter *p2;
  68550. assert( iOut<pSorter->nTree && iOut>0 );
  68551. if( iOut>=(pSorter->nTree/2) ){
  68552. i1 = (iOut - pSorter->nTree/2) * 2;
  68553. i2 = i1 + 1;
  68554. }else{
  68555. i1 = pSorter->aTree[iOut*2];
  68556. i2 = pSorter->aTree[iOut*2+1];
  68557. }
  68558. p1 = &pSorter->aIter[i1];
  68559. p2 = &pSorter->aIter[i2];
  68560. if( p1->pFile==0 ){
  68561. iRes = i2;
  68562. }else if( p2->pFile==0 ){
  68563. iRes = i1;
  68564. }else{
  68565. int res;
  68566. assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */
  68567. vdbeSorterCompare(
  68568. pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
  68569. );
  68570. if( res<=0 ){
  68571. iRes = i1;
  68572. }else{
  68573. iRes = i2;
  68574. }
  68575. }
  68576. pSorter->aTree[iOut] = iRes;
  68577. return SQLITE_OK;
  68578. }
  68579. /*
  68580. ** Initialize the temporary index cursor just opened as a sorter cursor.
  68581. */
  68582. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
  68583. int pgsz; /* Page size of main database */
  68584. int mxCache; /* Cache size */
  68585. VdbeSorter *pSorter; /* The new sorter */
  68586. char *d; /* Dummy */
  68587. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  68588. pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
  68589. if( pSorter==0 ){
  68590. return SQLITE_NOMEM;
  68591. }
  68592. pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
  68593. if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
  68594. assert( pSorter->pUnpacked==(UnpackedRecord *)d );
  68595. if( !sqlite3TempInMemory(db) ){
  68596. pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  68597. pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
  68598. mxCache = db->aDb[0].pSchema->cache_size;
  68599. if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
  68600. pSorter->mxPmaSize = mxCache * pgsz;
  68601. }
  68602. return SQLITE_OK;
  68603. }
  68604. /*
  68605. ** Free the list of sorted records starting at pRecord.
  68606. */
  68607. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  68608. SorterRecord *p;
  68609. SorterRecord *pNext;
  68610. for(p=pRecord; p; p=pNext){
  68611. pNext = p->pNext;
  68612. sqlite3DbFree(db, p);
  68613. }
  68614. }
  68615. /*
  68616. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  68617. */
  68618. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  68619. VdbeSorter *pSorter = pCsr->pSorter;
  68620. if( pSorter ){
  68621. if( pSorter->aIter ){
  68622. int i;
  68623. for(i=0; i<pSorter->nTree; i++){
  68624. vdbeSorterIterZero(db, &pSorter->aIter[i]);
  68625. }
  68626. sqlite3DbFree(db, pSorter->aIter);
  68627. }
  68628. if( pSorter->pTemp1 ){
  68629. sqlite3OsCloseFree(pSorter->pTemp1);
  68630. }
  68631. vdbeSorterRecordFree(db, pSorter->pRecord);
  68632. sqlite3DbFree(db, pSorter->pUnpacked);
  68633. sqlite3DbFree(db, pSorter);
  68634. pCsr->pSorter = 0;
  68635. }
  68636. }
  68637. /*
  68638. ** Allocate space for a file-handle and open a temporary file. If successful,
  68639. ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
  68640. ** Otherwise, set *ppFile to 0 and return an SQLite error code.
  68641. */
  68642. static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
  68643. int dummy;
  68644. return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
  68645. SQLITE_OPEN_TEMP_JOURNAL |
  68646. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  68647. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy
  68648. );
  68649. }
  68650. /*
  68651. ** Merge the two sorted lists p1 and p2 into a single list.
  68652. ** Set *ppOut to the head of the new list.
  68653. */
  68654. static void vdbeSorterMerge(
  68655. const VdbeCursor *pCsr, /* For pKeyInfo */
  68656. SorterRecord *p1, /* First list to merge */
  68657. SorterRecord *p2, /* Second list to merge */
  68658. SorterRecord **ppOut /* OUT: Head of merged list */
  68659. ){
  68660. SorterRecord *pFinal = 0;
  68661. SorterRecord **pp = &pFinal;
  68662. void *pVal2 = p2 ? p2->pVal : 0;
  68663. while( p1 && p2 ){
  68664. int res;
  68665. vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
  68666. if( res<=0 ){
  68667. *pp = p1;
  68668. pp = &p1->pNext;
  68669. p1 = p1->pNext;
  68670. pVal2 = 0;
  68671. }else{
  68672. *pp = p2;
  68673. pp = &p2->pNext;
  68674. p2 = p2->pNext;
  68675. if( p2==0 ) break;
  68676. pVal2 = p2->pVal;
  68677. }
  68678. }
  68679. *pp = p1 ? p1 : p2;
  68680. *ppOut = pFinal;
  68681. }
  68682. /*
  68683. ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
  68684. ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
  68685. ** occurs.
  68686. */
  68687. static int vdbeSorterSort(const VdbeCursor *pCsr){
  68688. int i;
  68689. SorterRecord **aSlot;
  68690. SorterRecord *p;
  68691. VdbeSorter *pSorter = pCsr->pSorter;
  68692. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  68693. if( !aSlot ){
  68694. return SQLITE_NOMEM;
  68695. }
  68696. p = pSorter->pRecord;
  68697. while( p ){
  68698. SorterRecord *pNext = p->pNext;
  68699. p->pNext = 0;
  68700. for(i=0; aSlot[i]; i++){
  68701. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  68702. aSlot[i] = 0;
  68703. }
  68704. aSlot[i] = p;
  68705. p = pNext;
  68706. }
  68707. p = 0;
  68708. for(i=0; i<64; i++){
  68709. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  68710. }
  68711. pSorter->pRecord = p;
  68712. sqlite3_free(aSlot);
  68713. return SQLITE_OK;
  68714. }
  68715. /*
  68716. ** Initialize a file-writer object.
  68717. */
  68718. static void fileWriterInit(
  68719. sqlite3 *db, /* Database (for malloc) */
  68720. sqlite3_file *pFile, /* File to write to */
  68721. FileWriter *p, /* Object to populate */
  68722. i64 iStart /* Offset of pFile to begin writing at */
  68723. ){
  68724. int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  68725. memset(p, 0, sizeof(FileWriter));
  68726. p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  68727. if( !p->aBuffer ){
  68728. p->eFWErr = SQLITE_NOMEM;
  68729. }else{
  68730. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  68731. p->iWriteOff = iStart - p->iBufStart;
  68732. p->nBuffer = nBuf;
  68733. p->pFile = pFile;
  68734. }
  68735. }
  68736. /*
  68737. ** Write nData bytes of data to the file-write object. Return SQLITE_OK
  68738. ** if successful, or an SQLite error code if an error occurs.
  68739. */
  68740. static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
  68741. int nRem = nData;
  68742. while( nRem>0 && p->eFWErr==0 ){
  68743. int nCopy = nRem;
  68744. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  68745. nCopy = p->nBuffer - p->iBufEnd;
  68746. }
  68747. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  68748. p->iBufEnd += nCopy;
  68749. if( p->iBufEnd==p->nBuffer ){
  68750. p->eFWErr = sqlite3OsWrite(p->pFile,
  68751. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  68752. p->iWriteOff + p->iBufStart
  68753. );
  68754. p->iBufStart = p->iBufEnd = 0;
  68755. p->iWriteOff += p->nBuffer;
  68756. }
  68757. assert( p->iBufEnd<p->nBuffer );
  68758. nRem -= nCopy;
  68759. }
  68760. }
  68761. /*
  68762. ** Flush any buffered data to disk and clean up the file-writer object.
  68763. ** The results of using the file-writer after this call are undefined.
  68764. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  68765. ** required. Otherwise, return an SQLite error code.
  68766. **
  68767. ** Before returning, set *piEof to the offset immediately following the
  68768. ** last byte written to the file.
  68769. */
  68770. static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
  68771. int rc;
  68772. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  68773. p->eFWErr = sqlite3OsWrite(p->pFile,
  68774. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  68775. p->iWriteOff + p->iBufStart
  68776. );
  68777. }
  68778. *piEof = (p->iWriteOff + p->iBufEnd);
  68779. sqlite3DbFree(db, p->aBuffer);
  68780. rc = p->eFWErr;
  68781. memset(p, 0, sizeof(FileWriter));
  68782. return rc;
  68783. }
  68784. /*
  68785. ** Write value iVal encoded as a varint to the file-write object. Return
  68786. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  68787. */
  68788. static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
  68789. int nByte;
  68790. u8 aByte[10];
  68791. nByte = sqlite3PutVarint(aByte, iVal);
  68792. fileWriterWrite(p, aByte, nByte);
  68793. }
  68794. /*
  68795. ** Write the current contents of the in-memory linked-list to a PMA. Return
  68796. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  68797. **
  68798. ** The format of a PMA is:
  68799. **
  68800. ** * A varint. This varint contains the total number of bytes of content
  68801. ** in the PMA (not including the varint itself).
  68802. **
  68803. ** * One or more records packed end-to-end in order of ascending keys.
  68804. ** Each record consists of a varint followed by a blob of data (the
  68805. ** key). The varint is the number of bytes in the blob of data.
  68806. */
  68807. static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
  68808. int rc = SQLITE_OK; /* Return code */
  68809. VdbeSorter *pSorter = pCsr->pSorter;
  68810. FileWriter writer;
  68811. memset(&writer, 0, sizeof(FileWriter));
  68812. if( pSorter->nInMemory==0 ){
  68813. assert( pSorter->pRecord==0 );
  68814. return rc;
  68815. }
  68816. rc = vdbeSorterSort(pCsr);
  68817. /* If the first temporary PMA file has not been opened, open it now. */
  68818. if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
  68819. rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
  68820. assert( rc!=SQLITE_OK || pSorter->pTemp1 );
  68821. assert( pSorter->iWriteOff==0 );
  68822. assert( pSorter->nPMA==0 );
  68823. }
  68824. if( rc==SQLITE_OK ){
  68825. SorterRecord *p;
  68826. SorterRecord *pNext = 0;
  68827. fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
  68828. pSorter->nPMA++;
  68829. fileWriterWriteVarint(&writer, pSorter->nInMemory);
  68830. for(p=pSorter->pRecord; p; p=pNext){
  68831. pNext = p->pNext;
  68832. fileWriterWriteVarint(&writer, p->nVal);
  68833. fileWriterWrite(&writer, p->pVal, p->nVal);
  68834. sqlite3DbFree(db, p);
  68835. }
  68836. pSorter->pRecord = p;
  68837. rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
  68838. }
  68839. return rc;
  68840. }
  68841. /*
  68842. ** Add a record to the sorter.
  68843. */
  68844. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  68845. sqlite3 *db, /* Database handle */
  68846. const VdbeCursor *pCsr, /* Sorter cursor */
  68847. Mem *pVal /* Memory cell containing record */
  68848. ){
  68849. VdbeSorter *pSorter = pCsr->pSorter;
  68850. int rc = SQLITE_OK; /* Return Code */
  68851. SorterRecord *pNew; /* New list element */
  68852. assert( pSorter );
  68853. pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
  68854. pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
  68855. if( pNew==0 ){
  68856. rc = SQLITE_NOMEM;
  68857. }else{
  68858. pNew->pVal = (void *)&pNew[1];
  68859. memcpy(pNew->pVal, pVal->z, pVal->n);
  68860. pNew->nVal = pVal->n;
  68861. pNew->pNext = pSorter->pRecord;
  68862. pSorter->pRecord = pNew;
  68863. }
  68864. /* See if the contents of the sorter should now be written out. They
  68865. ** are written out when either of the following are true:
  68866. **
  68867. ** * The total memory allocated for the in-memory list is greater
  68868. ** than (page-size * cache-size), or
  68869. **
  68870. ** * The total memory allocated for the in-memory list is greater
  68871. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  68872. */
  68873. if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
  68874. (pSorter->nInMemory>pSorter->mxPmaSize)
  68875. || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  68876. )){
  68877. #ifdef SQLITE_DEBUG
  68878. i64 nExpect = pSorter->iWriteOff
  68879. + sqlite3VarintLen(pSorter->nInMemory)
  68880. + pSorter->nInMemory;
  68881. #endif
  68882. rc = vdbeSorterListToPMA(db, pCsr);
  68883. pSorter->nInMemory = 0;
  68884. assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
  68885. }
  68886. return rc;
  68887. }
  68888. /*
  68889. ** Helper function for sqlite3VdbeSorterRewind().
  68890. */
  68891. static int vdbeSorterInitMerge(
  68892. sqlite3 *db, /* Database handle */
  68893. const VdbeCursor *pCsr, /* Cursor handle for this sorter */
  68894. i64 *pnByte /* Sum of bytes in all opened PMAs */
  68895. ){
  68896. VdbeSorter *pSorter = pCsr->pSorter;
  68897. int rc = SQLITE_OK; /* Return code */
  68898. int i; /* Used to iterator through aIter[] */
  68899. i64 nByte = 0; /* Total bytes in all opened PMAs */
  68900. /* Initialize the iterators. */
  68901. for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
  68902. VdbeSorterIter *pIter = &pSorter->aIter[i];
  68903. rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
  68904. pSorter->iReadOff = pIter->iEof;
  68905. assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
  68906. if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
  68907. }
  68908. /* Initialize the aTree[] array. */
  68909. for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
  68910. rc = vdbeSorterDoCompare(pCsr, i);
  68911. }
  68912. *pnByte = nByte;
  68913. return rc;
  68914. }
  68915. /*
  68916. ** Once the sorter has been populated, this function is called to prepare
  68917. ** for iterating through its contents in sorted order.
  68918. */
  68919. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  68920. VdbeSorter *pSorter = pCsr->pSorter;
  68921. int rc; /* Return code */
  68922. sqlite3_file *pTemp2 = 0; /* Second temp file to use */
  68923. i64 iWrite2 = 0; /* Write offset for pTemp2 */
  68924. int nIter; /* Number of iterators used */
  68925. int nByte; /* Bytes of space required for aIter/aTree */
  68926. int N = 2; /* Power of 2 >= nIter */
  68927. assert( pSorter );
  68928. /* If no data has been written to disk, then do not do so now. Instead,
  68929. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  68930. ** from the in-memory list. */
  68931. if( pSorter->nPMA==0 ){
  68932. *pbEof = !pSorter->pRecord;
  68933. assert( pSorter->aTree==0 );
  68934. return vdbeSorterSort(pCsr);
  68935. }
  68936. /* Write the current in-memory list to a PMA. */
  68937. rc = vdbeSorterListToPMA(db, pCsr);
  68938. if( rc!=SQLITE_OK ) return rc;
  68939. /* Allocate space for aIter[] and aTree[]. */
  68940. nIter = pSorter->nPMA;
  68941. if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
  68942. assert( nIter>0 );
  68943. while( N<nIter ) N += N;
  68944. nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
  68945. pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
  68946. if( !pSorter->aIter ) return SQLITE_NOMEM;
  68947. pSorter->aTree = (int *)&pSorter->aIter[N];
  68948. pSorter->nTree = N;
  68949. do {
  68950. int iNew; /* Index of new, merged, PMA */
  68951. for(iNew=0;
  68952. rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
  68953. iNew++
  68954. ){
  68955. int rc2; /* Return code from fileWriterFinish() */
  68956. FileWriter writer; /* Object used to write to disk */
  68957. i64 nWrite; /* Number of bytes in new PMA */
  68958. memset(&writer, 0, sizeof(FileWriter));
  68959. /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
  68960. ** initialize an iterator for each of them and break out of the loop.
  68961. ** These iterators will be incrementally merged as the VDBE layer calls
  68962. ** sqlite3VdbeSorterNext().
  68963. **
  68964. ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
  68965. ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
  68966. ** are merged into a single PMA that is written to file pTemp2.
  68967. */
  68968. rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
  68969. assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
  68970. if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  68971. break;
  68972. }
  68973. /* Open the second temp file, if it is not already open. */
  68974. if( pTemp2==0 ){
  68975. assert( iWrite2==0 );
  68976. rc = vdbeSorterOpenTempFile(db, &pTemp2);
  68977. }
  68978. if( rc==SQLITE_OK ){
  68979. int bEof = 0;
  68980. fileWriterInit(db, pTemp2, &writer, iWrite2);
  68981. fileWriterWriteVarint(&writer, nWrite);
  68982. while( rc==SQLITE_OK && bEof==0 ){
  68983. VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  68984. assert( pIter->pFile );
  68985. fileWriterWriteVarint(&writer, pIter->nKey);
  68986. fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
  68987. rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
  68988. }
  68989. rc2 = fileWriterFinish(db, &writer, &iWrite2);
  68990. if( rc==SQLITE_OK ) rc = rc2;
  68991. }
  68992. }
  68993. if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  68994. break;
  68995. }else{
  68996. sqlite3_file *pTmp = pSorter->pTemp1;
  68997. pSorter->nPMA = iNew;
  68998. pSorter->pTemp1 = pTemp2;
  68999. pTemp2 = pTmp;
  69000. pSorter->iWriteOff = iWrite2;
  69001. pSorter->iReadOff = 0;
  69002. iWrite2 = 0;
  69003. }
  69004. }while( rc==SQLITE_OK );
  69005. if( pTemp2 ){
  69006. sqlite3OsCloseFree(pTemp2);
  69007. }
  69008. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  69009. return rc;
  69010. }
  69011. /*
  69012. ** Advance to the next element in the sorter.
  69013. */
  69014. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  69015. VdbeSorter *pSorter = pCsr->pSorter;
  69016. int rc; /* Return code */
  69017. if( pSorter->aTree ){
  69018. int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
  69019. int i; /* Index of aTree[] to recalculate */
  69020. rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
  69021. for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
  69022. rc = vdbeSorterDoCompare(pCsr, i);
  69023. }
  69024. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  69025. }else{
  69026. SorterRecord *pFree = pSorter->pRecord;
  69027. pSorter->pRecord = pFree->pNext;
  69028. pFree->pNext = 0;
  69029. vdbeSorterRecordFree(db, pFree);
  69030. *pbEof = !pSorter->pRecord;
  69031. rc = SQLITE_OK;
  69032. }
  69033. return rc;
  69034. }
  69035. /*
  69036. ** Return a pointer to a buffer owned by the sorter that contains the
  69037. ** current key.
  69038. */
  69039. static void *vdbeSorterRowkey(
  69040. const VdbeSorter *pSorter, /* Sorter object */
  69041. int *pnKey /* OUT: Size of current key in bytes */
  69042. ){
  69043. void *pKey;
  69044. if( pSorter->aTree ){
  69045. VdbeSorterIter *pIter;
  69046. pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  69047. *pnKey = pIter->nKey;
  69048. pKey = pIter->aKey;
  69049. }else{
  69050. *pnKey = pSorter->pRecord->nVal;
  69051. pKey = pSorter->pRecord->pVal;
  69052. }
  69053. return pKey;
  69054. }
  69055. /*
  69056. ** Copy the current sorter key into the memory cell pOut.
  69057. */
  69058. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  69059. VdbeSorter *pSorter = pCsr->pSorter;
  69060. void *pKey; int nKey; /* Sorter key to copy into pOut */
  69061. pKey = vdbeSorterRowkey(pSorter, &nKey);
  69062. if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
  69063. return SQLITE_NOMEM;
  69064. }
  69065. pOut->n = nKey;
  69066. MemSetTypeFlag(pOut, MEM_Blob);
  69067. memcpy(pOut->z, pKey, nKey);
  69068. return SQLITE_OK;
  69069. }
  69070. /*
  69071. ** Compare the key in memory cell pVal with the key that the sorter cursor
  69072. ** passed as the first argument currently points to. For the purposes of
  69073. ** the comparison, ignore the rowid field at the end of each record.
  69074. **
  69075. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  69076. ** Otherwise, set *pRes to a negative, zero or positive value if the
  69077. ** key in pVal is smaller than, equal to or larger than the current sorter
  69078. ** key.
  69079. */
  69080. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  69081. const VdbeCursor *pCsr, /* Sorter cursor */
  69082. Mem *pVal, /* Value to compare to current sorter key */
  69083. int *pRes /* OUT: Result of comparison */
  69084. ){
  69085. VdbeSorter *pSorter = pCsr->pSorter;
  69086. void *pKey; int nKey; /* Sorter key to compare pVal with */
  69087. pKey = vdbeSorterRowkey(pSorter, &nKey);
  69088. vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
  69089. return SQLITE_OK;
  69090. }
  69091. /************** End of vdbesort.c ********************************************/
  69092. /************** Begin file journal.c *****************************************/
  69093. /*
  69094. ** 2007 August 22
  69095. **
  69096. ** The author disclaims copyright to this source code. In place of
  69097. ** a legal notice, here is a blessing:
  69098. **
  69099. ** May you do good and not evil.
  69100. ** May you find forgiveness for yourself and forgive others.
  69101. ** May you share freely, never taking more than you give.
  69102. **
  69103. *************************************************************************
  69104. **
  69105. ** This file implements a special kind of sqlite3_file object used
  69106. ** by SQLite to create journal files if the atomic-write optimization
  69107. ** is enabled.
  69108. **
  69109. ** The distinctive characteristic of this sqlite3_file is that the
  69110. ** actual on disk file is created lazily. When the file is created,
  69111. ** the caller specifies a buffer size for an in-memory buffer to
  69112. ** be used to service read() and write() requests. The actual file
  69113. ** on disk is not created or populated until either:
  69114. **
  69115. ** 1) The in-memory representation grows too large for the allocated
  69116. ** buffer, or
  69117. ** 2) The sqlite3JournalCreate() function is called.
  69118. */
  69119. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  69120. /*
  69121. ** A JournalFile object is a subclass of sqlite3_file used by
  69122. ** as an open file handle for journal files.
  69123. */
  69124. struct JournalFile {
  69125. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  69126. int nBuf; /* Size of zBuf[] in bytes */
  69127. char *zBuf; /* Space to buffer journal writes */
  69128. int iSize; /* Amount of zBuf[] currently used */
  69129. int flags; /* xOpen flags */
  69130. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  69131. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  69132. const char *zJournal; /* Name of the journal file */
  69133. };
  69134. typedef struct JournalFile JournalFile;
  69135. /*
  69136. ** If it does not already exists, create and populate the on-disk file
  69137. ** for JournalFile p.
  69138. */
  69139. static int createFile(JournalFile *p){
  69140. int rc = SQLITE_OK;
  69141. if( !p->pReal ){
  69142. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  69143. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  69144. if( rc==SQLITE_OK ){
  69145. p->pReal = pReal;
  69146. if( p->iSize>0 ){
  69147. assert(p->iSize<=p->nBuf);
  69148. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  69149. }
  69150. if( rc!=SQLITE_OK ){
  69151. /* If an error occurred while writing to the file, close it before
  69152. ** returning. This way, SQLite uses the in-memory journal data to
  69153. ** roll back changes made to the internal page-cache before this
  69154. ** function was called. */
  69155. sqlite3OsClose(pReal);
  69156. p->pReal = 0;
  69157. }
  69158. }
  69159. }
  69160. return rc;
  69161. }
  69162. /*
  69163. ** Close the file.
  69164. */
  69165. static int jrnlClose(sqlite3_file *pJfd){
  69166. JournalFile *p = (JournalFile *)pJfd;
  69167. if( p->pReal ){
  69168. sqlite3OsClose(p->pReal);
  69169. }
  69170. sqlite3_free(p->zBuf);
  69171. return SQLITE_OK;
  69172. }
  69173. /*
  69174. ** Read data from the file.
  69175. */
  69176. static int jrnlRead(
  69177. sqlite3_file *pJfd, /* The journal file from which to read */
  69178. void *zBuf, /* Put the results here */
  69179. int iAmt, /* Number of bytes to read */
  69180. sqlite_int64 iOfst /* Begin reading at this offset */
  69181. ){
  69182. int rc = SQLITE_OK;
  69183. JournalFile *p = (JournalFile *)pJfd;
  69184. if( p->pReal ){
  69185. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  69186. }else if( (iAmt+iOfst)>p->iSize ){
  69187. rc = SQLITE_IOERR_SHORT_READ;
  69188. }else{
  69189. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  69190. }
  69191. return rc;
  69192. }
  69193. /*
  69194. ** Write data to the file.
  69195. */
  69196. static int jrnlWrite(
  69197. sqlite3_file *pJfd, /* The journal file into which to write */
  69198. const void *zBuf, /* Take data to be written from here */
  69199. int iAmt, /* Number of bytes to write */
  69200. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  69201. ){
  69202. int rc = SQLITE_OK;
  69203. JournalFile *p = (JournalFile *)pJfd;
  69204. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  69205. rc = createFile(p);
  69206. }
  69207. if( rc==SQLITE_OK ){
  69208. if( p->pReal ){
  69209. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  69210. }else{
  69211. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  69212. if( p->iSize<(iOfst+iAmt) ){
  69213. p->iSize = (iOfst+iAmt);
  69214. }
  69215. }
  69216. }
  69217. return rc;
  69218. }
  69219. /*
  69220. ** Truncate the file.
  69221. */
  69222. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  69223. int rc = SQLITE_OK;
  69224. JournalFile *p = (JournalFile *)pJfd;
  69225. if( p->pReal ){
  69226. rc = sqlite3OsTruncate(p->pReal, size);
  69227. }else if( size<p->iSize ){
  69228. p->iSize = size;
  69229. }
  69230. return rc;
  69231. }
  69232. /*
  69233. ** Sync the file.
  69234. */
  69235. static int jrnlSync(sqlite3_file *pJfd, int flags){
  69236. int rc;
  69237. JournalFile *p = (JournalFile *)pJfd;
  69238. if( p->pReal ){
  69239. rc = sqlite3OsSync(p->pReal, flags);
  69240. }else{
  69241. rc = SQLITE_OK;
  69242. }
  69243. return rc;
  69244. }
  69245. /*
  69246. ** Query the size of the file in bytes.
  69247. */
  69248. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  69249. int rc = SQLITE_OK;
  69250. JournalFile *p = (JournalFile *)pJfd;
  69251. if( p->pReal ){
  69252. rc = sqlite3OsFileSize(p->pReal, pSize);
  69253. }else{
  69254. *pSize = (sqlite_int64) p->iSize;
  69255. }
  69256. return rc;
  69257. }
  69258. /*
  69259. ** Table of methods for JournalFile sqlite3_file object.
  69260. */
  69261. static struct sqlite3_io_methods JournalFileMethods = {
  69262. 1, /* iVersion */
  69263. jrnlClose, /* xClose */
  69264. jrnlRead, /* xRead */
  69265. jrnlWrite, /* xWrite */
  69266. jrnlTruncate, /* xTruncate */
  69267. jrnlSync, /* xSync */
  69268. jrnlFileSize, /* xFileSize */
  69269. 0, /* xLock */
  69270. 0, /* xUnlock */
  69271. 0, /* xCheckReservedLock */
  69272. 0, /* xFileControl */
  69273. 0, /* xSectorSize */
  69274. 0, /* xDeviceCharacteristics */
  69275. 0, /* xShmMap */
  69276. 0, /* xShmLock */
  69277. 0, /* xShmBarrier */
  69278. 0 /* xShmUnmap */
  69279. };
  69280. /*
  69281. ** Open a journal file.
  69282. */
  69283. SQLITE_PRIVATE int sqlite3JournalOpen(
  69284. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  69285. const char *zName, /* Name of the journal file */
  69286. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  69287. int flags, /* Opening flags */
  69288. int nBuf /* Bytes buffered before opening the file */
  69289. ){
  69290. JournalFile *p = (JournalFile *)pJfd;
  69291. memset(p, 0, sqlite3JournalSize(pVfs));
  69292. if( nBuf>0 ){
  69293. p->zBuf = sqlite3MallocZero(nBuf);
  69294. if( !p->zBuf ){
  69295. return SQLITE_NOMEM;
  69296. }
  69297. }else{
  69298. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  69299. }
  69300. p->pMethod = &JournalFileMethods;
  69301. p->nBuf = nBuf;
  69302. p->flags = flags;
  69303. p->zJournal = zName;
  69304. p->pVfs = pVfs;
  69305. return SQLITE_OK;
  69306. }
  69307. /*
  69308. ** If the argument p points to a JournalFile structure, and the underlying
  69309. ** file has not yet been created, create it now.
  69310. */
  69311. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  69312. if( p->pMethods!=&JournalFileMethods ){
  69313. return SQLITE_OK;
  69314. }
  69315. return createFile((JournalFile *)p);
  69316. }
  69317. /*
  69318. ** The file-handle passed as the only argument is guaranteed to be an open
  69319. ** file. It may or may not be of class JournalFile. If the file is a
  69320. ** JournalFile, and the underlying file on disk has not yet been opened,
  69321. ** return 0. Otherwise, return 1.
  69322. */
  69323. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  69324. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  69325. }
  69326. /*
  69327. ** Return the number of bytes required to store a JournalFile that uses vfs
  69328. ** pVfs to create the underlying on-disk files.
  69329. */
  69330. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  69331. return (pVfs->szOsFile+sizeof(JournalFile));
  69332. }
  69333. #endif
  69334. /************** End of journal.c *********************************************/
  69335. /************** Begin file memjournal.c **************************************/
  69336. /*
  69337. ** 2008 October 7
  69338. **
  69339. ** The author disclaims copyright to this source code. In place of
  69340. ** a legal notice, here is a blessing:
  69341. **
  69342. ** May you do good and not evil.
  69343. ** May you find forgiveness for yourself and forgive others.
  69344. ** May you share freely, never taking more than you give.
  69345. **
  69346. *************************************************************************
  69347. **
  69348. ** This file contains code use to implement an in-memory rollback journal.
  69349. ** The in-memory rollback journal is used to journal transactions for
  69350. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  69351. */
  69352. /* Forward references to internal structures */
  69353. typedef struct MemJournal MemJournal;
  69354. typedef struct FilePoint FilePoint;
  69355. typedef struct FileChunk FileChunk;
  69356. /* Space to hold the rollback journal is allocated in increments of
  69357. ** this many bytes.
  69358. **
  69359. ** The size chosen is a little less than a power of two. That way,
  69360. ** the FileChunk object will have a size that almost exactly fills
  69361. ** a power-of-two allocation. This mimimizes wasted space in power-of-two
  69362. ** memory allocators.
  69363. */
  69364. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  69365. /*
  69366. ** The rollback journal is composed of a linked list of these structures.
  69367. */
  69368. struct FileChunk {
  69369. FileChunk *pNext; /* Next chunk in the journal */
  69370. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  69371. };
  69372. /*
  69373. ** An instance of this object serves as a cursor into the rollback journal.
  69374. ** The cursor can be either for reading or writing.
  69375. */
  69376. struct FilePoint {
  69377. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  69378. FileChunk *pChunk; /* Specific chunk into which cursor points */
  69379. };
  69380. /*
  69381. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  69382. ** is an instance of this class.
  69383. */
  69384. struct MemJournal {
  69385. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  69386. FileChunk *pFirst; /* Head of in-memory chunk-list */
  69387. FilePoint endpoint; /* Pointer to the end of the file */
  69388. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  69389. };
  69390. /*
  69391. ** Read data from the in-memory journal file. This is the implementation
  69392. ** of the sqlite3_vfs.xRead method.
  69393. */
  69394. static int memjrnlRead(
  69395. sqlite3_file *pJfd, /* The journal file from which to read */
  69396. void *zBuf, /* Put the results here */
  69397. int iAmt, /* Number of bytes to read */
  69398. sqlite_int64 iOfst /* Begin reading at this offset */
  69399. ){
  69400. MemJournal *p = (MemJournal *)pJfd;
  69401. u8 *zOut = zBuf;
  69402. int nRead = iAmt;
  69403. int iChunkOffset;
  69404. FileChunk *pChunk;
  69405. /* SQLite never tries to read past the end of a rollback journal file */
  69406. assert( iOfst+iAmt<=p->endpoint.iOffset );
  69407. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  69408. sqlite3_int64 iOff = 0;
  69409. for(pChunk=p->pFirst;
  69410. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  69411. pChunk=pChunk->pNext
  69412. ){
  69413. iOff += JOURNAL_CHUNKSIZE;
  69414. }
  69415. }else{
  69416. pChunk = p->readpoint.pChunk;
  69417. }
  69418. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  69419. do {
  69420. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  69421. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  69422. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  69423. zOut += nCopy;
  69424. nRead -= iSpace;
  69425. iChunkOffset = 0;
  69426. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  69427. p->readpoint.iOffset = iOfst+iAmt;
  69428. p->readpoint.pChunk = pChunk;
  69429. return SQLITE_OK;
  69430. }
  69431. /*
  69432. ** Write data to the file.
  69433. */
  69434. static int memjrnlWrite(
  69435. sqlite3_file *pJfd, /* The journal file into which to write */
  69436. const void *zBuf, /* Take data to be written from here */
  69437. int iAmt, /* Number of bytes to write */
  69438. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  69439. ){
  69440. MemJournal *p = (MemJournal *)pJfd;
  69441. int nWrite = iAmt;
  69442. u8 *zWrite = (u8 *)zBuf;
  69443. /* An in-memory journal file should only ever be appended to. Random
  69444. ** access writes are not required by sqlite.
  69445. */
  69446. assert( iOfst==p->endpoint.iOffset );
  69447. UNUSED_PARAMETER(iOfst);
  69448. while( nWrite>0 ){
  69449. FileChunk *pChunk = p->endpoint.pChunk;
  69450. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  69451. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  69452. if( iChunkOffset==0 ){
  69453. /* New chunk is required to extend the file. */
  69454. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  69455. if( !pNew ){
  69456. return SQLITE_IOERR_NOMEM;
  69457. }
  69458. pNew->pNext = 0;
  69459. if( pChunk ){
  69460. assert( p->pFirst );
  69461. pChunk->pNext = pNew;
  69462. }else{
  69463. assert( !p->pFirst );
  69464. p->pFirst = pNew;
  69465. }
  69466. p->endpoint.pChunk = pNew;
  69467. }
  69468. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  69469. zWrite += iSpace;
  69470. nWrite -= iSpace;
  69471. p->endpoint.iOffset += iSpace;
  69472. }
  69473. return SQLITE_OK;
  69474. }
  69475. /*
  69476. ** Truncate the file.
  69477. */
  69478. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  69479. MemJournal *p = (MemJournal *)pJfd;
  69480. FileChunk *pChunk;
  69481. assert(size==0);
  69482. UNUSED_PARAMETER(size);
  69483. pChunk = p->pFirst;
  69484. while( pChunk ){
  69485. FileChunk *pTmp = pChunk;
  69486. pChunk = pChunk->pNext;
  69487. sqlite3_free(pTmp);
  69488. }
  69489. sqlite3MemJournalOpen(pJfd);
  69490. return SQLITE_OK;
  69491. }
  69492. /*
  69493. ** Close the file.
  69494. */
  69495. static int memjrnlClose(sqlite3_file *pJfd){
  69496. memjrnlTruncate(pJfd, 0);
  69497. return SQLITE_OK;
  69498. }
  69499. /*
  69500. ** Sync the file.
  69501. **
  69502. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  69503. ** is never called in a working implementation. This implementation
  69504. ** exists purely as a contingency, in case some malfunction in some other
  69505. ** part of SQLite causes Sync to be called by mistake.
  69506. */
  69507. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  69508. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  69509. return SQLITE_OK;
  69510. }
  69511. /*
  69512. ** Query the size of the file in bytes.
  69513. */
  69514. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  69515. MemJournal *p = (MemJournal *)pJfd;
  69516. *pSize = (sqlite_int64) p->endpoint.iOffset;
  69517. return SQLITE_OK;
  69518. }
  69519. /*
  69520. ** Table of methods for MemJournal sqlite3_file object.
  69521. */
  69522. static const struct sqlite3_io_methods MemJournalMethods = {
  69523. 1, /* iVersion */
  69524. memjrnlClose, /* xClose */
  69525. memjrnlRead, /* xRead */
  69526. memjrnlWrite, /* xWrite */
  69527. memjrnlTruncate, /* xTruncate */
  69528. memjrnlSync, /* xSync */
  69529. memjrnlFileSize, /* xFileSize */
  69530. 0, /* xLock */
  69531. 0, /* xUnlock */
  69532. 0, /* xCheckReservedLock */
  69533. 0, /* xFileControl */
  69534. 0, /* xSectorSize */
  69535. 0, /* xDeviceCharacteristics */
  69536. 0, /* xShmMap */
  69537. 0, /* xShmLock */
  69538. 0, /* xShmBarrier */
  69539. 0, /* xShmUnmap */
  69540. 0, /* xFetch */
  69541. 0 /* xUnfetch */
  69542. };
  69543. /*
  69544. ** Open a journal file.
  69545. */
  69546. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  69547. MemJournal *p = (MemJournal *)pJfd;
  69548. assert( EIGHT_BYTE_ALIGNMENT(p) );
  69549. memset(p, 0, sqlite3MemJournalSize());
  69550. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  69551. }
  69552. /*
  69553. ** Return true if the file-handle passed as an argument is
  69554. ** an in-memory journal
  69555. */
  69556. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  69557. return pJfd->pMethods==&MemJournalMethods;
  69558. }
  69559. /*
  69560. ** Return the number of bytes required to store a MemJournal file descriptor.
  69561. */
  69562. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  69563. return sizeof(MemJournal);
  69564. }
  69565. /************** End of memjournal.c ******************************************/
  69566. /************** Begin file walker.c ******************************************/
  69567. /*
  69568. ** 2008 August 16
  69569. **
  69570. ** The author disclaims copyright to this source code. In place of
  69571. ** a legal notice, here is a blessing:
  69572. **
  69573. ** May you do good and not evil.
  69574. ** May you find forgiveness for yourself and forgive others.
  69575. ** May you share freely, never taking more than you give.
  69576. **
  69577. *************************************************************************
  69578. ** This file contains routines used for walking the parser tree for
  69579. ** an SQL statement.
  69580. */
  69581. /* #include <stdlib.h> */
  69582. /* #include <string.h> */
  69583. /*
  69584. ** Walk an expression tree. Invoke the callback once for each node
  69585. ** of the expression, while decending. (In other words, the callback
  69586. ** is invoked before visiting children.)
  69587. **
  69588. ** The return value from the callback should be one of the WRC_*
  69589. ** constants to specify how to proceed with the walk.
  69590. **
  69591. ** WRC_Continue Continue descending down the tree.
  69592. **
  69593. ** WRC_Prune Do not descend into child nodes. But allow
  69594. ** the walk to continue with sibling nodes.
  69595. **
  69596. ** WRC_Abort Do no more callbacks. Unwind the stack and
  69597. ** return the top-level walk call.
  69598. **
  69599. ** The return value from this routine is WRC_Abort to abandon the tree walk
  69600. ** and WRC_Continue to continue.
  69601. */
  69602. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  69603. int rc;
  69604. if( pExpr==0 ) return WRC_Continue;
  69605. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  69606. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  69607. rc = pWalker->xExprCallback(pWalker, pExpr);
  69608. if( rc==WRC_Continue
  69609. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  69610. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  69611. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  69612. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  69613. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  69614. }else{
  69615. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  69616. }
  69617. }
  69618. return rc & WRC_Abort;
  69619. }
  69620. /*
  69621. ** Call sqlite3WalkExpr() for every expression in list p or until
  69622. ** an abort request is seen.
  69623. */
  69624. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  69625. int i;
  69626. struct ExprList_item *pItem;
  69627. if( p ){
  69628. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  69629. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  69630. }
  69631. }
  69632. return WRC_Continue;
  69633. }
  69634. /*
  69635. ** Walk all expressions associated with SELECT statement p. Do
  69636. ** not invoke the SELECT callback on p, but do (of course) invoke
  69637. ** any expr callbacks and SELECT callbacks that come from subqueries.
  69638. ** Return WRC_Abort or WRC_Continue.
  69639. */
  69640. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  69641. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  69642. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  69643. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  69644. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  69645. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  69646. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  69647. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  69648. return WRC_Continue;
  69649. }
  69650. /*
  69651. ** Walk the parse trees associated with all subqueries in the
  69652. ** FROM clause of SELECT statement p. Do not invoke the select
  69653. ** callback on p, but do invoke it on each FROM clause subquery
  69654. ** and on any subqueries further down in the tree. Return
  69655. ** WRC_Abort or WRC_Continue;
  69656. */
  69657. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  69658. SrcList *pSrc;
  69659. int i;
  69660. struct SrcList_item *pItem;
  69661. pSrc = p->pSrc;
  69662. if( ALWAYS(pSrc) ){
  69663. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  69664. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  69665. return WRC_Abort;
  69666. }
  69667. }
  69668. }
  69669. return WRC_Continue;
  69670. }
  69671. /*
  69672. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  69673. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  69674. ** on the compound select chain, p->pPrior. Invoke the xSelectCallback()
  69675. ** either before or after the walk of expressions and FROM clause, depending
  69676. ** on whether pWalker->bSelectDepthFirst is false or true, respectively.
  69677. **
  69678. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  69679. ** there is an abort request.
  69680. **
  69681. ** If the Walker does not have an xSelectCallback() then this routine
  69682. ** is a no-op returning WRC_Continue.
  69683. */
  69684. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  69685. int rc;
  69686. if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
  69687. rc = WRC_Continue;
  69688. pWalker->walkerDepth++;
  69689. while( p ){
  69690. if( !pWalker->bSelectDepthFirst ){
  69691. rc = pWalker->xSelectCallback(pWalker, p);
  69692. if( rc ) break;
  69693. }
  69694. if( sqlite3WalkSelectExpr(pWalker, p)
  69695. || sqlite3WalkSelectFrom(pWalker, p)
  69696. ){
  69697. pWalker->walkerDepth--;
  69698. return WRC_Abort;
  69699. }
  69700. if( pWalker->bSelectDepthFirst ){
  69701. rc = pWalker->xSelectCallback(pWalker, p);
  69702. /* Depth-first search is currently only used for
  69703. ** selectAddSubqueryTypeInfo() and that routine always returns
  69704. ** WRC_Continue (0). So the following branch is never taken. */
  69705. if( NEVER(rc) ) break;
  69706. }
  69707. p = p->pPrior;
  69708. }
  69709. pWalker->walkerDepth--;
  69710. return rc & WRC_Abort;
  69711. }
  69712. /************** End of walker.c **********************************************/
  69713. /************** Begin file resolve.c *****************************************/
  69714. /*
  69715. ** 2008 August 18
  69716. **
  69717. ** The author disclaims copyright to this source code. In place of
  69718. ** a legal notice, here is a blessing:
  69719. **
  69720. ** May you do good and not evil.
  69721. ** May you find forgiveness for yourself and forgive others.
  69722. ** May you share freely, never taking more than you give.
  69723. **
  69724. *************************************************************************
  69725. **
  69726. ** This file contains routines used for walking the parser tree and
  69727. ** resolve all identifiers by associating them with a particular
  69728. ** table and column.
  69729. */
  69730. /* #include <stdlib.h> */
  69731. /* #include <string.h> */
  69732. /*
  69733. ** Walk the expression tree pExpr and increase the aggregate function
  69734. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  69735. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  69736. ** outer query into an inner subquery.
  69737. **
  69738. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  69739. ** is a helper function - a callback for the tree walker.
  69740. */
  69741. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  69742. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
  69743. return WRC_Continue;
  69744. }
  69745. static void incrAggFunctionDepth(Expr *pExpr, int N){
  69746. if( N>0 ){
  69747. Walker w;
  69748. memset(&w, 0, sizeof(w));
  69749. w.xExprCallback = incrAggDepth;
  69750. w.u.i = N;
  69751. sqlite3WalkExpr(&w, pExpr);
  69752. }
  69753. }
  69754. /*
  69755. ** Turn the pExpr expression into an alias for the iCol-th column of the
  69756. ** result set in pEList.
  69757. **
  69758. ** If the result set column is a simple column reference, then this routine
  69759. ** makes an exact copy. But for any other kind of expression, this
  69760. ** routine make a copy of the result set column as the argument to the
  69761. ** TK_AS operator. The TK_AS operator causes the expression to be
  69762. ** evaluated just once and then reused for each alias.
  69763. **
  69764. ** The reason for suppressing the TK_AS term when the expression is a simple
  69765. ** column reference is so that the column reference will be recognized as
  69766. ** usable by indices within the WHERE clause processing logic.
  69767. **
  69768. ** The TK_AS operator is inhibited if zType[0]=='G'. This means
  69769. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  69770. **
  69771. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  69772. **
  69773. ** Is equivalent to:
  69774. **
  69775. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  69776. **
  69777. ** The result of random()%5 in the GROUP BY clause is probably different
  69778. ** from the result in the result-set. On the other hand Standard SQL does
  69779. ** not allow the GROUP BY clause to contain references to result-set columns.
  69780. ** So this should never come up in well-formed queries.
  69781. **
  69782. ** If the reference is followed by a COLLATE operator, then make sure
  69783. ** the COLLATE operator is preserved. For example:
  69784. **
  69785. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  69786. **
  69787. ** Should be transformed into:
  69788. **
  69789. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  69790. **
  69791. ** The nSubquery parameter specifies how many levels of subquery the
  69792. ** alias is removed from the original expression. The usually value is
  69793. ** zero but it might be more if the alias is contained within a subquery
  69794. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  69795. ** structures must be increased by the nSubquery amount.
  69796. */
  69797. static void resolveAlias(
  69798. Parse *pParse, /* Parsing context */
  69799. ExprList *pEList, /* A result set */
  69800. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  69801. Expr *pExpr, /* Transform this into an alias to the result set */
  69802. const char *zType, /* "GROUP" or "ORDER" or "" */
  69803. int nSubquery /* Number of subqueries that the label is moving */
  69804. ){
  69805. Expr *pOrig; /* The iCol-th column of the result set */
  69806. Expr *pDup; /* Copy of pOrig */
  69807. sqlite3 *db; /* The database connection */
  69808. assert( iCol>=0 && iCol<pEList->nExpr );
  69809. pOrig = pEList->a[iCol].pExpr;
  69810. assert( pOrig!=0 );
  69811. assert( pOrig->flags & EP_Resolved );
  69812. db = pParse->db;
  69813. pDup = sqlite3ExprDup(db, pOrig, 0);
  69814. if( pDup==0 ) return;
  69815. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  69816. incrAggFunctionDepth(pDup, nSubquery);
  69817. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  69818. if( pDup==0 ) return;
  69819. ExprSetProperty(pDup, EP_Skip);
  69820. if( pEList->a[iCol].iAlias==0 ){
  69821. pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
  69822. }
  69823. pDup->iTable = pEList->a[iCol].iAlias;
  69824. }
  69825. if( pExpr->op==TK_COLLATE ){
  69826. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  69827. }
  69828. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  69829. ** prevents ExprDelete() from deleting the Expr structure itself,
  69830. ** allowing it to be repopulated by the memcpy() on the following line.
  69831. ** The pExpr->u.zToken might point into memory that will be freed by the
  69832. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  69833. ** make a copy of the token before doing the sqlite3DbFree().
  69834. */
  69835. ExprSetProperty(pExpr, EP_Static);
  69836. sqlite3ExprDelete(db, pExpr);
  69837. memcpy(pExpr, pDup, sizeof(*pExpr));
  69838. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  69839. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  69840. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  69841. pExpr->flags |= EP_MemToken;
  69842. }
  69843. sqlite3DbFree(db, pDup);
  69844. }
  69845. /*
  69846. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  69847. **
  69848. ** Return FALSE if the USING clause is NULL or if it does not contain
  69849. ** zCol.
  69850. */
  69851. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  69852. if( pUsing ){
  69853. int k;
  69854. for(k=0; k<pUsing->nId; k++){
  69855. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  69856. }
  69857. }
  69858. return 0;
  69859. }
  69860. /*
  69861. ** Subqueries stores the original database, table and column names for their
  69862. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  69863. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  69864. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  69865. ** match anything.
  69866. */
  69867. SQLITE_PRIVATE int sqlite3MatchSpanName(
  69868. const char *zSpan,
  69869. const char *zCol,
  69870. const char *zTab,
  69871. const char *zDb
  69872. ){
  69873. int n;
  69874. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  69875. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  69876. return 0;
  69877. }
  69878. zSpan += n+1;
  69879. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  69880. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  69881. return 0;
  69882. }
  69883. zSpan += n+1;
  69884. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  69885. return 0;
  69886. }
  69887. return 1;
  69888. }
  69889. /*
  69890. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  69891. ** that name in the set of source tables in pSrcList and make the pExpr
  69892. ** expression node refer back to that source column. The following changes
  69893. ** are made to pExpr:
  69894. **
  69895. ** pExpr->iDb Set the index in db->aDb[] of the database X
  69896. ** (even if X is implied).
  69897. ** pExpr->iTable Set to the cursor number for the table obtained
  69898. ** from pSrcList.
  69899. ** pExpr->pTab Points to the Table structure of X.Y (even if
  69900. ** X and/or Y are implied.)
  69901. ** pExpr->iColumn Set to the column number within the table.
  69902. ** pExpr->op Set to TK_COLUMN.
  69903. ** pExpr->pLeft Any expression this points to is deleted
  69904. ** pExpr->pRight Any expression this points to is deleted.
  69905. **
  69906. ** The zDb variable is the name of the database (the "X"). This value may be
  69907. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  69908. ** can be used. The zTable variable is the name of the table (the "Y"). This
  69909. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  69910. ** means that the form of the name is Z and that columns from any table
  69911. ** can be used.
  69912. **
  69913. ** If the name cannot be resolved unambiguously, leave an error message
  69914. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  69915. */
  69916. static int lookupName(
  69917. Parse *pParse, /* The parsing context */
  69918. const char *zDb, /* Name of the database containing table, or NULL */
  69919. const char *zTab, /* Name of table containing column, or NULL */
  69920. const char *zCol, /* Name of the column. */
  69921. NameContext *pNC, /* The name context used to resolve the name */
  69922. Expr *pExpr /* Make this EXPR node point to the selected column */
  69923. ){
  69924. int i, j; /* Loop counters */
  69925. int cnt = 0; /* Number of matching column names */
  69926. int cntTab = 0; /* Number of matching table names */
  69927. int nSubquery = 0; /* How many levels of subquery */
  69928. sqlite3 *db = pParse->db; /* The database connection */
  69929. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  69930. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  69931. NameContext *pTopNC = pNC; /* First namecontext in the list */
  69932. Schema *pSchema = 0; /* Schema of the expression */
  69933. int isTrigger = 0;
  69934. assert( pNC ); /* the name context cannot be NULL. */
  69935. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  69936. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  69937. /* Initialize the node to no-match */
  69938. pExpr->iTable = -1;
  69939. pExpr->pTab = 0;
  69940. ExprSetVVAProperty(pExpr, EP_NoReduce);
  69941. /* Translate the schema name in zDb into a pointer to the corresponding
  69942. ** schema. If not found, pSchema will remain NULL and nothing will match
  69943. ** resulting in an appropriate error message toward the end of this routine
  69944. */
  69945. if( zDb ){
  69946. testcase( pNC->ncFlags & NC_PartIdx );
  69947. testcase( pNC->ncFlags & NC_IsCheck );
  69948. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  69949. /* Silently ignore database qualifiers inside CHECK constraints and partial
  69950. ** indices. Do not raise errors because that might break legacy and
  69951. ** because it does not hurt anything to just ignore the database name. */
  69952. zDb = 0;
  69953. }else{
  69954. for(i=0; i<db->nDb; i++){
  69955. assert( db->aDb[i].zName );
  69956. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  69957. pSchema = db->aDb[i].pSchema;
  69958. break;
  69959. }
  69960. }
  69961. }
  69962. }
  69963. /* Start at the inner-most context and move outward until a match is found */
  69964. while( pNC && cnt==0 ){
  69965. ExprList *pEList;
  69966. SrcList *pSrcList = pNC->pSrcList;
  69967. if( pSrcList ){
  69968. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  69969. Table *pTab;
  69970. Column *pCol;
  69971. pTab = pItem->pTab;
  69972. assert( pTab!=0 && pTab->zName!=0 );
  69973. assert( pTab->nCol>0 );
  69974. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  69975. int hit = 0;
  69976. pEList = pItem->pSelect->pEList;
  69977. for(j=0; j<pEList->nExpr; j++){
  69978. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  69979. cnt++;
  69980. cntTab = 2;
  69981. pMatch = pItem;
  69982. pExpr->iColumn = j;
  69983. hit = 1;
  69984. }
  69985. }
  69986. if( hit || zTab==0 ) continue;
  69987. }
  69988. if( zDb && pTab->pSchema!=pSchema ){
  69989. continue;
  69990. }
  69991. if( zTab ){
  69992. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  69993. assert( zTabName!=0 );
  69994. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  69995. continue;
  69996. }
  69997. }
  69998. if( 0==(cntTab++) ){
  69999. pMatch = pItem;
  70000. }
  70001. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  70002. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  70003. /* If there has been exactly one prior match and this match
  70004. ** is for the right-hand table of a NATURAL JOIN or is in a
  70005. ** USING clause, then skip this match.
  70006. */
  70007. if( cnt==1 ){
  70008. if( pItem->jointype & JT_NATURAL ) continue;
  70009. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  70010. }
  70011. cnt++;
  70012. pMatch = pItem;
  70013. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  70014. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  70015. break;
  70016. }
  70017. }
  70018. }
  70019. if( pMatch ){
  70020. pExpr->iTable = pMatch->iCursor;
  70021. pExpr->pTab = pMatch->pTab;
  70022. pSchema = pExpr->pTab->pSchema;
  70023. }
  70024. } /* if( pSrcList ) */
  70025. #ifndef SQLITE_OMIT_TRIGGER
  70026. /* If we have not already resolved the name, then maybe
  70027. ** it is a new.* or old.* trigger argument reference
  70028. */
  70029. if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
  70030. int op = pParse->eTriggerOp;
  70031. Table *pTab = 0;
  70032. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  70033. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  70034. pExpr->iTable = 1;
  70035. pTab = pParse->pTriggerTab;
  70036. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  70037. pExpr->iTable = 0;
  70038. pTab = pParse->pTriggerTab;
  70039. }
  70040. if( pTab ){
  70041. int iCol;
  70042. pSchema = pTab->pSchema;
  70043. cntTab++;
  70044. for(iCol=0; iCol<pTab->nCol; iCol++){
  70045. Column *pCol = &pTab->aCol[iCol];
  70046. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  70047. if( iCol==pTab->iPKey ){
  70048. iCol = -1;
  70049. }
  70050. break;
  70051. }
  70052. }
  70053. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
  70054. iCol = -1; /* IMP: R-44911-55124 */
  70055. }
  70056. if( iCol<pTab->nCol ){
  70057. cnt++;
  70058. if( iCol<0 ){
  70059. pExpr->affinity = SQLITE_AFF_INTEGER;
  70060. }else if( pExpr->iTable==0 ){
  70061. testcase( iCol==31 );
  70062. testcase( iCol==32 );
  70063. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  70064. }else{
  70065. testcase( iCol==31 );
  70066. testcase( iCol==32 );
  70067. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  70068. }
  70069. pExpr->iColumn = (i16)iCol;
  70070. pExpr->pTab = pTab;
  70071. isTrigger = 1;
  70072. }
  70073. }
  70074. }
  70075. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  70076. /*
  70077. ** Perhaps the name is a reference to the ROWID
  70078. */
  70079. if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
  70080. cnt = 1;
  70081. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  70082. pExpr->affinity = SQLITE_AFF_INTEGER;
  70083. }
  70084. /*
  70085. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  70086. ** might refer to an result-set alias. This happens, for example, when
  70087. ** we are resolving names in the WHERE clause of the following command:
  70088. **
  70089. ** SELECT a+b AS x FROM table WHERE x<10;
  70090. **
  70091. ** In cases like this, replace pExpr with a copy of the expression that
  70092. ** forms the result set entry ("a+b" in the example) and return immediately.
  70093. ** Note that the expression in the result set should have already been
  70094. ** resolved by the time the WHERE clause is resolved.
  70095. **
  70096. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  70097. ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
  70098. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  70099. ** is supported for backwards compatibility only. TO DO: Issue a warning
  70100. ** on sqlite3_log() whenever the capability is used.
  70101. */
  70102. if( (pEList = pNC->pEList)!=0
  70103. && zTab==0
  70104. && cnt==0
  70105. ){
  70106. for(j=0; j<pEList->nExpr; j++){
  70107. char *zAs = pEList->a[j].zName;
  70108. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  70109. Expr *pOrig;
  70110. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  70111. assert( pExpr->x.pList==0 );
  70112. assert( pExpr->x.pSelect==0 );
  70113. pOrig = pEList->a[j].pExpr;
  70114. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  70115. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  70116. return WRC_Abort;
  70117. }
  70118. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  70119. cnt = 1;
  70120. pMatch = 0;
  70121. assert( zTab==0 && zDb==0 );
  70122. goto lookupname_end;
  70123. }
  70124. }
  70125. }
  70126. /* Advance to the next name context. The loop will exit when either
  70127. ** we have a match (cnt>0) or when we run out of name contexts.
  70128. */
  70129. if( cnt==0 ){
  70130. pNC = pNC->pNext;
  70131. nSubquery++;
  70132. }
  70133. }
  70134. /*
  70135. ** If X and Y are NULL (in other words if only the column name Z is
  70136. ** supplied) and the value of Z is enclosed in double-quotes, then
  70137. ** Z is a string literal if it doesn't match any column names. In that
  70138. ** case, we need to return right away and not make any changes to
  70139. ** pExpr.
  70140. **
  70141. ** Because no reference was made to outer contexts, the pNC->nRef
  70142. ** fields are not changed in any context.
  70143. */
  70144. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  70145. pExpr->op = TK_STRING;
  70146. pExpr->pTab = 0;
  70147. return WRC_Prune;
  70148. }
  70149. /*
  70150. ** cnt==0 means there was not match. cnt>1 means there were two or
  70151. ** more matches. Either way, we have an error.
  70152. */
  70153. if( cnt!=1 ){
  70154. const char *zErr;
  70155. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  70156. if( zDb ){
  70157. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  70158. }else if( zTab ){
  70159. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  70160. }else{
  70161. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  70162. }
  70163. pParse->checkSchema = 1;
  70164. pTopNC->nErr++;
  70165. }
  70166. /* If a column from a table in pSrcList is referenced, then record
  70167. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  70168. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  70169. ** column number is greater than the number of bits in the bitmask
  70170. ** then set the high-order bit of the bitmask.
  70171. */
  70172. if( pExpr->iColumn>=0 && pMatch!=0 ){
  70173. int n = pExpr->iColumn;
  70174. testcase( n==BMS-1 );
  70175. if( n>=BMS ){
  70176. n = BMS-1;
  70177. }
  70178. assert( pMatch->iCursor==pExpr->iTable );
  70179. pMatch->colUsed |= ((Bitmask)1)<<n;
  70180. }
  70181. /* Clean up and return
  70182. */
  70183. sqlite3ExprDelete(db, pExpr->pLeft);
  70184. pExpr->pLeft = 0;
  70185. sqlite3ExprDelete(db, pExpr->pRight);
  70186. pExpr->pRight = 0;
  70187. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  70188. lookupname_end:
  70189. if( cnt==1 ){
  70190. assert( pNC!=0 );
  70191. if( pExpr->op!=TK_AS ){
  70192. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  70193. }
  70194. /* Increment the nRef value on all name contexts from TopNC up to
  70195. ** the point where the name matched. */
  70196. for(;;){
  70197. assert( pTopNC!=0 );
  70198. pTopNC->nRef++;
  70199. if( pTopNC==pNC ) break;
  70200. pTopNC = pTopNC->pNext;
  70201. }
  70202. return WRC_Prune;
  70203. } else {
  70204. return WRC_Abort;
  70205. }
  70206. }
  70207. /*
  70208. ** Allocate and return a pointer to an expression to load the column iCol
  70209. ** from datasource iSrc in SrcList pSrc.
  70210. */
  70211. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  70212. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  70213. if( p ){
  70214. struct SrcList_item *pItem = &pSrc->a[iSrc];
  70215. p->pTab = pItem->pTab;
  70216. p->iTable = pItem->iCursor;
  70217. if( p->pTab->iPKey==iCol ){
  70218. p->iColumn = -1;
  70219. }else{
  70220. p->iColumn = (ynVar)iCol;
  70221. testcase( iCol==BMS );
  70222. testcase( iCol==BMS-1 );
  70223. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  70224. }
  70225. ExprSetProperty(p, EP_Resolved);
  70226. }
  70227. return p;
  70228. }
  70229. /*
  70230. ** Report an error that an expression is not valid for a partial index WHERE
  70231. ** clause.
  70232. */
  70233. static void notValidPartIdxWhere(
  70234. Parse *pParse, /* Leave error message here */
  70235. NameContext *pNC, /* The name context */
  70236. const char *zMsg /* Type of error */
  70237. ){
  70238. if( (pNC->ncFlags & NC_PartIdx)!=0 ){
  70239. sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
  70240. zMsg);
  70241. }
  70242. }
  70243. #ifndef SQLITE_OMIT_CHECK
  70244. /*
  70245. ** Report an error that an expression is not valid for a CHECK constraint.
  70246. */
  70247. static void notValidCheckConstraint(
  70248. Parse *pParse, /* Leave error message here */
  70249. NameContext *pNC, /* The name context */
  70250. const char *zMsg /* Type of error */
  70251. ){
  70252. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  70253. sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
  70254. }
  70255. }
  70256. #else
  70257. # define notValidCheckConstraint(P,N,M)
  70258. #endif
  70259. /*
  70260. ** Expression p should encode a floating point value between 1.0 and 0.0.
  70261. ** Return 1024 times this value. Or return -1 if p is not a floating point
  70262. ** value between 1.0 and 0.0.
  70263. */
  70264. static int exprProbability(Expr *p){
  70265. double r = -1.0;
  70266. if( p->op!=TK_FLOAT ) return -1;
  70267. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  70268. assert( r>=0.0 );
  70269. if( r>1.0 ) return -1;
  70270. return (int)(r*1000.0);
  70271. }
  70272. /*
  70273. ** This routine is callback for sqlite3WalkExpr().
  70274. **
  70275. ** Resolve symbolic names into TK_COLUMN operators for the current
  70276. ** node in the expression tree. Return 0 to continue the search down
  70277. ** the tree or 2 to abort the tree walk.
  70278. **
  70279. ** This routine also does error checking and name resolution for
  70280. ** function names. The operator for aggregate functions is changed
  70281. ** to TK_AGG_FUNCTION.
  70282. */
  70283. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  70284. NameContext *pNC;
  70285. Parse *pParse;
  70286. pNC = pWalker->u.pNC;
  70287. assert( pNC!=0 );
  70288. pParse = pNC->pParse;
  70289. assert( pParse==pWalker->pParse );
  70290. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  70291. ExprSetProperty(pExpr, EP_Resolved);
  70292. #ifndef NDEBUG
  70293. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  70294. SrcList *pSrcList = pNC->pSrcList;
  70295. int i;
  70296. for(i=0; i<pNC->pSrcList->nSrc; i++){
  70297. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  70298. }
  70299. }
  70300. #endif
  70301. switch( pExpr->op ){
  70302. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  70303. /* The special operator TK_ROW means use the rowid for the first
  70304. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  70305. ** clause processing on UPDATE and DELETE statements.
  70306. */
  70307. case TK_ROW: {
  70308. SrcList *pSrcList = pNC->pSrcList;
  70309. struct SrcList_item *pItem;
  70310. assert( pSrcList && pSrcList->nSrc==1 );
  70311. pItem = pSrcList->a;
  70312. pExpr->op = TK_COLUMN;
  70313. pExpr->pTab = pItem->pTab;
  70314. pExpr->iTable = pItem->iCursor;
  70315. pExpr->iColumn = -1;
  70316. pExpr->affinity = SQLITE_AFF_INTEGER;
  70317. break;
  70318. }
  70319. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  70320. /* A lone identifier is the name of a column.
  70321. */
  70322. case TK_ID: {
  70323. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  70324. }
  70325. /* A table name and column name: ID.ID
  70326. ** Or a database, table and column: ID.ID.ID
  70327. */
  70328. case TK_DOT: {
  70329. const char *zColumn;
  70330. const char *zTable;
  70331. const char *zDb;
  70332. Expr *pRight;
  70333. /* if( pSrcList==0 ) break; */
  70334. pRight = pExpr->pRight;
  70335. if( pRight->op==TK_ID ){
  70336. zDb = 0;
  70337. zTable = pExpr->pLeft->u.zToken;
  70338. zColumn = pRight->u.zToken;
  70339. }else{
  70340. assert( pRight->op==TK_DOT );
  70341. zDb = pExpr->pLeft->u.zToken;
  70342. zTable = pRight->pLeft->u.zToken;
  70343. zColumn = pRight->pRight->u.zToken;
  70344. }
  70345. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  70346. }
  70347. /* Resolve function names
  70348. */
  70349. case TK_CONST_FUNC:
  70350. case TK_FUNCTION: {
  70351. ExprList *pList = pExpr->x.pList; /* The argument list */
  70352. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  70353. int no_such_func = 0; /* True if no such function exists */
  70354. int wrong_num_args = 0; /* True if wrong number of arguments */
  70355. int is_agg = 0; /* True if is an aggregate function */
  70356. int auth; /* Authorization to use the function */
  70357. int nId; /* Number of characters in function name */
  70358. const char *zId; /* The function name. */
  70359. FuncDef *pDef; /* Information about the function */
  70360. u8 enc = ENC(pParse->db); /* The database encoding */
  70361. testcase( pExpr->op==TK_CONST_FUNC );
  70362. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  70363. notValidPartIdxWhere(pParse, pNC, "functions");
  70364. zId = pExpr->u.zToken;
  70365. nId = sqlite3Strlen30(zId);
  70366. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  70367. if( pDef==0 ){
  70368. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  70369. if( pDef==0 ){
  70370. no_such_func = 1;
  70371. }else{
  70372. wrong_num_args = 1;
  70373. }
  70374. }else{
  70375. is_agg = pDef->xFunc==0;
  70376. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  70377. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  70378. if( n==2 ){
  70379. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  70380. if( pExpr->iTable<0 ){
  70381. sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
  70382. "constant between 0.0 and 1.0");
  70383. pNC->nErr++;
  70384. }
  70385. }else{
  70386. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
  70387. ** likelihood(X, 0.0625).
  70388. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
  70389. ** likelihood(X,0.0625). */
  70390. pExpr->iTable = 62; /* TUNING: Default 2nd arg to unlikely() is 0.0625 */
  70391. }
  70392. }
  70393. }
  70394. #ifndef SQLITE_OMIT_AUTHORIZATION
  70395. if( pDef ){
  70396. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  70397. if( auth!=SQLITE_OK ){
  70398. if( auth==SQLITE_DENY ){
  70399. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  70400. pDef->zName);
  70401. pNC->nErr++;
  70402. }
  70403. pExpr->op = TK_NULL;
  70404. return WRC_Prune;
  70405. }
  70406. }
  70407. #endif
  70408. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  70409. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  70410. pNC->nErr++;
  70411. is_agg = 0;
  70412. }else if( no_such_func && pParse->db->init.busy==0 ){
  70413. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  70414. pNC->nErr++;
  70415. }else if( wrong_num_args ){
  70416. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  70417. nId, zId);
  70418. pNC->nErr++;
  70419. }
  70420. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  70421. sqlite3WalkExprList(pWalker, pList);
  70422. if( is_agg ){
  70423. NameContext *pNC2 = pNC;
  70424. pExpr->op = TK_AGG_FUNCTION;
  70425. pExpr->op2 = 0;
  70426. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  70427. pExpr->op2++;
  70428. pNC2 = pNC2->pNext;
  70429. }
  70430. if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
  70431. pNC->ncFlags |= NC_AllowAgg;
  70432. }
  70433. /* FIX ME: Compute pExpr->affinity based on the expected return
  70434. ** type of the function
  70435. */
  70436. return WRC_Prune;
  70437. }
  70438. #ifndef SQLITE_OMIT_SUBQUERY
  70439. case TK_SELECT:
  70440. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  70441. #endif
  70442. case TK_IN: {
  70443. testcase( pExpr->op==TK_IN );
  70444. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  70445. int nRef = pNC->nRef;
  70446. notValidCheckConstraint(pParse, pNC, "subqueries");
  70447. notValidPartIdxWhere(pParse, pNC, "subqueries");
  70448. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  70449. assert( pNC->nRef>=nRef );
  70450. if( nRef!=pNC->nRef ){
  70451. ExprSetProperty(pExpr, EP_VarSelect);
  70452. }
  70453. }
  70454. break;
  70455. }
  70456. case TK_VARIABLE: {
  70457. notValidCheckConstraint(pParse, pNC, "parameters");
  70458. notValidPartIdxWhere(pParse, pNC, "parameters");
  70459. break;
  70460. }
  70461. }
  70462. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  70463. }
  70464. /*
  70465. ** pEList is a list of expressions which are really the result set of the
  70466. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  70467. ** This routine checks to see if pE is a simple identifier which corresponds
  70468. ** to the AS-name of one of the terms of the expression list. If it is,
  70469. ** this routine return an integer between 1 and N where N is the number of
  70470. ** elements in pEList, corresponding to the matching entry. If there is
  70471. ** no match, or if pE is not a simple identifier, then this routine
  70472. ** return 0.
  70473. **
  70474. ** pEList has been resolved. pE has not.
  70475. */
  70476. static int resolveAsName(
  70477. Parse *pParse, /* Parsing context for error messages */
  70478. ExprList *pEList, /* List of expressions to scan */
  70479. Expr *pE /* Expression we are trying to match */
  70480. ){
  70481. int i; /* Loop counter */
  70482. UNUSED_PARAMETER(pParse);
  70483. if( pE->op==TK_ID ){
  70484. char *zCol = pE->u.zToken;
  70485. for(i=0; i<pEList->nExpr; i++){
  70486. char *zAs = pEList->a[i].zName;
  70487. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  70488. return i+1;
  70489. }
  70490. }
  70491. }
  70492. return 0;
  70493. }
  70494. /*
  70495. ** pE is a pointer to an expression which is a single term in the
  70496. ** ORDER BY of a compound SELECT. The expression has not been
  70497. ** name resolved.
  70498. **
  70499. ** At the point this routine is called, we already know that the
  70500. ** ORDER BY term is not an integer index into the result set. That
  70501. ** case is handled by the calling routine.
  70502. **
  70503. ** Attempt to match pE against result set columns in the left-most
  70504. ** SELECT statement. Return the index i of the matching column,
  70505. ** as an indication to the caller that it should sort by the i-th column.
  70506. ** The left-most column is 1. In other words, the value returned is the
  70507. ** same integer value that would be used in the SQL statement to indicate
  70508. ** the column.
  70509. **
  70510. ** If there is no match, return 0. Return -1 if an error occurs.
  70511. */
  70512. static int resolveOrderByTermToExprList(
  70513. Parse *pParse, /* Parsing context for error messages */
  70514. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  70515. Expr *pE /* The specific ORDER BY term */
  70516. ){
  70517. int i; /* Loop counter */
  70518. ExprList *pEList; /* The columns of the result set */
  70519. NameContext nc; /* Name context for resolving pE */
  70520. sqlite3 *db; /* Database connection */
  70521. int rc; /* Return code from subprocedures */
  70522. u8 savedSuppErr; /* Saved value of db->suppressErr */
  70523. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  70524. pEList = pSelect->pEList;
  70525. /* Resolve all names in the ORDER BY term expression
  70526. */
  70527. memset(&nc, 0, sizeof(nc));
  70528. nc.pParse = pParse;
  70529. nc.pSrcList = pSelect->pSrc;
  70530. nc.pEList = pEList;
  70531. nc.ncFlags = NC_AllowAgg;
  70532. nc.nErr = 0;
  70533. db = pParse->db;
  70534. savedSuppErr = db->suppressErr;
  70535. db->suppressErr = 1;
  70536. rc = sqlite3ResolveExprNames(&nc, pE);
  70537. db->suppressErr = savedSuppErr;
  70538. if( rc ) return 0;
  70539. /* Try to match the ORDER BY expression against an expression
  70540. ** in the result set. Return an 1-based index of the matching
  70541. ** result-set entry.
  70542. */
  70543. for(i=0; i<pEList->nExpr; i++){
  70544. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  70545. return i+1;
  70546. }
  70547. }
  70548. /* If no match, return 0. */
  70549. return 0;
  70550. }
  70551. /*
  70552. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  70553. */
  70554. static void resolveOutOfRangeError(
  70555. Parse *pParse, /* The error context into which to write the error */
  70556. const char *zType, /* "ORDER" or "GROUP" */
  70557. int i, /* The index (1-based) of the term out of range */
  70558. int mx /* Largest permissible value of i */
  70559. ){
  70560. sqlite3ErrorMsg(pParse,
  70561. "%r %s BY term out of range - should be "
  70562. "between 1 and %d", i, zType, mx);
  70563. }
  70564. /*
  70565. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  70566. ** each term of the ORDER BY clause is a constant integer between 1
  70567. ** and N where N is the number of columns in the compound SELECT.
  70568. **
  70569. ** ORDER BY terms that are already an integer between 1 and N are
  70570. ** unmodified. ORDER BY terms that are integers outside the range of
  70571. ** 1 through N generate an error. ORDER BY terms that are expressions
  70572. ** are matched against result set expressions of compound SELECT
  70573. ** beginning with the left-most SELECT and working toward the right.
  70574. ** At the first match, the ORDER BY expression is transformed into
  70575. ** the integer column number.
  70576. **
  70577. ** Return the number of errors seen.
  70578. */
  70579. static int resolveCompoundOrderBy(
  70580. Parse *pParse, /* Parsing context. Leave error messages here */
  70581. Select *pSelect /* The SELECT statement containing the ORDER BY */
  70582. ){
  70583. int i;
  70584. ExprList *pOrderBy;
  70585. ExprList *pEList;
  70586. sqlite3 *db;
  70587. int moreToDo = 1;
  70588. pOrderBy = pSelect->pOrderBy;
  70589. if( pOrderBy==0 ) return 0;
  70590. db = pParse->db;
  70591. #if SQLITE_MAX_COLUMN
  70592. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  70593. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  70594. return 1;
  70595. }
  70596. #endif
  70597. for(i=0; i<pOrderBy->nExpr; i++){
  70598. pOrderBy->a[i].done = 0;
  70599. }
  70600. pSelect->pNext = 0;
  70601. while( pSelect->pPrior ){
  70602. pSelect->pPrior->pNext = pSelect;
  70603. pSelect = pSelect->pPrior;
  70604. }
  70605. while( pSelect && moreToDo ){
  70606. struct ExprList_item *pItem;
  70607. moreToDo = 0;
  70608. pEList = pSelect->pEList;
  70609. assert( pEList!=0 );
  70610. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  70611. int iCol = -1;
  70612. Expr *pE, *pDup;
  70613. if( pItem->done ) continue;
  70614. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  70615. if( sqlite3ExprIsInteger(pE, &iCol) ){
  70616. if( iCol<=0 || iCol>pEList->nExpr ){
  70617. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  70618. return 1;
  70619. }
  70620. }else{
  70621. iCol = resolveAsName(pParse, pEList, pE);
  70622. if( iCol==0 ){
  70623. pDup = sqlite3ExprDup(db, pE, 0);
  70624. if( !db->mallocFailed ){
  70625. assert(pDup);
  70626. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  70627. }
  70628. sqlite3ExprDelete(db, pDup);
  70629. }
  70630. }
  70631. if( iCol>0 ){
  70632. /* Convert the ORDER BY term into an integer column number iCol,
  70633. ** taking care to preserve the COLLATE clause if it exists */
  70634. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  70635. if( pNew==0 ) return 1;
  70636. pNew->flags |= EP_IntValue;
  70637. pNew->u.iValue = iCol;
  70638. if( pItem->pExpr==pE ){
  70639. pItem->pExpr = pNew;
  70640. }else{
  70641. assert( pItem->pExpr->op==TK_COLLATE );
  70642. assert( pItem->pExpr->pLeft==pE );
  70643. pItem->pExpr->pLeft = pNew;
  70644. }
  70645. sqlite3ExprDelete(db, pE);
  70646. pItem->iOrderByCol = (u16)iCol;
  70647. pItem->done = 1;
  70648. }else{
  70649. moreToDo = 1;
  70650. }
  70651. }
  70652. pSelect = pSelect->pNext;
  70653. }
  70654. for(i=0; i<pOrderBy->nExpr; i++){
  70655. if( pOrderBy->a[i].done==0 ){
  70656. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  70657. "column in the result set", i+1);
  70658. return 1;
  70659. }
  70660. }
  70661. return 0;
  70662. }
  70663. /*
  70664. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  70665. ** the SELECT statement pSelect. If any term is reference to a
  70666. ** result set expression (as determined by the ExprList.a.iOrderByCol field)
  70667. ** then convert that term into a copy of the corresponding result set
  70668. ** column.
  70669. **
  70670. ** If any errors are detected, add an error message to pParse and
  70671. ** return non-zero. Return zero if no errors are seen.
  70672. */
  70673. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  70674. Parse *pParse, /* Parsing context. Leave error messages here */
  70675. Select *pSelect, /* The SELECT statement containing the clause */
  70676. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  70677. const char *zType /* "ORDER" or "GROUP" */
  70678. ){
  70679. int i;
  70680. sqlite3 *db = pParse->db;
  70681. ExprList *pEList;
  70682. struct ExprList_item *pItem;
  70683. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  70684. #if SQLITE_MAX_COLUMN
  70685. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  70686. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  70687. return 1;
  70688. }
  70689. #endif
  70690. pEList = pSelect->pEList;
  70691. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  70692. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  70693. if( pItem->iOrderByCol ){
  70694. if( pItem->iOrderByCol>pEList->nExpr ){
  70695. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  70696. return 1;
  70697. }
  70698. resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
  70699. }
  70700. }
  70701. return 0;
  70702. }
  70703. /*
  70704. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  70705. ** The Name context of the SELECT statement is pNC. zType is either
  70706. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  70707. **
  70708. ** This routine resolves each term of the clause into an expression.
  70709. ** If the order-by term is an integer I between 1 and N (where N is the
  70710. ** number of columns in the result set of the SELECT) then the expression
  70711. ** in the resolution is a copy of the I-th result-set expression. If
  70712. ** the order-by term is an identifier that corresponds to the AS-name of
  70713. ** a result-set expression, then the term resolves to a copy of the
  70714. ** result-set expression. Otherwise, the expression is resolved in
  70715. ** the usual way - using sqlite3ResolveExprNames().
  70716. **
  70717. ** This routine returns the number of errors. If errors occur, then
  70718. ** an appropriate error message might be left in pParse. (OOM errors
  70719. ** excepted.)
  70720. */
  70721. static int resolveOrderGroupBy(
  70722. NameContext *pNC, /* The name context of the SELECT statement */
  70723. Select *pSelect, /* The SELECT statement holding pOrderBy */
  70724. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  70725. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  70726. ){
  70727. int i, j; /* Loop counters */
  70728. int iCol; /* Column number */
  70729. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  70730. Parse *pParse; /* Parsing context */
  70731. int nResult; /* Number of terms in the result set */
  70732. if( pOrderBy==0 ) return 0;
  70733. nResult = pSelect->pEList->nExpr;
  70734. pParse = pNC->pParse;
  70735. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  70736. Expr *pE = pItem->pExpr;
  70737. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  70738. if( zType[0]!='G' ){
  70739. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  70740. if( iCol>0 ){
  70741. /* If an AS-name match is found, mark this ORDER BY column as being
  70742. ** a copy of the iCol-th result-set column. The subsequent call to
  70743. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  70744. ** copy of the iCol-th result-set expression. */
  70745. pItem->iOrderByCol = (u16)iCol;
  70746. continue;
  70747. }
  70748. }
  70749. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  70750. /* The ORDER BY term is an integer constant. Again, set the column
  70751. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  70752. ** order-by term to a copy of the result-set expression */
  70753. if( iCol<1 || iCol>0xffff ){
  70754. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  70755. return 1;
  70756. }
  70757. pItem->iOrderByCol = (u16)iCol;
  70758. continue;
  70759. }
  70760. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  70761. pItem->iOrderByCol = 0;
  70762. if( sqlite3ResolveExprNames(pNC, pE) ){
  70763. return 1;
  70764. }
  70765. for(j=0; j<pSelect->pEList->nExpr; j++){
  70766. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  70767. pItem->iOrderByCol = j+1;
  70768. }
  70769. }
  70770. }
  70771. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  70772. }
  70773. /*
  70774. ** Resolve names in the SELECT statement p and all of its descendents.
  70775. */
  70776. static int resolveSelectStep(Walker *pWalker, Select *p){
  70777. NameContext *pOuterNC; /* Context that contains this SELECT */
  70778. NameContext sNC; /* Name context of this SELECT */
  70779. int isCompound; /* True if p is a compound select */
  70780. int nCompound; /* Number of compound terms processed so far */
  70781. Parse *pParse; /* Parsing context */
  70782. ExprList *pEList; /* Result set expression list */
  70783. int i; /* Loop counter */
  70784. ExprList *pGroupBy; /* The GROUP BY clause */
  70785. Select *pLeftmost; /* Left-most of SELECT of a compound */
  70786. sqlite3 *db; /* Database connection */
  70787. assert( p!=0 );
  70788. if( p->selFlags & SF_Resolved ){
  70789. return WRC_Prune;
  70790. }
  70791. pOuterNC = pWalker->u.pNC;
  70792. pParse = pWalker->pParse;
  70793. db = pParse->db;
  70794. /* Normally sqlite3SelectExpand() will be called first and will have
  70795. ** already expanded this SELECT. However, if this is a subquery within
  70796. ** an expression, sqlite3ResolveExprNames() will be called without a
  70797. ** prior call to sqlite3SelectExpand(). When that happens, let
  70798. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  70799. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  70800. ** this routine in the correct order.
  70801. */
  70802. if( (p->selFlags & SF_Expanded)==0 ){
  70803. sqlite3SelectPrep(pParse, p, pOuterNC);
  70804. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  70805. }
  70806. isCompound = p->pPrior!=0;
  70807. nCompound = 0;
  70808. pLeftmost = p;
  70809. while( p ){
  70810. assert( (p->selFlags & SF_Expanded)!=0 );
  70811. assert( (p->selFlags & SF_Resolved)==0 );
  70812. p->selFlags |= SF_Resolved;
  70813. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  70814. ** are not allowed to refer to any names, so pass an empty NameContext.
  70815. */
  70816. memset(&sNC, 0, sizeof(sNC));
  70817. sNC.pParse = pParse;
  70818. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  70819. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  70820. return WRC_Abort;
  70821. }
  70822. /* Recursively resolve names in all subqueries
  70823. */
  70824. for(i=0; i<p->pSrc->nSrc; i++){
  70825. struct SrcList_item *pItem = &p->pSrc->a[i];
  70826. if( pItem->pSelect ){
  70827. NameContext *pNC; /* Used to iterate name contexts */
  70828. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  70829. const char *zSavedContext = pParse->zAuthContext;
  70830. /* Count the total number of references to pOuterNC and all of its
  70831. ** parent contexts. After resolving references to expressions in
  70832. ** pItem->pSelect, check if this value has changed. If so, then
  70833. ** SELECT statement pItem->pSelect must be correlated. Set the
  70834. ** pItem->isCorrelated flag if this is the case. */
  70835. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  70836. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  70837. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  70838. pParse->zAuthContext = zSavedContext;
  70839. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  70840. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  70841. assert( pItem->isCorrelated==0 && nRef<=0 );
  70842. pItem->isCorrelated = (nRef!=0);
  70843. }
  70844. }
  70845. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  70846. ** resolve the result-set expression list.
  70847. */
  70848. sNC.ncFlags = NC_AllowAgg;
  70849. sNC.pSrcList = p->pSrc;
  70850. sNC.pNext = pOuterNC;
  70851. /* Resolve names in the result set. */
  70852. pEList = p->pEList;
  70853. assert( pEList!=0 );
  70854. for(i=0; i<pEList->nExpr; i++){
  70855. Expr *pX = pEList->a[i].pExpr;
  70856. if( sqlite3ResolveExprNames(&sNC, pX) ){
  70857. return WRC_Abort;
  70858. }
  70859. }
  70860. /* If there are no aggregate functions in the result-set, and no GROUP BY
  70861. ** expression, do not allow aggregates in any of the other expressions.
  70862. */
  70863. assert( (p->selFlags & SF_Aggregate)==0 );
  70864. pGroupBy = p->pGroupBy;
  70865. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  70866. p->selFlags |= SF_Aggregate;
  70867. }else{
  70868. sNC.ncFlags &= ~NC_AllowAgg;
  70869. }
  70870. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  70871. */
  70872. if( p->pHaving && !pGroupBy ){
  70873. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  70874. return WRC_Abort;
  70875. }
  70876. /* Add the output column list to the name-context before parsing the
  70877. ** other expressions in the SELECT statement. This is so that
  70878. ** expressions in the WHERE clause (etc.) can refer to expressions by
  70879. ** aliases in the result set.
  70880. **
  70881. ** Minor point: If this is the case, then the expression will be
  70882. ** re-evaluated for each reference to it.
  70883. */
  70884. sNC.pEList = p->pEList;
  70885. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  70886. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  70887. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  70888. ** outer queries
  70889. */
  70890. sNC.pNext = 0;
  70891. sNC.ncFlags |= NC_AllowAgg;
  70892. /* Process the ORDER BY clause for singleton SELECT statements.
  70893. ** The ORDER BY clause for compounds SELECT statements is handled
  70894. ** below, after all of the result-sets for all of the elements of
  70895. ** the compound have been resolved.
  70896. */
  70897. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  70898. return WRC_Abort;
  70899. }
  70900. if( db->mallocFailed ){
  70901. return WRC_Abort;
  70902. }
  70903. /* Resolve the GROUP BY clause. At the same time, make sure
  70904. ** the GROUP BY clause does not contain aggregate functions.
  70905. */
  70906. if( pGroupBy ){
  70907. struct ExprList_item *pItem;
  70908. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  70909. return WRC_Abort;
  70910. }
  70911. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  70912. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  70913. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  70914. "the GROUP BY clause");
  70915. return WRC_Abort;
  70916. }
  70917. }
  70918. }
  70919. /* Advance to the next term of the compound
  70920. */
  70921. p = p->pPrior;
  70922. nCompound++;
  70923. }
  70924. /* Resolve the ORDER BY on a compound SELECT after all terms of
  70925. ** the compound have been resolved.
  70926. */
  70927. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  70928. return WRC_Abort;
  70929. }
  70930. return WRC_Prune;
  70931. }
  70932. /*
  70933. ** This routine walks an expression tree and resolves references to
  70934. ** table columns and result-set columns. At the same time, do error
  70935. ** checking on function usage and set a flag if any aggregate functions
  70936. ** are seen.
  70937. **
  70938. ** To resolve table columns references we look for nodes (or subtrees) of the
  70939. ** form X.Y.Z or Y.Z or just Z where
  70940. **
  70941. ** X: The name of a database. Ex: "main" or "temp" or
  70942. ** the symbolic name assigned to an ATTACH-ed database.
  70943. **
  70944. ** Y: The name of a table in a FROM clause. Or in a trigger
  70945. ** one of the special names "old" or "new".
  70946. **
  70947. ** Z: The name of a column in table Y.
  70948. **
  70949. ** The node at the root of the subtree is modified as follows:
  70950. **
  70951. ** Expr.op Changed to TK_COLUMN
  70952. ** Expr.pTab Points to the Table object for X.Y
  70953. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  70954. ** Expr.iTable The VDBE cursor number for X.Y
  70955. **
  70956. **
  70957. ** To resolve result-set references, look for expression nodes of the
  70958. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  70959. ** size of an AS clause in the result-set of a SELECT. The Z expression
  70960. ** is replaced by a copy of the left-hand side of the result-set expression.
  70961. ** Table-name and function resolution occurs on the substituted expression
  70962. ** tree. For example, in:
  70963. **
  70964. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  70965. **
  70966. ** The "x" term of the order by is replaced by "a+b" to render:
  70967. **
  70968. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  70969. **
  70970. ** Function calls are checked to make sure that the function is
  70971. ** defined and that the correct number of arguments are specified.
  70972. ** If the function is an aggregate function, then the NC_HasAgg flag is
  70973. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  70974. ** If an expression contains aggregate functions then the EP_Agg
  70975. ** property on the expression is set.
  70976. **
  70977. ** An error message is left in pParse if anything is amiss. The number
  70978. ** if errors is returned.
  70979. */
  70980. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  70981. NameContext *pNC, /* Namespace to resolve expressions in. */
  70982. Expr *pExpr /* The expression to be analyzed. */
  70983. ){
  70984. u8 savedHasAgg;
  70985. Walker w;
  70986. if( pExpr==0 ) return 0;
  70987. #if SQLITE_MAX_EXPR_DEPTH>0
  70988. {
  70989. Parse *pParse = pNC->pParse;
  70990. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  70991. return 1;
  70992. }
  70993. pParse->nHeight += pExpr->nHeight;
  70994. }
  70995. #endif
  70996. savedHasAgg = pNC->ncFlags & NC_HasAgg;
  70997. pNC->ncFlags &= ~NC_HasAgg;
  70998. memset(&w, 0, sizeof(w));
  70999. w.xExprCallback = resolveExprStep;
  71000. w.xSelectCallback = resolveSelectStep;
  71001. w.pParse = pNC->pParse;
  71002. w.u.pNC = pNC;
  71003. sqlite3WalkExpr(&w, pExpr);
  71004. #if SQLITE_MAX_EXPR_DEPTH>0
  71005. pNC->pParse->nHeight -= pExpr->nHeight;
  71006. #endif
  71007. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  71008. ExprSetProperty(pExpr, EP_Error);
  71009. }
  71010. if( pNC->ncFlags & NC_HasAgg ){
  71011. ExprSetProperty(pExpr, EP_Agg);
  71012. }else if( savedHasAgg ){
  71013. pNC->ncFlags |= NC_HasAgg;
  71014. }
  71015. return ExprHasProperty(pExpr, EP_Error);
  71016. }
  71017. /*
  71018. ** Resolve all names in all expressions of a SELECT and in all
  71019. ** decendents of the SELECT, including compounds off of p->pPrior,
  71020. ** subqueries in expressions, and subqueries used as FROM clause
  71021. ** terms.
  71022. **
  71023. ** See sqlite3ResolveExprNames() for a description of the kinds of
  71024. ** transformations that occur.
  71025. **
  71026. ** All SELECT statements should have been expanded using
  71027. ** sqlite3SelectExpand() prior to invoking this routine.
  71028. */
  71029. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  71030. Parse *pParse, /* The parser context */
  71031. Select *p, /* The SELECT statement being coded. */
  71032. NameContext *pOuterNC /* Name context for parent SELECT statement */
  71033. ){
  71034. Walker w;
  71035. assert( p!=0 );
  71036. memset(&w, 0, sizeof(w));
  71037. w.xExprCallback = resolveExprStep;
  71038. w.xSelectCallback = resolveSelectStep;
  71039. w.pParse = pParse;
  71040. w.u.pNC = pOuterNC;
  71041. sqlite3WalkSelect(&w, p);
  71042. }
  71043. /*
  71044. ** Resolve names in expressions that can only reference a single table:
  71045. **
  71046. ** * CHECK constraints
  71047. ** * WHERE clauses on partial indices
  71048. **
  71049. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  71050. ** is set to -1 and the Expr.iColumn value is set to the column number.
  71051. **
  71052. ** Any errors cause an error message to be set in pParse.
  71053. */
  71054. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  71055. Parse *pParse, /* Parsing context */
  71056. Table *pTab, /* The table being referenced */
  71057. int type, /* NC_IsCheck or NC_PartIdx */
  71058. Expr *pExpr, /* Expression to resolve. May be NULL. */
  71059. ExprList *pList /* Expression list to resolve. May be NUL. */
  71060. ){
  71061. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  71062. NameContext sNC; /* Name context for pParse->pNewTable */
  71063. int i; /* Loop counter */
  71064. assert( type==NC_IsCheck || type==NC_PartIdx );
  71065. memset(&sNC, 0, sizeof(sNC));
  71066. memset(&sSrc, 0, sizeof(sSrc));
  71067. sSrc.nSrc = 1;
  71068. sSrc.a[0].zName = pTab->zName;
  71069. sSrc.a[0].pTab = pTab;
  71070. sSrc.a[0].iCursor = -1;
  71071. sNC.pParse = pParse;
  71072. sNC.pSrcList = &sSrc;
  71073. sNC.ncFlags = type;
  71074. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  71075. if( pList ){
  71076. for(i=0; i<pList->nExpr; i++){
  71077. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  71078. return;
  71079. }
  71080. }
  71081. }
  71082. }
  71083. /************** End of resolve.c *********************************************/
  71084. /************** Begin file expr.c ********************************************/
  71085. /*
  71086. ** 2001 September 15
  71087. **
  71088. ** The author disclaims copyright to this source code. In place of
  71089. ** a legal notice, here is a blessing:
  71090. **
  71091. ** May you do good and not evil.
  71092. ** May you find forgiveness for yourself and forgive others.
  71093. ** May you share freely, never taking more than you give.
  71094. **
  71095. *************************************************************************
  71096. ** This file contains routines used for analyzing expressions and
  71097. ** for generating VDBE code that evaluates expressions in SQLite.
  71098. */
  71099. /*
  71100. ** Return the 'affinity' of the expression pExpr if any.
  71101. **
  71102. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  71103. ** or a sub-select with a column as the return value, then the
  71104. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  71105. ** indicating no affinity for the expression.
  71106. **
  71107. ** i.e. the WHERE clause expresssions in the following statements all
  71108. ** have an affinity:
  71109. **
  71110. ** CREATE TABLE t1(a);
  71111. ** SELECT * FROM t1 WHERE a;
  71112. ** SELECT a AS b FROM t1 WHERE b;
  71113. ** SELECT * FROM t1 WHERE (select a from t1);
  71114. */
  71115. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  71116. int op;
  71117. pExpr = sqlite3ExprSkipCollate(pExpr);
  71118. op = pExpr->op;
  71119. if( op==TK_SELECT ){
  71120. assert( pExpr->flags&EP_xIsSelect );
  71121. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  71122. }
  71123. #ifndef SQLITE_OMIT_CAST
  71124. if( op==TK_CAST ){
  71125. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  71126. return sqlite3AffinityType(pExpr->u.zToken, 0);
  71127. }
  71128. #endif
  71129. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  71130. && pExpr->pTab!=0
  71131. ){
  71132. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  71133. ** a TK_COLUMN but was previously evaluated and cached in a register */
  71134. int j = pExpr->iColumn;
  71135. if( j<0 ) return SQLITE_AFF_INTEGER;
  71136. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  71137. return pExpr->pTab->aCol[j].affinity;
  71138. }
  71139. return pExpr->affinity;
  71140. }
  71141. /*
  71142. ** Set the collating sequence for expression pExpr to be the collating
  71143. ** sequence named by pToken. Return a pointer to a new Expr node that
  71144. ** implements the COLLATE operator.
  71145. **
  71146. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  71147. ** and the pExpr parameter is returned unchanged.
  71148. */
  71149. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
  71150. if( pCollName->n>0 ){
  71151. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
  71152. if( pNew ){
  71153. pNew->pLeft = pExpr;
  71154. pNew->flags |= EP_Collate|EP_Skip;
  71155. pExpr = pNew;
  71156. }
  71157. }
  71158. return pExpr;
  71159. }
  71160. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  71161. Token s;
  71162. assert( zC!=0 );
  71163. s.z = zC;
  71164. s.n = sqlite3Strlen30(s.z);
  71165. return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
  71166. }
  71167. /*
  71168. ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
  71169. ** or likelihood() function at the root of an expression.
  71170. */
  71171. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  71172. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  71173. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  71174. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  71175. assert( pExpr->x.pList->nExpr>0 );
  71176. assert( pExpr->op==TK_FUNCTION );
  71177. pExpr = pExpr->x.pList->a[0].pExpr;
  71178. }else{
  71179. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
  71180. pExpr = pExpr->pLeft;
  71181. }
  71182. }
  71183. return pExpr;
  71184. }
  71185. /*
  71186. ** Return the collation sequence for the expression pExpr. If
  71187. ** there is no defined collating sequence, return NULL.
  71188. **
  71189. ** The collating sequence might be determined by a COLLATE operator
  71190. ** or by the presence of a column with a defined collating sequence.
  71191. ** COLLATE operators take first precedence. Left operands take
  71192. ** precedence over right operands.
  71193. */
  71194. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  71195. sqlite3 *db = pParse->db;
  71196. CollSeq *pColl = 0;
  71197. Expr *p = pExpr;
  71198. while( p ){
  71199. int op = p->op;
  71200. if( op==TK_CAST || op==TK_UPLUS ){
  71201. p = p->pLeft;
  71202. continue;
  71203. }
  71204. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  71205. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  71206. break;
  71207. }
  71208. if( p->pTab!=0
  71209. && (op==TK_AGG_COLUMN || op==TK_COLUMN
  71210. || op==TK_REGISTER || op==TK_TRIGGER)
  71211. ){
  71212. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  71213. ** a TK_COLUMN but was previously evaluated and cached in a register */
  71214. int j = p->iColumn;
  71215. if( j>=0 ){
  71216. const char *zColl = p->pTab->aCol[j].zColl;
  71217. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  71218. }
  71219. break;
  71220. }
  71221. if( p->flags & EP_Collate ){
  71222. if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
  71223. p = p->pLeft;
  71224. }else{
  71225. p = p->pRight;
  71226. }
  71227. }else{
  71228. break;
  71229. }
  71230. }
  71231. if( sqlite3CheckCollSeq(pParse, pColl) ){
  71232. pColl = 0;
  71233. }
  71234. return pColl;
  71235. }
  71236. /*
  71237. ** pExpr is an operand of a comparison operator. aff2 is the
  71238. ** type affinity of the other operand. This routine returns the
  71239. ** type affinity that should be used for the comparison operator.
  71240. */
  71241. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  71242. char aff1 = sqlite3ExprAffinity(pExpr);
  71243. if( aff1 && aff2 ){
  71244. /* Both sides of the comparison are columns. If one has numeric
  71245. ** affinity, use that. Otherwise use no affinity.
  71246. */
  71247. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  71248. return SQLITE_AFF_NUMERIC;
  71249. }else{
  71250. return SQLITE_AFF_NONE;
  71251. }
  71252. }else if( !aff1 && !aff2 ){
  71253. /* Neither side of the comparison is a column. Compare the
  71254. ** results directly.
  71255. */
  71256. return SQLITE_AFF_NONE;
  71257. }else{
  71258. /* One side is a column, the other is not. Use the columns affinity. */
  71259. assert( aff1==0 || aff2==0 );
  71260. return (aff1 + aff2);
  71261. }
  71262. }
  71263. /*
  71264. ** pExpr is a comparison operator. Return the type affinity that should
  71265. ** be applied to both operands prior to doing the comparison.
  71266. */
  71267. static char comparisonAffinity(Expr *pExpr){
  71268. char aff;
  71269. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  71270. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  71271. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  71272. assert( pExpr->pLeft );
  71273. aff = sqlite3ExprAffinity(pExpr->pLeft);
  71274. if( pExpr->pRight ){
  71275. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  71276. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  71277. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  71278. }else if( !aff ){
  71279. aff = SQLITE_AFF_NONE;
  71280. }
  71281. return aff;
  71282. }
  71283. /*
  71284. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  71285. ** idx_affinity is the affinity of an indexed column. Return true
  71286. ** if the index with affinity idx_affinity may be used to implement
  71287. ** the comparison in pExpr.
  71288. */
  71289. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  71290. char aff = comparisonAffinity(pExpr);
  71291. switch( aff ){
  71292. case SQLITE_AFF_NONE:
  71293. return 1;
  71294. case SQLITE_AFF_TEXT:
  71295. return idx_affinity==SQLITE_AFF_TEXT;
  71296. default:
  71297. return sqlite3IsNumericAffinity(idx_affinity);
  71298. }
  71299. }
  71300. /*
  71301. ** Return the P5 value that should be used for a binary comparison
  71302. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  71303. */
  71304. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  71305. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  71306. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  71307. return aff;
  71308. }
  71309. /*
  71310. ** Return a pointer to the collation sequence that should be used by
  71311. ** a binary comparison operator comparing pLeft and pRight.
  71312. **
  71313. ** If the left hand expression has a collating sequence type, then it is
  71314. ** used. Otherwise the collation sequence for the right hand expression
  71315. ** is used, or the default (BINARY) if neither expression has a collating
  71316. ** type.
  71317. **
  71318. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  71319. ** it is not considered.
  71320. */
  71321. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  71322. Parse *pParse,
  71323. Expr *pLeft,
  71324. Expr *pRight
  71325. ){
  71326. CollSeq *pColl;
  71327. assert( pLeft );
  71328. if( pLeft->flags & EP_Collate ){
  71329. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  71330. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  71331. pColl = sqlite3ExprCollSeq(pParse, pRight);
  71332. }else{
  71333. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  71334. if( !pColl ){
  71335. pColl = sqlite3ExprCollSeq(pParse, pRight);
  71336. }
  71337. }
  71338. return pColl;
  71339. }
  71340. /*
  71341. ** Generate code for a comparison operator.
  71342. */
  71343. static int codeCompare(
  71344. Parse *pParse, /* The parsing (and code generating) context */
  71345. Expr *pLeft, /* The left operand */
  71346. Expr *pRight, /* The right operand */
  71347. int opcode, /* The comparison opcode */
  71348. int in1, int in2, /* Register holding operands */
  71349. int dest, /* Jump here if true. */
  71350. int jumpIfNull /* If true, jump if either operand is NULL */
  71351. ){
  71352. int p5;
  71353. int addr;
  71354. CollSeq *p4;
  71355. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  71356. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  71357. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  71358. (void*)p4, P4_COLLSEQ);
  71359. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  71360. return addr;
  71361. }
  71362. #if SQLITE_MAX_EXPR_DEPTH>0
  71363. /*
  71364. ** Check that argument nHeight is less than or equal to the maximum
  71365. ** expression depth allowed. If it is not, leave an error message in
  71366. ** pParse.
  71367. */
  71368. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  71369. int rc = SQLITE_OK;
  71370. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  71371. if( nHeight>mxHeight ){
  71372. sqlite3ErrorMsg(pParse,
  71373. "Expression tree is too large (maximum depth %d)", mxHeight
  71374. );
  71375. rc = SQLITE_ERROR;
  71376. }
  71377. return rc;
  71378. }
  71379. /* The following three functions, heightOfExpr(), heightOfExprList()
  71380. ** and heightOfSelect(), are used to determine the maximum height
  71381. ** of any expression tree referenced by the structure passed as the
  71382. ** first argument.
  71383. **
  71384. ** If this maximum height is greater than the current value pointed
  71385. ** to by pnHeight, the second parameter, then set *pnHeight to that
  71386. ** value.
  71387. */
  71388. static void heightOfExpr(Expr *p, int *pnHeight){
  71389. if( p ){
  71390. if( p->nHeight>*pnHeight ){
  71391. *pnHeight = p->nHeight;
  71392. }
  71393. }
  71394. }
  71395. static void heightOfExprList(ExprList *p, int *pnHeight){
  71396. if( p ){
  71397. int i;
  71398. for(i=0; i<p->nExpr; i++){
  71399. heightOfExpr(p->a[i].pExpr, pnHeight);
  71400. }
  71401. }
  71402. }
  71403. static void heightOfSelect(Select *p, int *pnHeight){
  71404. if( p ){
  71405. heightOfExpr(p->pWhere, pnHeight);
  71406. heightOfExpr(p->pHaving, pnHeight);
  71407. heightOfExpr(p->pLimit, pnHeight);
  71408. heightOfExpr(p->pOffset, pnHeight);
  71409. heightOfExprList(p->pEList, pnHeight);
  71410. heightOfExprList(p->pGroupBy, pnHeight);
  71411. heightOfExprList(p->pOrderBy, pnHeight);
  71412. heightOfSelect(p->pPrior, pnHeight);
  71413. }
  71414. }
  71415. /*
  71416. ** Set the Expr.nHeight variable in the structure passed as an
  71417. ** argument. An expression with no children, Expr.pList or
  71418. ** Expr.pSelect member has a height of 1. Any other expression
  71419. ** has a height equal to the maximum height of any other
  71420. ** referenced Expr plus one.
  71421. */
  71422. static void exprSetHeight(Expr *p){
  71423. int nHeight = 0;
  71424. heightOfExpr(p->pLeft, &nHeight);
  71425. heightOfExpr(p->pRight, &nHeight);
  71426. if( ExprHasProperty(p, EP_xIsSelect) ){
  71427. heightOfSelect(p->x.pSelect, &nHeight);
  71428. }else{
  71429. heightOfExprList(p->x.pList, &nHeight);
  71430. }
  71431. p->nHeight = nHeight + 1;
  71432. }
  71433. /*
  71434. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  71435. ** the height is greater than the maximum allowed expression depth,
  71436. ** leave an error in pParse.
  71437. */
  71438. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  71439. exprSetHeight(p);
  71440. sqlite3ExprCheckHeight(pParse, p->nHeight);
  71441. }
  71442. /*
  71443. ** Return the maximum height of any expression tree referenced
  71444. ** by the select statement passed as an argument.
  71445. */
  71446. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  71447. int nHeight = 0;
  71448. heightOfSelect(p, &nHeight);
  71449. return nHeight;
  71450. }
  71451. #else
  71452. #define exprSetHeight(y)
  71453. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  71454. /*
  71455. ** This routine is the core allocator for Expr nodes.
  71456. **
  71457. ** Construct a new expression node and return a pointer to it. Memory
  71458. ** for this node and for the pToken argument is a single allocation
  71459. ** obtained from sqlite3DbMalloc(). The calling function
  71460. ** is responsible for making sure the node eventually gets freed.
  71461. **
  71462. ** If dequote is true, then the token (if it exists) is dequoted.
  71463. ** If dequote is false, no dequoting is performance. The deQuote
  71464. ** parameter is ignored if pToken is NULL or if the token does not
  71465. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  71466. ** then the EP_DblQuoted flag is set on the expression node.
  71467. **
  71468. ** Special case: If op==TK_INTEGER and pToken points to a string that
  71469. ** can be translated into a 32-bit integer, then the token is not
  71470. ** stored in u.zToken. Instead, the integer values is written
  71471. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  71472. ** is allocated to hold the integer text and the dequote flag is ignored.
  71473. */
  71474. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  71475. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  71476. int op, /* Expression opcode */
  71477. const Token *pToken, /* Token argument. Might be NULL */
  71478. int dequote /* True to dequote */
  71479. ){
  71480. Expr *pNew;
  71481. int nExtra = 0;
  71482. int iValue = 0;
  71483. if( pToken ){
  71484. if( op!=TK_INTEGER || pToken->z==0
  71485. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  71486. nExtra = pToken->n+1;
  71487. assert( iValue>=0 );
  71488. }
  71489. }
  71490. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  71491. if( pNew ){
  71492. pNew->op = (u8)op;
  71493. pNew->iAgg = -1;
  71494. if( pToken ){
  71495. if( nExtra==0 ){
  71496. pNew->flags |= EP_IntValue;
  71497. pNew->u.iValue = iValue;
  71498. }else{
  71499. int c;
  71500. pNew->u.zToken = (char*)&pNew[1];
  71501. assert( pToken->z!=0 || pToken->n==0 );
  71502. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  71503. pNew->u.zToken[pToken->n] = 0;
  71504. if( dequote && nExtra>=3
  71505. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  71506. sqlite3Dequote(pNew->u.zToken);
  71507. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  71508. }
  71509. }
  71510. }
  71511. #if SQLITE_MAX_EXPR_DEPTH>0
  71512. pNew->nHeight = 1;
  71513. #endif
  71514. }
  71515. return pNew;
  71516. }
  71517. /*
  71518. ** Allocate a new expression node from a zero-terminated token that has
  71519. ** already been dequoted.
  71520. */
  71521. SQLITE_PRIVATE Expr *sqlite3Expr(
  71522. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  71523. int op, /* Expression opcode */
  71524. const char *zToken /* Token argument. Might be NULL */
  71525. ){
  71526. Token x;
  71527. x.z = zToken;
  71528. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  71529. return sqlite3ExprAlloc(db, op, &x, 0);
  71530. }
  71531. /*
  71532. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  71533. **
  71534. ** If pRoot==NULL that means that a memory allocation error has occurred.
  71535. ** In that case, delete the subtrees pLeft and pRight.
  71536. */
  71537. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  71538. sqlite3 *db,
  71539. Expr *pRoot,
  71540. Expr *pLeft,
  71541. Expr *pRight
  71542. ){
  71543. if( pRoot==0 ){
  71544. assert( db->mallocFailed );
  71545. sqlite3ExprDelete(db, pLeft);
  71546. sqlite3ExprDelete(db, pRight);
  71547. }else{
  71548. if( pRight ){
  71549. pRoot->pRight = pRight;
  71550. pRoot->flags |= EP_Collate & pRight->flags;
  71551. }
  71552. if( pLeft ){
  71553. pRoot->pLeft = pLeft;
  71554. pRoot->flags |= EP_Collate & pLeft->flags;
  71555. }
  71556. exprSetHeight(pRoot);
  71557. }
  71558. }
  71559. /*
  71560. ** Allocate a Expr node which joins as many as two subtrees.
  71561. **
  71562. ** One or both of the subtrees can be NULL. Return a pointer to the new
  71563. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  71564. ** free the subtrees and return NULL.
  71565. */
  71566. SQLITE_PRIVATE Expr *sqlite3PExpr(
  71567. Parse *pParse, /* Parsing context */
  71568. int op, /* Expression opcode */
  71569. Expr *pLeft, /* Left operand */
  71570. Expr *pRight, /* Right operand */
  71571. const Token *pToken /* Argument token */
  71572. ){
  71573. Expr *p;
  71574. if( op==TK_AND && pLeft && pRight ){
  71575. /* Take advantage of short-circuit false optimization for AND */
  71576. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  71577. }else{
  71578. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  71579. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  71580. }
  71581. if( p ) {
  71582. sqlite3ExprCheckHeight(pParse, p->nHeight);
  71583. }
  71584. return p;
  71585. }
  71586. /*
  71587. ** Return 1 if an expression must be FALSE in all cases and 0 if the
  71588. ** expression might be true. This is an optimization. If is OK to
  71589. ** return 0 here even if the expression really is always false (a
  71590. ** false negative). But it is a bug to return 1 if the expression
  71591. ** might be true in some rare circumstances (a false positive.)
  71592. **
  71593. ** Note that if the expression is part of conditional for a
  71594. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  71595. ** is it true or false, so always return 0.
  71596. */
  71597. static int exprAlwaysFalse(Expr *p){
  71598. int v = 0;
  71599. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  71600. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  71601. return v==0;
  71602. }
  71603. /*
  71604. ** Join two expressions using an AND operator. If either expression is
  71605. ** NULL, then just return the other expression.
  71606. **
  71607. ** If one side or the other of the AND is known to be false, then instead
  71608. ** of returning an AND expression, just return a constant expression with
  71609. ** a value of false.
  71610. */
  71611. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  71612. if( pLeft==0 ){
  71613. return pRight;
  71614. }else if( pRight==0 ){
  71615. return pLeft;
  71616. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  71617. sqlite3ExprDelete(db, pLeft);
  71618. sqlite3ExprDelete(db, pRight);
  71619. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  71620. }else{
  71621. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  71622. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  71623. return pNew;
  71624. }
  71625. }
  71626. /*
  71627. ** Construct a new expression node for a function with multiple
  71628. ** arguments.
  71629. */
  71630. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  71631. Expr *pNew;
  71632. sqlite3 *db = pParse->db;
  71633. assert( pToken );
  71634. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  71635. if( pNew==0 ){
  71636. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  71637. return 0;
  71638. }
  71639. pNew->x.pList = pList;
  71640. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  71641. sqlite3ExprSetHeight(pParse, pNew);
  71642. return pNew;
  71643. }
  71644. /*
  71645. ** Assign a variable number to an expression that encodes a wildcard
  71646. ** in the original SQL statement.
  71647. **
  71648. ** Wildcards consisting of a single "?" are assigned the next sequential
  71649. ** variable number.
  71650. **
  71651. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  71652. ** sure "nnn" is not too be to avoid a denial of service attack when
  71653. ** the SQL statement comes from an external source.
  71654. **
  71655. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  71656. ** as the previous instance of the same wildcard. Or if this is the first
  71657. ** instance of the wildcard, the next sequenial variable number is
  71658. ** assigned.
  71659. */
  71660. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  71661. sqlite3 *db = pParse->db;
  71662. const char *z;
  71663. if( pExpr==0 ) return;
  71664. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  71665. z = pExpr->u.zToken;
  71666. assert( z!=0 );
  71667. assert( z[0]!=0 );
  71668. if( z[1]==0 ){
  71669. /* Wildcard of the form "?". Assign the next variable number */
  71670. assert( z[0]=='?' );
  71671. pExpr->iColumn = (ynVar)(++pParse->nVar);
  71672. }else{
  71673. ynVar x = 0;
  71674. u32 n = sqlite3Strlen30(z);
  71675. if( z[0]=='?' ){
  71676. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  71677. ** use it as the variable number */
  71678. i64 i;
  71679. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  71680. pExpr->iColumn = x = (ynVar)i;
  71681. testcase( i==0 );
  71682. testcase( i==1 );
  71683. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  71684. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  71685. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  71686. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  71687. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  71688. x = 0;
  71689. }
  71690. if( i>pParse->nVar ){
  71691. pParse->nVar = (int)i;
  71692. }
  71693. }else{
  71694. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  71695. ** number as the prior appearance of the same name, or if the name
  71696. ** has never appeared before, reuse the same variable number
  71697. */
  71698. ynVar i;
  71699. for(i=0; i<pParse->nzVar; i++){
  71700. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  71701. pExpr->iColumn = x = (ynVar)i+1;
  71702. break;
  71703. }
  71704. }
  71705. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  71706. }
  71707. if( x>0 ){
  71708. if( x>pParse->nzVar ){
  71709. char **a;
  71710. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  71711. if( a==0 ) return; /* Error reported through db->mallocFailed */
  71712. pParse->azVar = a;
  71713. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  71714. pParse->nzVar = x;
  71715. }
  71716. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  71717. sqlite3DbFree(db, pParse->azVar[x-1]);
  71718. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  71719. }
  71720. }
  71721. }
  71722. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  71723. sqlite3ErrorMsg(pParse, "too many SQL variables");
  71724. }
  71725. }
  71726. /*
  71727. ** Recursively delete an expression tree.
  71728. */
  71729. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  71730. if( p==0 ) return;
  71731. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  71732. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  71733. if( !ExprHasProperty(p, EP_TokenOnly) ){
  71734. /* The Expr.x union is never used at the same time as Expr.pRight */
  71735. assert( p->x.pList==0 || p->pRight==0 );
  71736. sqlite3ExprDelete(db, p->pLeft);
  71737. sqlite3ExprDelete(db, p->pRight);
  71738. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  71739. if( ExprHasProperty(p, EP_xIsSelect) ){
  71740. sqlite3SelectDelete(db, p->x.pSelect);
  71741. }else{
  71742. sqlite3ExprListDelete(db, p->x.pList);
  71743. }
  71744. }
  71745. if( !ExprHasProperty(p, EP_Static) ){
  71746. sqlite3DbFree(db, p);
  71747. }
  71748. }
  71749. /*
  71750. ** Return the number of bytes allocated for the expression structure
  71751. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  71752. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  71753. */
  71754. static int exprStructSize(Expr *p){
  71755. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  71756. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  71757. return EXPR_FULLSIZE;
  71758. }
  71759. /*
  71760. ** The dupedExpr*Size() routines each return the number of bytes required
  71761. ** to store a copy of an expression or expression tree. They differ in
  71762. ** how much of the tree is measured.
  71763. **
  71764. ** dupedExprStructSize() Size of only the Expr structure
  71765. ** dupedExprNodeSize() Size of Expr + space for token
  71766. ** dupedExprSize() Expr + token + subtree components
  71767. **
  71768. ***************************************************************************
  71769. **
  71770. ** The dupedExprStructSize() function returns two values OR-ed together:
  71771. ** (1) the space required for a copy of the Expr structure only and
  71772. ** (2) the EP_xxx flags that indicate what the structure size should be.
  71773. ** The return values is always one of:
  71774. **
  71775. ** EXPR_FULLSIZE
  71776. ** EXPR_REDUCEDSIZE | EP_Reduced
  71777. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  71778. **
  71779. ** The size of the structure can be found by masking the return value
  71780. ** of this routine with 0xfff. The flags can be found by masking the
  71781. ** return value with EP_Reduced|EP_TokenOnly.
  71782. **
  71783. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  71784. ** (unreduced) Expr objects as they or originally constructed by the parser.
  71785. ** During expression analysis, extra information is computed and moved into
  71786. ** later parts of teh Expr object and that extra information might get chopped
  71787. ** off if the expression is reduced. Note also that it does not work to
  71788. ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  71789. ** to reduce a pristine expression tree from the parser. The implementation
  71790. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  71791. ** to enforce this constraint.
  71792. */
  71793. static int dupedExprStructSize(Expr *p, int flags){
  71794. int nSize;
  71795. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  71796. assert( EXPR_FULLSIZE<=0xfff );
  71797. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  71798. if( 0==(flags&EXPRDUP_REDUCE) ){
  71799. nSize = EXPR_FULLSIZE;
  71800. }else{
  71801. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  71802. assert( !ExprHasProperty(p, EP_FromJoin) );
  71803. assert( !ExprHasProperty(p, EP_MemToken) );
  71804. assert( !ExprHasProperty(p, EP_NoReduce) );
  71805. if( p->pLeft || p->x.pList ){
  71806. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  71807. }else{
  71808. assert( p->pRight==0 );
  71809. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  71810. }
  71811. }
  71812. return nSize;
  71813. }
  71814. /*
  71815. ** This function returns the space in bytes required to store the copy
  71816. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  71817. ** string is defined.)
  71818. */
  71819. static int dupedExprNodeSize(Expr *p, int flags){
  71820. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  71821. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  71822. nByte += sqlite3Strlen30(p->u.zToken)+1;
  71823. }
  71824. return ROUND8(nByte);
  71825. }
  71826. /*
  71827. ** Return the number of bytes required to create a duplicate of the
  71828. ** expression passed as the first argument. The second argument is a
  71829. ** mask containing EXPRDUP_XXX flags.
  71830. **
  71831. ** The value returned includes space to create a copy of the Expr struct
  71832. ** itself and the buffer referred to by Expr.u.zToken, if any.
  71833. **
  71834. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  71835. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  71836. ** and Expr.pRight variables (but not for any structures pointed to or
  71837. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  71838. */
  71839. static int dupedExprSize(Expr *p, int flags){
  71840. int nByte = 0;
  71841. if( p ){
  71842. nByte = dupedExprNodeSize(p, flags);
  71843. if( flags&EXPRDUP_REDUCE ){
  71844. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  71845. }
  71846. }
  71847. return nByte;
  71848. }
  71849. /*
  71850. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  71851. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  71852. ** to store the copy of expression p, the copies of p->u.zToken
  71853. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  71854. ** if any. Before returning, *pzBuffer is set to the first byte passed the
  71855. ** portion of the buffer copied into by this function.
  71856. */
  71857. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  71858. Expr *pNew = 0; /* Value to return */
  71859. if( p ){
  71860. const int isReduced = (flags&EXPRDUP_REDUCE);
  71861. u8 *zAlloc;
  71862. u32 staticFlag = 0;
  71863. assert( pzBuffer==0 || isReduced );
  71864. /* Figure out where to write the new Expr structure. */
  71865. if( pzBuffer ){
  71866. zAlloc = *pzBuffer;
  71867. staticFlag = EP_Static;
  71868. }else{
  71869. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  71870. }
  71871. pNew = (Expr *)zAlloc;
  71872. if( pNew ){
  71873. /* Set nNewSize to the size allocated for the structure pointed to
  71874. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  71875. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  71876. ** by the copy of the p->u.zToken string (if any).
  71877. */
  71878. const unsigned nStructSize = dupedExprStructSize(p, flags);
  71879. const int nNewSize = nStructSize & 0xfff;
  71880. int nToken;
  71881. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  71882. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  71883. }else{
  71884. nToken = 0;
  71885. }
  71886. if( isReduced ){
  71887. assert( ExprHasProperty(p, EP_Reduced)==0 );
  71888. memcpy(zAlloc, p, nNewSize);
  71889. }else{
  71890. int nSize = exprStructSize(p);
  71891. memcpy(zAlloc, p, nSize);
  71892. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  71893. }
  71894. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  71895. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  71896. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  71897. pNew->flags |= staticFlag;
  71898. /* Copy the p->u.zToken string, if any. */
  71899. if( nToken ){
  71900. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  71901. memcpy(zToken, p->u.zToken, nToken);
  71902. }
  71903. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  71904. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  71905. if( ExprHasProperty(p, EP_xIsSelect) ){
  71906. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  71907. }else{
  71908. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  71909. }
  71910. }
  71911. /* Fill in pNew->pLeft and pNew->pRight. */
  71912. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  71913. zAlloc += dupedExprNodeSize(p, flags);
  71914. if( ExprHasProperty(pNew, EP_Reduced) ){
  71915. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  71916. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  71917. }
  71918. if( pzBuffer ){
  71919. *pzBuffer = zAlloc;
  71920. }
  71921. }else{
  71922. if( !ExprHasProperty(p, EP_TokenOnly) ){
  71923. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  71924. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  71925. }
  71926. }
  71927. }
  71928. }
  71929. return pNew;
  71930. }
  71931. /*
  71932. ** The following group of routines make deep copies of expressions,
  71933. ** expression lists, ID lists, and select statements. The copies can
  71934. ** be deleted (by being passed to their respective ...Delete() routines)
  71935. ** without effecting the originals.
  71936. **
  71937. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  71938. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  71939. ** by subsequent calls to sqlite*ListAppend() routines.
  71940. **
  71941. ** Any tables that the SrcList might point to are not duplicated.
  71942. **
  71943. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  71944. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  71945. ** truncated version of the usual Expr structure that will be stored as
  71946. ** part of the in-memory representation of the database schema.
  71947. */
  71948. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  71949. return exprDup(db, p, flags, 0);
  71950. }
  71951. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  71952. ExprList *pNew;
  71953. struct ExprList_item *pItem, *pOldItem;
  71954. int i;
  71955. if( p==0 ) return 0;
  71956. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  71957. if( pNew==0 ) return 0;
  71958. pNew->iECursor = 0;
  71959. pNew->nExpr = i = p->nExpr;
  71960. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  71961. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  71962. if( pItem==0 ){
  71963. sqlite3DbFree(db, pNew);
  71964. return 0;
  71965. }
  71966. pOldItem = p->a;
  71967. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  71968. Expr *pOldExpr = pOldItem->pExpr;
  71969. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  71970. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  71971. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  71972. pItem->sortOrder = pOldItem->sortOrder;
  71973. pItem->done = 0;
  71974. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  71975. pItem->iOrderByCol = pOldItem->iOrderByCol;
  71976. pItem->iAlias = pOldItem->iAlias;
  71977. }
  71978. return pNew;
  71979. }
  71980. /*
  71981. ** If cursors, triggers, views and subqueries are all omitted from
  71982. ** the build, then none of the following routines, except for
  71983. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  71984. ** called with a NULL argument.
  71985. */
  71986. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  71987. || !defined(SQLITE_OMIT_SUBQUERY)
  71988. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  71989. SrcList *pNew;
  71990. int i;
  71991. int nByte;
  71992. if( p==0 ) return 0;
  71993. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  71994. pNew = sqlite3DbMallocRaw(db, nByte );
  71995. if( pNew==0 ) return 0;
  71996. pNew->nSrc = pNew->nAlloc = p->nSrc;
  71997. for(i=0; i<p->nSrc; i++){
  71998. struct SrcList_item *pNewItem = &pNew->a[i];
  71999. struct SrcList_item *pOldItem = &p->a[i];
  72000. Table *pTab;
  72001. pNewItem->pSchema = pOldItem->pSchema;
  72002. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  72003. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  72004. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  72005. pNewItem->jointype = pOldItem->jointype;
  72006. pNewItem->iCursor = pOldItem->iCursor;
  72007. pNewItem->addrFillSub = pOldItem->addrFillSub;
  72008. pNewItem->regReturn = pOldItem->regReturn;
  72009. pNewItem->isCorrelated = pOldItem->isCorrelated;
  72010. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  72011. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  72012. pNewItem->notIndexed = pOldItem->notIndexed;
  72013. pNewItem->pIndex = pOldItem->pIndex;
  72014. pTab = pNewItem->pTab = pOldItem->pTab;
  72015. if( pTab ){
  72016. pTab->nRef++;
  72017. }
  72018. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  72019. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  72020. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  72021. pNewItem->colUsed = pOldItem->colUsed;
  72022. }
  72023. return pNew;
  72024. }
  72025. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  72026. IdList *pNew;
  72027. int i;
  72028. if( p==0 ) return 0;
  72029. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  72030. if( pNew==0 ) return 0;
  72031. pNew->nId = p->nId;
  72032. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  72033. if( pNew->a==0 ){
  72034. sqlite3DbFree(db, pNew);
  72035. return 0;
  72036. }
  72037. /* Note that because the size of the allocation for p->a[] is not
  72038. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  72039. ** on the duplicate created by this function. */
  72040. for(i=0; i<p->nId; i++){
  72041. struct IdList_item *pNewItem = &pNew->a[i];
  72042. struct IdList_item *pOldItem = &p->a[i];
  72043. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  72044. pNewItem->idx = pOldItem->idx;
  72045. }
  72046. return pNew;
  72047. }
  72048. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  72049. Select *pNew, *pPrior;
  72050. if( p==0 ) return 0;
  72051. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  72052. if( pNew==0 ) return 0;
  72053. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  72054. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  72055. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  72056. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  72057. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  72058. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  72059. pNew->op = p->op;
  72060. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  72061. if( pPrior ) pPrior->pNext = pNew;
  72062. pNew->pNext = 0;
  72063. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  72064. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  72065. pNew->iLimit = 0;
  72066. pNew->iOffset = 0;
  72067. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  72068. pNew->pRightmost = 0;
  72069. pNew->addrOpenEphm[0] = -1;
  72070. pNew->addrOpenEphm[1] = -1;
  72071. pNew->addrOpenEphm[2] = -1;
  72072. return pNew;
  72073. }
  72074. #else
  72075. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  72076. assert( p==0 );
  72077. return 0;
  72078. }
  72079. #endif
  72080. /*
  72081. ** Add a new element to the end of an expression list. If pList is
  72082. ** initially NULL, then create a new expression list.
  72083. **
  72084. ** If a memory allocation error occurs, the entire list is freed and
  72085. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  72086. ** that the new entry was successfully appended.
  72087. */
  72088. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  72089. Parse *pParse, /* Parsing context */
  72090. ExprList *pList, /* List to which to append. Might be NULL */
  72091. Expr *pExpr /* Expression to be appended. Might be NULL */
  72092. ){
  72093. sqlite3 *db = pParse->db;
  72094. if( pList==0 ){
  72095. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  72096. if( pList==0 ){
  72097. goto no_mem;
  72098. }
  72099. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  72100. if( pList->a==0 ) goto no_mem;
  72101. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  72102. struct ExprList_item *a;
  72103. assert( pList->nExpr>0 );
  72104. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  72105. if( a==0 ){
  72106. goto no_mem;
  72107. }
  72108. pList->a = a;
  72109. }
  72110. assert( pList->a!=0 );
  72111. if( 1 ){
  72112. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  72113. memset(pItem, 0, sizeof(*pItem));
  72114. pItem->pExpr = pExpr;
  72115. }
  72116. return pList;
  72117. no_mem:
  72118. /* Avoid leaking memory if malloc has failed. */
  72119. sqlite3ExprDelete(db, pExpr);
  72120. sqlite3ExprListDelete(db, pList);
  72121. return 0;
  72122. }
  72123. /*
  72124. ** Set the ExprList.a[].zName element of the most recently added item
  72125. ** on the expression list.
  72126. **
  72127. ** pList might be NULL following an OOM error. But pName should never be
  72128. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  72129. ** is set.
  72130. */
  72131. SQLITE_PRIVATE void sqlite3ExprListSetName(
  72132. Parse *pParse, /* Parsing context */
  72133. ExprList *pList, /* List to which to add the span. */
  72134. Token *pName, /* Name to be added */
  72135. int dequote /* True to cause the name to be dequoted */
  72136. ){
  72137. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  72138. if( pList ){
  72139. struct ExprList_item *pItem;
  72140. assert( pList->nExpr>0 );
  72141. pItem = &pList->a[pList->nExpr-1];
  72142. assert( pItem->zName==0 );
  72143. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  72144. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  72145. }
  72146. }
  72147. /*
  72148. ** Set the ExprList.a[].zSpan element of the most recently added item
  72149. ** on the expression list.
  72150. **
  72151. ** pList might be NULL following an OOM error. But pSpan should never be
  72152. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  72153. ** is set.
  72154. */
  72155. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  72156. Parse *pParse, /* Parsing context */
  72157. ExprList *pList, /* List to which to add the span. */
  72158. ExprSpan *pSpan /* The span to be added */
  72159. ){
  72160. sqlite3 *db = pParse->db;
  72161. assert( pList!=0 || db->mallocFailed!=0 );
  72162. if( pList ){
  72163. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  72164. assert( pList->nExpr>0 );
  72165. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  72166. sqlite3DbFree(db, pItem->zSpan);
  72167. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  72168. (int)(pSpan->zEnd - pSpan->zStart));
  72169. }
  72170. }
  72171. /*
  72172. ** If the expression list pEList contains more than iLimit elements,
  72173. ** leave an error message in pParse.
  72174. */
  72175. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  72176. Parse *pParse,
  72177. ExprList *pEList,
  72178. const char *zObject
  72179. ){
  72180. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  72181. testcase( pEList && pEList->nExpr==mx );
  72182. testcase( pEList && pEList->nExpr==mx+1 );
  72183. if( pEList && pEList->nExpr>mx ){
  72184. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  72185. }
  72186. }
  72187. /*
  72188. ** Delete an entire expression list.
  72189. */
  72190. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  72191. int i;
  72192. struct ExprList_item *pItem;
  72193. if( pList==0 ) return;
  72194. assert( pList->a!=0 || pList->nExpr==0 );
  72195. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  72196. sqlite3ExprDelete(db, pItem->pExpr);
  72197. sqlite3DbFree(db, pItem->zName);
  72198. sqlite3DbFree(db, pItem->zSpan);
  72199. }
  72200. sqlite3DbFree(db, pList->a);
  72201. sqlite3DbFree(db, pList);
  72202. }
  72203. /*
  72204. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  72205. ** to an integer. These routines are checking an expression to see
  72206. ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
  72207. ** not constant.
  72208. **
  72209. ** These callback routines are used to implement the following:
  72210. **
  72211. ** sqlite3ExprIsConstant()
  72212. ** sqlite3ExprIsConstantNotJoin()
  72213. ** sqlite3ExprIsConstantOrFunction()
  72214. **
  72215. */
  72216. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  72217. /* If pWalker->u.i is 3 then any term of the expression that comes from
  72218. ** the ON or USING clauses of a join disqualifies the expression
  72219. ** from being considered constant. */
  72220. if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
  72221. pWalker->u.i = 0;
  72222. return WRC_Abort;
  72223. }
  72224. switch( pExpr->op ){
  72225. /* Consider functions to be constant if all their arguments are constant
  72226. ** and pWalker->u.i==2 */
  72227. case TK_FUNCTION:
  72228. if( pWalker->u.i==2 ) return 0;
  72229. /* Fall through */
  72230. case TK_ID:
  72231. case TK_COLUMN:
  72232. case TK_AGG_FUNCTION:
  72233. case TK_AGG_COLUMN:
  72234. testcase( pExpr->op==TK_ID );
  72235. testcase( pExpr->op==TK_COLUMN );
  72236. testcase( pExpr->op==TK_AGG_FUNCTION );
  72237. testcase( pExpr->op==TK_AGG_COLUMN );
  72238. pWalker->u.i = 0;
  72239. return WRC_Abort;
  72240. default:
  72241. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  72242. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  72243. return WRC_Continue;
  72244. }
  72245. }
  72246. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  72247. UNUSED_PARAMETER(NotUsed);
  72248. pWalker->u.i = 0;
  72249. return WRC_Abort;
  72250. }
  72251. static int exprIsConst(Expr *p, int initFlag){
  72252. Walker w;
  72253. memset(&w, 0, sizeof(w));
  72254. w.u.i = initFlag;
  72255. w.xExprCallback = exprNodeIsConstant;
  72256. w.xSelectCallback = selectNodeIsConstant;
  72257. sqlite3WalkExpr(&w, p);
  72258. return w.u.i;
  72259. }
  72260. /*
  72261. ** Walk an expression tree. Return 1 if the expression is constant
  72262. ** and 0 if it involves variables or function calls.
  72263. **
  72264. ** For the purposes of this function, a double-quoted string (ex: "abc")
  72265. ** is considered a variable but a single-quoted string (ex: 'abc') is
  72266. ** a constant.
  72267. */
  72268. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  72269. return exprIsConst(p, 1);
  72270. }
  72271. /*
  72272. ** Walk an expression tree. Return 1 if the expression is constant
  72273. ** that does no originate from the ON or USING clauses of a join.
  72274. ** Return 0 if it involves variables or function calls or terms from
  72275. ** an ON or USING clause.
  72276. */
  72277. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  72278. return exprIsConst(p, 3);
  72279. }
  72280. /*
  72281. ** Walk an expression tree. Return 1 if the expression is constant
  72282. ** or a function call with constant arguments. Return and 0 if there
  72283. ** are any variables.
  72284. **
  72285. ** For the purposes of this function, a double-quoted string (ex: "abc")
  72286. ** is considered a variable but a single-quoted string (ex: 'abc') is
  72287. ** a constant.
  72288. */
  72289. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
  72290. return exprIsConst(p, 2);
  72291. }
  72292. /*
  72293. ** If the expression p codes a constant integer that is small enough
  72294. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  72295. ** in *pValue. If the expression is not an integer or if it is too big
  72296. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  72297. */
  72298. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  72299. int rc = 0;
  72300. /* If an expression is an integer literal that fits in a signed 32-bit
  72301. ** integer, then the EP_IntValue flag will have already been set */
  72302. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  72303. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  72304. if( p->flags & EP_IntValue ){
  72305. *pValue = p->u.iValue;
  72306. return 1;
  72307. }
  72308. switch( p->op ){
  72309. case TK_UPLUS: {
  72310. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  72311. break;
  72312. }
  72313. case TK_UMINUS: {
  72314. int v;
  72315. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  72316. assert( v!=(-2147483647-1) );
  72317. *pValue = -v;
  72318. rc = 1;
  72319. }
  72320. break;
  72321. }
  72322. default: break;
  72323. }
  72324. return rc;
  72325. }
  72326. /*
  72327. ** Return FALSE if there is no chance that the expression can be NULL.
  72328. **
  72329. ** If the expression might be NULL or if the expression is too complex
  72330. ** to tell return TRUE.
  72331. **
  72332. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  72333. ** when we know that a value cannot be NULL. Hence, a false positive
  72334. ** (returning TRUE when in fact the expression can never be NULL) might
  72335. ** be a small performance hit but is otherwise harmless. On the other
  72336. ** hand, a false negative (returning FALSE when the result could be NULL)
  72337. ** will likely result in an incorrect answer. So when in doubt, return
  72338. ** TRUE.
  72339. */
  72340. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  72341. u8 op;
  72342. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  72343. op = p->op;
  72344. if( op==TK_REGISTER ) op = p->op2;
  72345. switch( op ){
  72346. case TK_INTEGER:
  72347. case TK_STRING:
  72348. case TK_FLOAT:
  72349. case TK_BLOB:
  72350. return 0;
  72351. default:
  72352. return 1;
  72353. }
  72354. }
  72355. /*
  72356. ** Generate an OP_IsNull instruction that tests register iReg and jumps
  72357. ** to location iDest if the value in iReg is NULL. The value in iReg
  72358. ** was computed by pExpr. If we can look at pExpr at compile-time and
  72359. ** determine that it can never generate a NULL, then the OP_IsNull operation
  72360. ** can be omitted.
  72361. */
  72362. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
  72363. Vdbe *v, /* The VDBE under construction */
  72364. const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
  72365. int iReg, /* Test the value in this register for NULL */
  72366. int iDest /* Jump here if the value is null */
  72367. ){
  72368. if( sqlite3ExprCanBeNull(pExpr) ){
  72369. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
  72370. }
  72371. }
  72372. /*
  72373. ** Return TRUE if the given expression is a constant which would be
  72374. ** unchanged by OP_Affinity with the affinity given in the second
  72375. ** argument.
  72376. **
  72377. ** This routine is used to determine if the OP_Affinity operation
  72378. ** can be omitted. When in doubt return FALSE. A false negative
  72379. ** is harmless. A false positive, however, can result in the wrong
  72380. ** answer.
  72381. */
  72382. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  72383. u8 op;
  72384. if( aff==SQLITE_AFF_NONE ) return 1;
  72385. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  72386. op = p->op;
  72387. if( op==TK_REGISTER ) op = p->op2;
  72388. switch( op ){
  72389. case TK_INTEGER: {
  72390. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  72391. }
  72392. case TK_FLOAT: {
  72393. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  72394. }
  72395. case TK_STRING: {
  72396. return aff==SQLITE_AFF_TEXT;
  72397. }
  72398. case TK_BLOB: {
  72399. return 1;
  72400. }
  72401. case TK_COLUMN: {
  72402. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  72403. return p->iColumn<0
  72404. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  72405. }
  72406. default: {
  72407. return 0;
  72408. }
  72409. }
  72410. }
  72411. /*
  72412. ** Return TRUE if the given string is a row-id column name.
  72413. */
  72414. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  72415. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  72416. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  72417. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  72418. return 0;
  72419. }
  72420. /*
  72421. ** Return true if we are able to the IN operator optimization on a
  72422. ** query of the form
  72423. **
  72424. ** x IN (SELECT ...)
  72425. **
  72426. ** Where the SELECT... clause is as specified by the parameter to this
  72427. ** routine.
  72428. **
  72429. ** The Select object passed in has already been preprocessed and no
  72430. ** errors have been found.
  72431. */
  72432. #ifndef SQLITE_OMIT_SUBQUERY
  72433. static int isCandidateForInOpt(Select *p){
  72434. SrcList *pSrc;
  72435. ExprList *pEList;
  72436. Table *pTab;
  72437. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  72438. if( p->pPrior ) return 0; /* Not a compound SELECT */
  72439. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  72440. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  72441. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  72442. return 0; /* No DISTINCT keyword and no aggregate functions */
  72443. }
  72444. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  72445. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  72446. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  72447. if( p->pWhere ) return 0; /* Has no WHERE clause */
  72448. pSrc = p->pSrc;
  72449. assert( pSrc!=0 );
  72450. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  72451. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  72452. pTab = pSrc->a[0].pTab;
  72453. if( NEVER(pTab==0) ) return 0;
  72454. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  72455. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  72456. pEList = p->pEList;
  72457. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  72458. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  72459. return 1;
  72460. }
  72461. #endif /* SQLITE_OMIT_SUBQUERY */
  72462. /*
  72463. ** Code an OP_Once instruction and allocate space for its flag. Return the
  72464. ** address of the new instruction.
  72465. */
  72466. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  72467. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  72468. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  72469. }
  72470. /*
  72471. ** This function is used by the implementation of the IN (...) operator.
  72472. ** The pX parameter is the expression on the RHS of the IN operator, which
  72473. ** might be either a list of expressions or a subquery.
  72474. **
  72475. ** The job of this routine is to find or create a b-tree object that can
  72476. ** be used either to test for membership in the RHS set or to iterate through
  72477. ** all members of the RHS set, skipping duplicates.
  72478. **
  72479. ** A cursor is opened on the b-tree object that the RHS of the IN operator
  72480. ** and pX->iTable is set to the index of that cursor.
  72481. **
  72482. ** The returned value of this function indicates the b-tree type, as follows:
  72483. **
  72484. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  72485. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  72486. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  72487. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  72488. ** populated epheremal table.
  72489. **
  72490. ** An existing b-tree might be used if the RHS expression pX is a simple
  72491. ** subquery such as:
  72492. **
  72493. ** SELECT <column> FROM <table>
  72494. **
  72495. ** If the RHS of the IN operator is a list or a more complex subquery, then
  72496. ** an ephemeral table might need to be generated from the RHS and then
  72497. ** pX->iTable made to point to the ephermeral table instead of an
  72498. ** existing table.
  72499. **
  72500. ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
  72501. ** through the set members, skipping any duplicates. In this case an
  72502. ** epheremal table must be used unless the selected <column> is guaranteed
  72503. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  72504. ** has a UNIQUE constraint or UNIQUE index.
  72505. **
  72506. ** If the prNotFound parameter is not 0, then the b-tree will be used
  72507. ** for fast set membership tests. In this case an epheremal table must
  72508. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  72509. ** be found with <column> as its left-most column.
  72510. **
  72511. ** When the b-tree is being used for membership tests, the calling function
  72512. ** needs to know whether or not the structure contains an SQL NULL
  72513. ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
  72514. ** If there is any chance that the (...) might contain a NULL value at
  72515. ** runtime, then a register is allocated and the register number written
  72516. ** to *prNotFound. If there is no chance that the (...) contains a
  72517. ** NULL value, then *prNotFound is left unchanged.
  72518. **
  72519. ** If a register is allocated and its location stored in *prNotFound, then
  72520. ** its initial value is NULL. If the (...) does not remain constant
  72521. ** for the duration of the query (i.e. the SELECT within the (...)
  72522. ** is a correlated subquery) then the value of the allocated register is
  72523. ** reset to NULL each time the subquery is rerun. This allows the
  72524. ** caller to use vdbe code equivalent to the following:
  72525. **
  72526. ** if( register==NULL ){
  72527. ** has_null = <test if data structure contains null>
  72528. ** register = 1
  72529. ** }
  72530. **
  72531. ** in order to avoid running the <test if data structure contains null>
  72532. ** test more often than is necessary.
  72533. */
  72534. #ifndef SQLITE_OMIT_SUBQUERY
  72535. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  72536. Select *p; /* SELECT to the right of IN operator */
  72537. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  72538. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  72539. int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
  72540. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  72541. assert( pX->op==TK_IN );
  72542. /* Check to see if an existing table or index can be used to
  72543. ** satisfy the query. This is preferable to generating a new
  72544. ** ephemeral table.
  72545. */
  72546. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  72547. if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  72548. sqlite3 *db = pParse->db; /* Database connection */
  72549. Table *pTab; /* Table <table>. */
  72550. Expr *pExpr; /* Expression <column> */
  72551. int iCol; /* Index of column <column> */
  72552. int iDb; /* Database idx for pTab */
  72553. assert( p ); /* Because of isCandidateForInOpt(p) */
  72554. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  72555. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  72556. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  72557. pTab = p->pSrc->a[0].pTab;
  72558. pExpr = p->pEList->a[0].pExpr;
  72559. iCol = pExpr->iColumn;
  72560. /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
  72561. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  72562. sqlite3CodeVerifySchema(pParse, iDb);
  72563. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  72564. /* This function is only called from two places. In both cases the vdbe
  72565. ** has already been allocated. So assume sqlite3GetVdbe() is always
  72566. ** successful here.
  72567. */
  72568. assert(v);
  72569. if( iCol<0 ){
  72570. int iAddr;
  72571. iAddr = sqlite3CodeOnce(pParse);
  72572. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  72573. eType = IN_INDEX_ROWID;
  72574. sqlite3VdbeJumpHere(v, iAddr);
  72575. }else{
  72576. Index *pIdx; /* Iterator variable */
  72577. /* The collation sequence used by the comparison. If an index is to
  72578. ** be used in place of a temp-table, it must be ordered according
  72579. ** to this collation sequence. */
  72580. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  72581. /* Check that the affinity that will be used to perform the
  72582. ** comparison is the same as the affinity of the column. If
  72583. ** it is not, it is not possible to use any index.
  72584. */
  72585. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  72586. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  72587. if( (pIdx->aiColumn[0]==iCol)
  72588. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  72589. && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  72590. ){
  72591. int iAddr;
  72592. char *pKey;
  72593. pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  72594. iAddr = sqlite3CodeOnce(pParse);
  72595. sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  72596. pKey,P4_KEYINFO_HANDOFF);
  72597. VdbeComment((v, "%s", pIdx->zName));
  72598. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  72599. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  72600. sqlite3VdbeJumpHere(v, iAddr);
  72601. if( prNotFound && !pTab->aCol[iCol].notNull ){
  72602. *prNotFound = ++pParse->nMem;
  72603. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  72604. }
  72605. }
  72606. }
  72607. }
  72608. }
  72609. if( eType==0 ){
  72610. /* Could not found an existing table or index to use as the RHS b-tree.
  72611. ** We will have to generate an ephemeral table to do the job.
  72612. */
  72613. u32 savedNQueryLoop = pParse->nQueryLoop;
  72614. int rMayHaveNull = 0;
  72615. eType = IN_INDEX_EPH;
  72616. if( prNotFound ){
  72617. *prNotFound = rMayHaveNull = ++pParse->nMem;
  72618. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  72619. }else{
  72620. testcase( pParse->nQueryLoop>0 );
  72621. pParse->nQueryLoop = 0;
  72622. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  72623. eType = IN_INDEX_ROWID;
  72624. }
  72625. }
  72626. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  72627. pParse->nQueryLoop = savedNQueryLoop;
  72628. }else{
  72629. pX->iTable = iTab;
  72630. }
  72631. return eType;
  72632. }
  72633. #endif
  72634. /*
  72635. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  72636. ** or IN operators. Examples:
  72637. **
  72638. ** (SELECT a FROM b) -- subquery
  72639. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  72640. ** x IN (4,5,11) -- IN operator with list on right-hand side
  72641. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  72642. **
  72643. ** The pExpr parameter describes the expression that contains the IN
  72644. ** operator or subquery.
  72645. **
  72646. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  72647. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  72648. ** to some integer key column of a table B-Tree. In this case, use an
  72649. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  72650. ** (slower) variable length keys B-Tree.
  72651. **
  72652. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  72653. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  72654. ** Furthermore, the IN is in a WHERE clause and that we really want
  72655. ** to iterate over the RHS of the IN operator in order to quickly locate
  72656. ** all corresponding LHS elements. All this routine does is initialize
  72657. ** the register given by rMayHaveNull to NULL. Calling routines will take
  72658. ** care of changing this register value to non-NULL if the RHS is NULL-free.
  72659. **
  72660. ** If rMayHaveNull is zero, that means that the subquery is being used
  72661. ** for membership testing only. There is no need to initialize any
  72662. ** registers to indicate the presence or absence of NULLs on the RHS.
  72663. **
  72664. ** For a SELECT or EXISTS operator, return the register that holds the
  72665. ** result. For IN operators or if an error occurs, the return value is 0.
  72666. */
  72667. #ifndef SQLITE_OMIT_SUBQUERY
  72668. SQLITE_PRIVATE int sqlite3CodeSubselect(
  72669. Parse *pParse, /* Parsing context */
  72670. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  72671. int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
  72672. int isRowid /* If true, LHS of IN operator is a rowid */
  72673. ){
  72674. int testAddr = -1; /* One-time test address */
  72675. int rReg = 0; /* Register storing resulting */
  72676. Vdbe *v = sqlite3GetVdbe(pParse);
  72677. if( NEVER(v==0) ) return 0;
  72678. sqlite3ExprCachePush(pParse);
  72679. /* This code must be run in its entirety every time it is encountered
  72680. ** if any of the following is true:
  72681. **
  72682. ** * The right-hand side is a correlated subquery
  72683. ** * The right-hand side is an expression list containing variables
  72684. ** * We are inside a trigger
  72685. **
  72686. ** If all of the above are false, then we can run this code just once
  72687. ** save the results, and reuse the same result on subsequent invocations.
  72688. */
  72689. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  72690. testAddr = sqlite3CodeOnce(pParse);
  72691. }
  72692. #ifndef SQLITE_OMIT_EXPLAIN
  72693. if( pParse->explain==2 ){
  72694. char *zMsg = sqlite3MPrintf(
  72695. pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
  72696. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  72697. );
  72698. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  72699. }
  72700. #endif
  72701. switch( pExpr->op ){
  72702. case TK_IN: {
  72703. char affinity; /* Affinity of the LHS of the IN */
  72704. int addr; /* Address of OP_OpenEphemeral instruction */
  72705. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  72706. KeyInfo *pKeyInfo = 0; /* Key information */
  72707. if( rMayHaveNull ){
  72708. sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  72709. }
  72710. affinity = sqlite3ExprAffinity(pLeft);
  72711. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  72712. ** expression it is handled the same way. An ephemeral table is
  72713. ** filled with single-field index keys representing the results
  72714. ** from the SELECT or the <exprlist>.
  72715. **
  72716. ** If the 'x' expression is a column value, or the SELECT...
  72717. ** statement returns a column value, then the affinity of that
  72718. ** column is used to build the index keys. If both 'x' and the
  72719. ** SELECT... statement are columns, then numeric affinity is used
  72720. ** if either column has NUMERIC or INTEGER affinity. If neither
  72721. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  72722. ** is used.
  72723. */
  72724. pExpr->iTable = pParse->nTab++;
  72725. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  72726. if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  72727. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1);
  72728. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  72729. /* Case 1: expr IN (SELECT ...)
  72730. **
  72731. ** Generate code to write the results of the select into the temporary
  72732. ** table allocated and opened above.
  72733. */
  72734. SelectDest dest;
  72735. ExprList *pEList;
  72736. assert( !isRowid );
  72737. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  72738. dest.affSdst = (u8)affinity;
  72739. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  72740. pExpr->x.pSelect->iLimit = 0;
  72741. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  72742. if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
  72743. sqlite3DbFree(pParse->db, pKeyInfo);
  72744. return 0;
  72745. }
  72746. pEList = pExpr->x.pSelect->pEList;
  72747. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  72748. assert( pEList!=0 );
  72749. assert( pEList->nExpr>0 );
  72750. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  72751. pEList->a[0].pExpr);
  72752. }else if( ALWAYS(pExpr->x.pList!=0) ){
  72753. /* Case 2: expr IN (exprlist)
  72754. **
  72755. ** For each expression, build an index key from the evaluation and
  72756. ** store it in the temporary table. If <expr> is a column, then use
  72757. ** that columns affinity when building index keys. If <expr> is not
  72758. ** a column, use numeric affinity.
  72759. */
  72760. int i;
  72761. ExprList *pList = pExpr->x.pList;
  72762. struct ExprList_item *pItem;
  72763. int r1, r2, r3;
  72764. if( !affinity ){
  72765. affinity = SQLITE_AFF_NONE;
  72766. }
  72767. if( pKeyInfo ){
  72768. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  72769. }
  72770. /* Loop through each expression in <exprlist>. */
  72771. r1 = sqlite3GetTempReg(pParse);
  72772. r2 = sqlite3GetTempReg(pParse);
  72773. sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  72774. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  72775. Expr *pE2 = pItem->pExpr;
  72776. int iValToIns;
  72777. /* If the expression is not constant then we will need to
  72778. ** disable the test that was generated above that makes sure
  72779. ** this code only executes once. Because for a non-constant
  72780. ** expression we need to rerun this code each time.
  72781. */
  72782. if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
  72783. sqlite3VdbeChangeToNoop(v, testAddr);
  72784. testAddr = -1;
  72785. }
  72786. /* Evaluate the expression and insert it into the temp table */
  72787. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  72788. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  72789. }else{
  72790. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  72791. if( isRowid ){
  72792. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  72793. sqlite3VdbeCurrentAddr(v)+2);
  72794. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  72795. }else{
  72796. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  72797. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  72798. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  72799. }
  72800. }
  72801. }
  72802. sqlite3ReleaseTempReg(pParse, r1);
  72803. sqlite3ReleaseTempReg(pParse, r2);
  72804. }
  72805. if( pKeyInfo ){
  72806. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO_HANDOFF);
  72807. }
  72808. break;
  72809. }
  72810. case TK_EXISTS:
  72811. case TK_SELECT:
  72812. default: {
  72813. /* If this has to be a scalar SELECT. Generate code to put the
  72814. ** value of this select in a memory cell and record the number
  72815. ** of the memory cell in iColumn. If this is an EXISTS, write
  72816. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  72817. ** and record that memory cell in iColumn.
  72818. */
  72819. Select *pSel; /* SELECT statement to encode */
  72820. SelectDest dest; /* How to deal with SELECt result */
  72821. testcase( pExpr->op==TK_EXISTS );
  72822. testcase( pExpr->op==TK_SELECT );
  72823. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  72824. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  72825. pSel = pExpr->x.pSelect;
  72826. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  72827. if( pExpr->op==TK_SELECT ){
  72828. dest.eDest = SRT_Mem;
  72829. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  72830. VdbeComment((v, "Init subquery result"));
  72831. }else{
  72832. dest.eDest = SRT_Exists;
  72833. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  72834. VdbeComment((v, "Init EXISTS result"));
  72835. }
  72836. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  72837. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  72838. &sqlite3IntTokens[1]);
  72839. pSel->iLimit = 0;
  72840. if( sqlite3Select(pParse, pSel, &dest) ){
  72841. return 0;
  72842. }
  72843. rReg = dest.iSDParm;
  72844. ExprSetVVAProperty(pExpr, EP_NoReduce);
  72845. break;
  72846. }
  72847. }
  72848. if( testAddr>=0 ){
  72849. sqlite3VdbeJumpHere(v, testAddr);
  72850. }
  72851. sqlite3ExprCachePop(pParse, 1);
  72852. return rReg;
  72853. }
  72854. #endif /* SQLITE_OMIT_SUBQUERY */
  72855. #ifndef SQLITE_OMIT_SUBQUERY
  72856. /*
  72857. ** Generate code for an IN expression.
  72858. **
  72859. ** x IN (SELECT ...)
  72860. ** x IN (value, value, ...)
  72861. **
  72862. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  72863. ** is an array of zero or more values. The expression is true if the LHS is
  72864. ** contained within the RHS. The value of the expression is unknown (NULL)
  72865. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  72866. ** RHS contains one or more NULL values.
  72867. **
  72868. ** This routine generates code will jump to destIfFalse if the LHS is not
  72869. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  72870. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  72871. ** within the RHS then fall through.
  72872. */
  72873. static void sqlite3ExprCodeIN(
  72874. Parse *pParse, /* Parsing and code generating context */
  72875. Expr *pExpr, /* The IN expression */
  72876. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  72877. int destIfNull /* Jump here if the results are unknown due to NULLs */
  72878. ){
  72879. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  72880. char affinity; /* Comparison affinity to use */
  72881. int eType; /* Type of the RHS */
  72882. int r1; /* Temporary use register */
  72883. Vdbe *v; /* Statement under construction */
  72884. /* Compute the RHS. After this step, the table with cursor
  72885. ** pExpr->iTable will contains the values that make up the RHS.
  72886. */
  72887. v = pParse->pVdbe;
  72888. assert( v!=0 ); /* OOM detected prior to this routine */
  72889. VdbeNoopComment((v, "begin IN expr"));
  72890. eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
  72891. /* Figure out the affinity to use to create a key from the results
  72892. ** of the expression. affinityStr stores a static string suitable for
  72893. ** P4 of OP_MakeRecord.
  72894. */
  72895. affinity = comparisonAffinity(pExpr);
  72896. /* Code the LHS, the <expr> from "<expr> IN (...)".
  72897. */
  72898. sqlite3ExprCachePush(pParse);
  72899. r1 = sqlite3GetTempReg(pParse);
  72900. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  72901. /* If the LHS is NULL, then the result is either false or NULL depending
  72902. ** on whether the RHS is empty or not, respectively.
  72903. */
  72904. if( destIfNull==destIfFalse ){
  72905. /* Shortcut for the common case where the false and NULL outcomes are
  72906. ** the same. */
  72907. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
  72908. }else{
  72909. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
  72910. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  72911. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  72912. sqlite3VdbeJumpHere(v, addr1);
  72913. }
  72914. if( eType==IN_INDEX_ROWID ){
  72915. /* In this case, the RHS is the ROWID of table b-tree
  72916. */
  72917. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
  72918. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  72919. }else{
  72920. /* In this case, the RHS is an index b-tree.
  72921. */
  72922. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  72923. /* If the set membership test fails, then the result of the
  72924. ** "x IN (...)" expression must be either 0 or NULL. If the set
  72925. ** contains no NULL values, then the result is 0. If the set
  72926. ** contains one or more NULL values, then the result of the
  72927. ** expression is also NULL.
  72928. */
  72929. if( rRhsHasNull==0 || destIfFalse==destIfNull ){
  72930. /* This branch runs if it is known at compile time that the RHS
  72931. ** cannot contain NULL values. This happens as the result
  72932. ** of a "NOT NULL" constraint in the database schema.
  72933. **
  72934. ** Also run this branch if NULL is equivalent to FALSE
  72935. ** for this particular IN operator.
  72936. */
  72937. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  72938. }else{
  72939. /* In this branch, the RHS of the IN might contain a NULL and
  72940. ** the presence of a NULL on the RHS makes a difference in the
  72941. ** outcome.
  72942. */
  72943. int j1, j2, j3;
  72944. /* First check to see if the LHS is contained in the RHS. If so,
  72945. ** then the presence of NULLs in the RHS does not matter, so jump
  72946. ** over all of the code that follows.
  72947. */
  72948. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  72949. /* Here we begin generating code that runs if the LHS is not
  72950. ** contained within the RHS. Generate additional code that
  72951. ** tests the RHS for NULLs. If the RHS contains a NULL then
  72952. ** jump to destIfNull. If there are no NULLs in the RHS then
  72953. ** jump to destIfFalse.
  72954. */
  72955. j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
  72956. j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
  72957. sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
  72958. sqlite3VdbeJumpHere(v, j3);
  72959. sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
  72960. sqlite3VdbeJumpHere(v, j2);
  72961. /* Jump to the appropriate target depending on whether or not
  72962. ** the RHS contains a NULL
  72963. */
  72964. sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
  72965. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  72966. /* The OP_Found at the top of this branch jumps here when true,
  72967. ** causing the overall IN expression evaluation to fall through.
  72968. */
  72969. sqlite3VdbeJumpHere(v, j1);
  72970. }
  72971. }
  72972. sqlite3ReleaseTempReg(pParse, r1);
  72973. sqlite3ExprCachePop(pParse, 1);
  72974. VdbeComment((v, "end IN expr"));
  72975. }
  72976. #endif /* SQLITE_OMIT_SUBQUERY */
  72977. /*
  72978. ** Duplicate an 8-byte value
  72979. */
  72980. static char *dup8bytes(Vdbe *v, const char *in){
  72981. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  72982. if( out ){
  72983. memcpy(out, in, 8);
  72984. }
  72985. return out;
  72986. }
  72987. #ifndef SQLITE_OMIT_FLOATING_POINT
  72988. /*
  72989. ** Generate an instruction that will put the floating point
  72990. ** value described by z[0..n-1] into register iMem.
  72991. **
  72992. ** The z[] string will probably not be zero-terminated. But the
  72993. ** z[n] character is guaranteed to be something that does not look
  72994. ** like the continuation of the number.
  72995. */
  72996. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  72997. if( ALWAYS(z!=0) ){
  72998. double value;
  72999. char *zV;
  73000. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  73001. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  73002. if( negateFlag ) value = -value;
  73003. zV = dup8bytes(v, (char*)&value);
  73004. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  73005. }
  73006. }
  73007. #endif
  73008. /*
  73009. ** Generate an instruction that will put the integer describe by
  73010. ** text z[0..n-1] into register iMem.
  73011. **
  73012. ** Expr.u.zToken is always UTF8 and zero-terminated.
  73013. */
  73014. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  73015. Vdbe *v = pParse->pVdbe;
  73016. if( pExpr->flags & EP_IntValue ){
  73017. int i = pExpr->u.iValue;
  73018. assert( i>=0 );
  73019. if( negFlag ) i = -i;
  73020. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  73021. }else{
  73022. int c;
  73023. i64 value;
  73024. const char *z = pExpr->u.zToken;
  73025. assert( z!=0 );
  73026. c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  73027. if( c==0 || (c==2 && negFlag) ){
  73028. char *zV;
  73029. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  73030. zV = dup8bytes(v, (char*)&value);
  73031. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  73032. }else{
  73033. #ifdef SQLITE_OMIT_FLOATING_POINT
  73034. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  73035. #else
  73036. codeReal(v, z, negFlag, iMem);
  73037. #endif
  73038. }
  73039. }
  73040. }
  73041. /*
  73042. ** Clear a cache entry.
  73043. */
  73044. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  73045. if( p->tempReg ){
  73046. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  73047. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  73048. }
  73049. p->tempReg = 0;
  73050. }
  73051. }
  73052. /*
  73053. ** Record in the column cache that a particular column from a
  73054. ** particular table is stored in a particular register.
  73055. */
  73056. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  73057. int i;
  73058. int minLru;
  73059. int idxLru;
  73060. struct yColCache *p;
  73061. assert( iReg>0 ); /* Register numbers are always positive */
  73062. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  73063. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  73064. ** for testing only - to verify that SQLite always gets the same answer
  73065. ** with and without the column cache.
  73066. */
  73067. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  73068. /* First replace any existing entry.
  73069. **
  73070. ** Actually, the way the column cache is currently used, we are guaranteed
  73071. ** that the object will never already be in cache. Verify this guarantee.
  73072. */
  73073. #ifndef NDEBUG
  73074. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  73075. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  73076. }
  73077. #endif
  73078. /* Find an empty slot and replace it */
  73079. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  73080. if( p->iReg==0 ){
  73081. p->iLevel = pParse->iCacheLevel;
  73082. p->iTable = iTab;
  73083. p->iColumn = iCol;
  73084. p->iReg = iReg;
  73085. p->tempReg = 0;
  73086. p->lru = pParse->iCacheCnt++;
  73087. return;
  73088. }
  73089. }
  73090. /* Replace the last recently used */
  73091. minLru = 0x7fffffff;
  73092. idxLru = -1;
  73093. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  73094. if( p->lru<minLru ){
  73095. idxLru = i;
  73096. minLru = p->lru;
  73097. }
  73098. }
  73099. if( ALWAYS(idxLru>=0) ){
  73100. p = &pParse->aColCache[idxLru];
  73101. p->iLevel = pParse->iCacheLevel;
  73102. p->iTable = iTab;
  73103. p->iColumn = iCol;
  73104. p->iReg = iReg;
  73105. p->tempReg = 0;
  73106. p->lru = pParse->iCacheCnt++;
  73107. return;
  73108. }
  73109. }
  73110. /*
  73111. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  73112. ** Purge the range of registers from the column cache.
  73113. */
  73114. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  73115. int i;
  73116. int iLast = iReg + nReg - 1;
  73117. struct yColCache *p;
  73118. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  73119. int r = p->iReg;
  73120. if( r>=iReg && r<=iLast ){
  73121. cacheEntryClear(pParse, p);
  73122. p->iReg = 0;
  73123. }
  73124. }
  73125. }
  73126. /*
  73127. ** Remember the current column cache context. Any new entries added
  73128. ** added to the column cache after this call are removed when the
  73129. ** corresponding pop occurs.
  73130. */
  73131. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  73132. pParse->iCacheLevel++;
  73133. }
  73134. /*
  73135. ** Remove from the column cache any entries that were added since the
  73136. ** the previous N Push operations. In other words, restore the cache
  73137. ** to the state it was in N Pushes ago.
  73138. */
  73139. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
  73140. int i;
  73141. struct yColCache *p;
  73142. assert( N>0 );
  73143. assert( pParse->iCacheLevel>=N );
  73144. pParse->iCacheLevel -= N;
  73145. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  73146. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  73147. cacheEntryClear(pParse, p);
  73148. p->iReg = 0;
  73149. }
  73150. }
  73151. }
  73152. /*
  73153. ** When a cached column is reused, make sure that its register is
  73154. ** no longer available as a temp register. ticket #3879: that same
  73155. ** register might be in the cache in multiple places, so be sure to
  73156. ** get them all.
  73157. */
  73158. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  73159. int i;
  73160. struct yColCache *p;
  73161. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  73162. if( p->iReg==iReg ){
  73163. p->tempReg = 0;
  73164. }
  73165. }
  73166. }
  73167. /*
  73168. ** Generate code to extract the value of the iCol-th column of a table.
  73169. */
  73170. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  73171. Vdbe *v, /* The VDBE under construction */
  73172. Table *pTab, /* The table containing the value */
  73173. int iTabCur, /* The cursor for this table */
  73174. int iCol, /* Index of the column to extract */
  73175. int regOut /* Extract the valud into this register */
  73176. ){
  73177. if( iCol<0 || iCol==pTab->iPKey ){
  73178. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  73179. }else{
  73180. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  73181. sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
  73182. }
  73183. if( iCol>=0 ){
  73184. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  73185. }
  73186. }
  73187. /*
  73188. ** Generate code that will extract the iColumn-th column from
  73189. ** table pTab and store the column value in a register. An effort
  73190. ** is made to store the column value in register iReg, but this is
  73191. ** not guaranteed. The location of the column value is returned.
  73192. **
  73193. ** There must be an open cursor to pTab in iTable when this routine
  73194. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  73195. */
  73196. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  73197. Parse *pParse, /* Parsing and code generating context */
  73198. Table *pTab, /* Description of the table we are reading from */
  73199. int iColumn, /* Index of the table column */
  73200. int iTable, /* The cursor pointing to the table */
  73201. int iReg, /* Store results here */
  73202. u8 p5 /* P5 value for OP_Column */
  73203. ){
  73204. Vdbe *v = pParse->pVdbe;
  73205. int i;
  73206. struct yColCache *p;
  73207. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  73208. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  73209. p->lru = pParse->iCacheCnt++;
  73210. sqlite3ExprCachePinRegister(pParse, p->iReg);
  73211. return p->iReg;
  73212. }
  73213. }
  73214. assert( v!=0 );
  73215. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  73216. if( p5 ){
  73217. sqlite3VdbeChangeP5(v, p5);
  73218. }else{
  73219. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  73220. }
  73221. return iReg;
  73222. }
  73223. /*
  73224. ** Clear all column cache entries.
  73225. */
  73226. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  73227. int i;
  73228. struct yColCache *p;
  73229. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  73230. if( p->iReg ){
  73231. cacheEntryClear(pParse, p);
  73232. p->iReg = 0;
  73233. }
  73234. }
  73235. }
  73236. /*
  73237. ** Record the fact that an affinity change has occurred on iCount
  73238. ** registers starting with iStart.
  73239. */
  73240. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  73241. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  73242. }
  73243. /*
  73244. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  73245. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  73246. */
  73247. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  73248. int i;
  73249. struct yColCache *p;
  73250. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  73251. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
  73252. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  73253. int x = p->iReg;
  73254. if( x>=iFrom && x<iFrom+nReg ){
  73255. p->iReg += iTo-iFrom;
  73256. }
  73257. }
  73258. }
  73259. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  73260. /*
  73261. ** Return true if any register in the range iFrom..iTo (inclusive)
  73262. ** is used as part of the column cache.
  73263. **
  73264. ** This routine is used within assert() and testcase() macros only
  73265. ** and does not appear in a normal build.
  73266. */
  73267. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  73268. int i;
  73269. struct yColCache *p;
  73270. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  73271. int r = p->iReg;
  73272. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  73273. }
  73274. return 0;
  73275. }
  73276. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  73277. /*
  73278. ** Convert an expression node to a TK_REGISTER
  73279. */
  73280. static void exprToRegister(Expr *p, int iReg){
  73281. p->op2 = p->op;
  73282. p->op = TK_REGISTER;
  73283. p->iTable = iReg;
  73284. ExprClearProperty(p, EP_Skip);
  73285. }
  73286. /*
  73287. ** Generate code into the current Vdbe to evaluate the given
  73288. ** expression. Attempt to store the results in register "target".
  73289. ** Return the register where results are stored.
  73290. **
  73291. ** With this routine, there is no guarantee that results will
  73292. ** be stored in target. The result might be stored in some other
  73293. ** register if it is convenient to do so. The calling function
  73294. ** must check the return code and move the results to the desired
  73295. ** register.
  73296. */
  73297. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  73298. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  73299. int op; /* The opcode being coded */
  73300. int inReg = target; /* Results stored in register inReg */
  73301. int regFree1 = 0; /* If non-zero free this temporary register */
  73302. int regFree2 = 0; /* If non-zero free this temporary register */
  73303. int r1, r2, r3, r4; /* Various register numbers */
  73304. sqlite3 *db = pParse->db; /* The database connection */
  73305. assert( target>0 && target<=pParse->nMem );
  73306. if( v==0 ){
  73307. assert( pParse->db->mallocFailed );
  73308. return 0;
  73309. }
  73310. if( pExpr==0 ){
  73311. op = TK_NULL;
  73312. }else{
  73313. op = pExpr->op;
  73314. }
  73315. switch( op ){
  73316. case TK_AGG_COLUMN: {
  73317. AggInfo *pAggInfo = pExpr->pAggInfo;
  73318. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  73319. if( !pAggInfo->directMode ){
  73320. assert( pCol->iMem>0 );
  73321. inReg = pCol->iMem;
  73322. break;
  73323. }else if( pAggInfo->useSortingIdx ){
  73324. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  73325. pCol->iSorterColumn, target);
  73326. break;
  73327. }
  73328. /* Otherwise, fall thru into the TK_COLUMN case */
  73329. }
  73330. case TK_COLUMN: {
  73331. int iTab = pExpr->iTable;
  73332. if( iTab<0 ){
  73333. if( pParse->ckBase>0 ){
  73334. /* Generating CHECK constraints or inserting into partial index */
  73335. inReg = pExpr->iColumn + pParse->ckBase;
  73336. break;
  73337. }else{
  73338. /* Deleting from a partial index */
  73339. iTab = pParse->iPartIdxTab;
  73340. }
  73341. }
  73342. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  73343. pExpr->iColumn, iTab, target,
  73344. pExpr->op2);
  73345. break;
  73346. }
  73347. case TK_INTEGER: {
  73348. codeInteger(pParse, pExpr, 0, target);
  73349. break;
  73350. }
  73351. #ifndef SQLITE_OMIT_FLOATING_POINT
  73352. case TK_FLOAT: {
  73353. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  73354. codeReal(v, pExpr->u.zToken, 0, target);
  73355. break;
  73356. }
  73357. #endif
  73358. case TK_STRING: {
  73359. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  73360. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  73361. break;
  73362. }
  73363. case TK_NULL: {
  73364. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  73365. break;
  73366. }
  73367. #ifndef SQLITE_OMIT_BLOB_LITERAL
  73368. case TK_BLOB: {
  73369. int n;
  73370. const char *z;
  73371. char *zBlob;
  73372. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  73373. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  73374. assert( pExpr->u.zToken[1]=='\'' );
  73375. z = &pExpr->u.zToken[2];
  73376. n = sqlite3Strlen30(z) - 1;
  73377. assert( z[n]=='\'' );
  73378. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  73379. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  73380. break;
  73381. }
  73382. #endif
  73383. case TK_VARIABLE: {
  73384. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  73385. assert( pExpr->u.zToken!=0 );
  73386. assert( pExpr->u.zToken[0]!=0 );
  73387. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  73388. if( pExpr->u.zToken[1]!=0 ){
  73389. assert( pExpr->u.zToken[0]=='?'
  73390. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  73391. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  73392. }
  73393. break;
  73394. }
  73395. case TK_REGISTER: {
  73396. inReg = pExpr->iTable;
  73397. break;
  73398. }
  73399. case TK_AS: {
  73400. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  73401. break;
  73402. }
  73403. #ifndef SQLITE_OMIT_CAST
  73404. case TK_CAST: {
  73405. /* Expressions of the form: CAST(pLeft AS token) */
  73406. int aff, to_op;
  73407. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  73408. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  73409. aff = sqlite3AffinityType(pExpr->u.zToken, 0);
  73410. to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
  73411. assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
  73412. assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
  73413. assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
  73414. assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
  73415. assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
  73416. testcase( to_op==OP_ToText );
  73417. testcase( to_op==OP_ToBlob );
  73418. testcase( to_op==OP_ToNumeric );
  73419. testcase( to_op==OP_ToInt );
  73420. testcase( to_op==OP_ToReal );
  73421. if( inReg!=target ){
  73422. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  73423. inReg = target;
  73424. }
  73425. sqlite3VdbeAddOp1(v, to_op, inReg);
  73426. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  73427. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  73428. break;
  73429. }
  73430. #endif /* SQLITE_OMIT_CAST */
  73431. case TK_LT:
  73432. case TK_LE:
  73433. case TK_GT:
  73434. case TK_GE:
  73435. case TK_NE:
  73436. case TK_EQ: {
  73437. assert( TK_LT==OP_Lt );
  73438. assert( TK_LE==OP_Le );
  73439. assert( TK_GT==OP_Gt );
  73440. assert( TK_GE==OP_Ge );
  73441. assert( TK_EQ==OP_Eq );
  73442. assert( TK_NE==OP_Ne );
  73443. testcase( op==TK_LT );
  73444. testcase( op==TK_LE );
  73445. testcase( op==TK_GT );
  73446. testcase( op==TK_GE );
  73447. testcase( op==TK_EQ );
  73448. testcase( op==TK_NE );
  73449. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  73450. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  73451. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  73452. r1, r2, inReg, SQLITE_STOREP2);
  73453. testcase( regFree1==0 );
  73454. testcase( regFree2==0 );
  73455. break;
  73456. }
  73457. case TK_IS:
  73458. case TK_ISNOT: {
  73459. testcase( op==TK_IS );
  73460. testcase( op==TK_ISNOT );
  73461. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  73462. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  73463. op = (op==TK_IS) ? TK_EQ : TK_NE;
  73464. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  73465. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  73466. testcase( regFree1==0 );
  73467. testcase( regFree2==0 );
  73468. break;
  73469. }
  73470. case TK_AND:
  73471. case TK_OR:
  73472. case TK_PLUS:
  73473. case TK_STAR:
  73474. case TK_MINUS:
  73475. case TK_REM:
  73476. case TK_BITAND:
  73477. case TK_BITOR:
  73478. case TK_SLASH:
  73479. case TK_LSHIFT:
  73480. case TK_RSHIFT:
  73481. case TK_CONCAT: {
  73482. assert( TK_AND==OP_And );
  73483. assert( TK_OR==OP_Or );
  73484. assert( TK_PLUS==OP_Add );
  73485. assert( TK_MINUS==OP_Subtract );
  73486. assert( TK_REM==OP_Remainder );
  73487. assert( TK_BITAND==OP_BitAnd );
  73488. assert( TK_BITOR==OP_BitOr );
  73489. assert( TK_SLASH==OP_Divide );
  73490. assert( TK_LSHIFT==OP_ShiftLeft );
  73491. assert( TK_RSHIFT==OP_ShiftRight );
  73492. assert( TK_CONCAT==OP_Concat );
  73493. testcase( op==TK_AND );
  73494. testcase( op==TK_OR );
  73495. testcase( op==TK_PLUS );
  73496. testcase( op==TK_MINUS );
  73497. testcase( op==TK_REM );
  73498. testcase( op==TK_BITAND );
  73499. testcase( op==TK_BITOR );
  73500. testcase( op==TK_SLASH );
  73501. testcase( op==TK_LSHIFT );
  73502. testcase( op==TK_RSHIFT );
  73503. testcase( op==TK_CONCAT );
  73504. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  73505. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  73506. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  73507. testcase( regFree1==0 );
  73508. testcase( regFree2==0 );
  73509. break;
  73510. }
  73511. case TK_UMINUS: {
  73512. Expr *pLeft = pExpr->pLeft;
  73513. assert( pLeft );
  73514. if( pLeft->op==TK_INTEGER ){
  73515. codeInteger(pParse, pLeft, 1, target);
  73516. #ifndef SQLITE_OMIT_FLOATING_POINT
  73517. }else if( pLeft->op==TK_FLOAT ){
  73518. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  73519. codeReal(v, pLeft->u.zToken, 1, target);
  73520. #endif
  73521. }else{
  73522. regFree1 = r1 = sqlite3GetTempReg(pParse);
  73523. sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
  73524. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  73525. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  73526. testcase( regFree2==0 );
  73527. }
  73528. inReg = target;
  73529. break;
  73530. }
  73531. case TK_BITNOT:
  73532. case TK_NOT: {
  73533. assert( TK_BITNOT==OP_BitNot );
  73534. assert( TK_NOT==OP_Not );
  73535. testcase( op==TK_BITNOT );
  73536. testcase( op==TK_NOT );
  73537. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  73538. testcase( regFree1==0 );
  73539. inReg = target;
  73540. sqlite3VdbeAddOp2(v, op, r1, inReg);
  73541. break;
  73542. }
  73543. case TK_ISNULL:
  73544. case TK_NOTNULL: {
  73545. int addr;
  73546. assert( TK_ISNULL==OP_IsNull );
  73547. assert( TK_NOTNULL==OP_NotNull );
  73548. testcase( op==TK_ISNULL );
  73549. testcase( op==TK_NOTNULL );
  73550. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  73551. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  73552. testcase( regFree1==0 );
  73553. addr = sqlite3VdbeAddOp1(v, op, r1);
  73554. sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  73555. sqlite3VdbeJumpHere(v, addr);
  73556. break;
  73557. }
  73558. case TK_AGG_FUNCTION: {
  73559. AggInfo *pInfo = pExpr->pAggInfo;
  73560. if( pInfo==0 ){
  73561. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  73562. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  73563. }else{
  73564. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  73565. }
  73566. break;
  73567. }
  73568. case TK_CONST_FUNC:
  73569. case TK_FUNCTION: {
  73570. ExprList *pFarg; /* List of function arguments */
  73571. int nFarg; /* Number of function arguments */
  73572. FuncDef *pDef; /* The function definition object */
  73573. int nId; /* Length of the function name in bytes */
  73574. const char *zId; /* The function name */
  73575. int constMask = 0; /* Mask of function arguments that are constant */
  73576. int i; /* Loop counter */
  73577. u8 enc = ENC(db); /* The text encoding used by this database */
  73578. CollSeq *pColl = 0; /* A collating sequence */
  73579. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  73580. testcase( op==TK_CONST_FUNC );
  73581. testcase( op==TK_FUNCTION );
  73582. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  73583. pFarg = 0;
  73584. }else{
  73585. pFarg = pExpr->x.pList;
  73586. }
  73587. nFarg = pFarg ? pFarg->nExpr : 0;
  73588. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  73589. zId = pExpr->u.zToken;
  73590. nId = sqlite3Strlen30(zId);
  73591. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  73592. if( pDef==0 ){
  73593. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  73594. break;
  73595. }
  73596. /* Attempt a direct implementation of the built-in COALESCE() and
  73597. ** IFNULL() functions. This avoids unnecessary evalation of
  73598. ** arguments past the first non-NULL argument.
  73599. */
  73600. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  73601. int endCoalesce = sqlite3VdbeMakeLabel(v);
  73602. assert( nFarg>=2 );
  73603. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  73604. for(i=1; i<nFarg; i++){
  73605. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  73606. sqlite3ExprCacheRemove(pParse, target, 1);
  73607. sqlite3ExprCachePush(pParse);
  73608. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  73609. sqlite3ExprCachePop(pParse, 1);
  73610. }
  73611. sqlite3VdbeResolveLabel(v, endCoalesce);
  73612. break;
  73613. }
  73614. /* The UNLIKELY() function is a no-op. The result is the value
  73615. ** of the first argument.
  73616. */
  73617. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  73618. assert( nFarg>=1 );
  73619. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  73620. break;
  73621. }
  73622. if( pFarg ){
  73623. r1 = sqlite3GetTempRange(pParse, nFarg);
  73624. /* For length() and typeof() functions with a column argument,
  73625. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  73626. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  73627. ** loading.
  73628. */
  73629. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  73630. u8 exprOp;
  73631. assert( nFarg==1 );
  73632. assert( pFarg->a[0].pExpr!=0 );
  73633. exprOp = pFarg->a[0].pExpr->op;
  73634. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  73635. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  73636. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  73637. testcase( (pDef->funcFlags&~SQLITE_FUNC_ENCMASK)
  73638. ==SQLITE_FUNC_LENGTH );
  73639. pFarg->a[0].pExpr->op2 = pDef->funcFlags&~SQLITE_FUNC_ENCMASK;
  73640. }
  73641. }
  73642. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  73643. sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
  73644. sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
  73645. }else{
  73646. r1 = 0;
  73647. }
  73648. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73649. /* Possibly overload the function if the first argument is
  73650. ** a virtual table column.
  73651. **
  73652. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  73653. ** second argument, not the first, as the argument to test to
  73654. ** see if it is a column in a virtual table. This is done because
  73655. ** the left operand of infix functions (the operand we want to
  73656. ** control overloading) ends up as the second argument to the
  73657. ** function. The expression "A glob B" is equivalent to
  73658. ** "glob(B,A). We want to use the A in "A glob B" to test
  73659. ** for function overloading. But we use the B term in "glob(B,A)".
  73660. */
  73661. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  73662. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  73663. }else if( nFarg>0 ){
  73664. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  73665. }
  73666. #endif
  73667. for(i=0; i<nFarg; i++){
  73668. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  73669. constMask |= (1<<i);
  73670. }
  73671. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  73672. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  73673. }
  73674. }
  73675. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  73676. if( !pColl ) pColl = db->pDfltColl;
  73677. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  73678. }
  73679. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  73680. (char*)pDef, P4_FUNCDEF);
  73681. sqlite3VdbeChangeP5(v, (u8)nFarg);
  73682. if( nFarg ){
  73683. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  73684. }
  73685. break;
  73686. }
  73687. #ifndef SQLITE_OMIT_SUBQUERY
  73688. case TK_EXISTS:
  73689. case TK_SELECT: {
  73690. testcase( op==TK_EXISTS );
  73691. testcase( op==TK_SELECT );
  73692. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  73693. break;
  73694. }
  73695. case TK_IN: {
  73696. int destIfFalse = sqlite3VdbeMakeLabel(v);
  73697. int destIfNull = sqlite3VdbeMakeLabel(v);
  73698. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  73699. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  73700. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  73701. sqlite3VdbeResolveLabel(v, destIfFalse);
  73702. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  73703. sqlite3VdbeResolveLabel(v, destIfNull);
  73704. break;
  73705. }
  73706. #endif /* SQLITE_OMIT_SUBQUERY */
  73707. /*
  73708. ** x BETWEEN y AND z
  73709. **
  73710. ** This is equivalent to
  73711. **
  73712. ** x>=y AND x<=z
  73713. **
  73714. ** X is stored in pExpr->pLeft.
  73715. ** Y is stored in pExpr->pList->a[0].pExpr.
  73716. ** Z is stored in pExpr->pList->a[1].pExpr.
  73717. */
  73718. case TK_BETWEEN: {
  73719. Expr *pLeft = pExpr->pLeft;
  73720. struct ExprList_item *pLItem = pExpr->x.pList->a;
  73721. Expr *pRight = pLItem->pExpr;
  73722. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  73723. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  73724. testcase( regFree1==0 );
  73725. testcase( regFree2==0 );
  73726. r3 = sqlite3GetTempReg(pParse);
  73727. r4 = sqlite3GetTempReg(pParse);
  73728. codeCompare(pParse, pLeft, pRight, OP_Ge,
  73729. r1, r2, r3, SQLITE_STOREP2);
  73730. pLItem++;
  73731. pRight = pLItem->pExpr;
  73732. sqlite3ReleaseTempReg(pParse, regFree2);
  73733. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  73734. testcase( regFree2==0 );
  73735. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  73736. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  73737. sqlite3ReleaseTempReg(pParse, r3);
  73738. sqlite3ReleaseTempReg(pParse, r4);
  73739. break;
  73740. }
  73741. case TK_COLLATE:
  73742. case TK_UPLUS: {
  73743. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  73744. break;
  73745. }
  73746. case TK_TRIGGER: {
  73747. /* If the opcode is TK_TRIGGER, then the expression is a reference
  73748. ** to a column in the new.* or old.* pseudo-tables available to
  73749. ** trigger programs. In this case Expr.iTable is set to 1 for the
  73750. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  73751. ** is set to the column of the pseudo-table to read, or to -1 to
  73752. ** read the rowid field.
  73753. **
  73754. ** The expression is implemented using an OP_Param opcode. The p1
  73755. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  73756. ** to reference another column of the old.* pseudo-table, where
  73757. ** i is the index of the column. For a new.rowid reference, p1 is
  73758. ** set to (n+1), where n is the number of columns in each pseudo-table.
  73759. ** For a reference to any other column in the new.* pseudo-table, p1
  73760. ** is set to (n+2+i), where n and i are as defined previously. For
  73761. ** example, if the table on which triggers are being fired is
  73762. ** declared as:
  73763. **
  73764. ** CREATE TABLE t1(a, b);
  73765. **
  73766. ** Then p1 is interpreted as follows:
  73767. **
  73768. ** p1==0 -> old.rowid p1==3 -> new.rowid
  73769. ** p1==1 -> old.a p1==4 -> new.a
  73770. ** p1==2 -> old.b p1==5 -> new.b
  73771. */
  73772. Table *pTab = pExpr->pTab;
  73773. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  73774. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  73775. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  73776. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  73777. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  73778. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  73779. VdbeComment((v, "%s.%s -> $%d",
  73780. (pExpr->iTable ? "new" : "old"),
  73781. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  73782. target
  73783. ));
  73784. #ifndef SQLITE_OMIT_FLOATING_POINT
  73785. /* If the column has REAL affinity, it may currently be stored as an
  73786. ** integer. Use OP_RealAffinity to make sure it is really real. */
  73787. if( pExpr->iColumn>=0
  73788. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  73789. ){
  73790. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  73791. }
  73792. #endif
  73793. break;
  73794. }
  73795. /*
  73796. ** Form A:
  73797. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  73798. **
  73799. ** Form B:
  73800. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  73801. **
  73802. ** Form A is can be transformed into the equivalent form B as follows:
  73803. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  73804. ** WHEN x=eN THEN rN ELSE y END
  73805. **
  73806. ** X (if it exists) is in pExpr->pLeft.
  73807. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  73808. ** odd. The Y is also optional. If the number of elements in x.pList
  73809. ** is even, then Y is omitted and the "otherwise" result is NULL.
  73810. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  73811. **
  73812. ** The result of the expression is the Ri for the first matching Ei,
  73813. ** or if there is no matching Ei, the ELSE term Y, or if there is
  73814. ** no ELSE term, NULL.
  73815. */
  73816. default: assert( op==TK_CASE ); {
  73817. int endLabel; /* GOTO label for end of CASE stmt */
  73818. int nextCase; /* GOTO label for next WHEN clause */
  73819. int nExpr; /* 2x number of WHEN terms */
  73820. int i; /* Loop counter */
  73821. ExprList *pEList; /* List of WHEN terms */
  73822. struct ExprList_item *aListelem; /* Array of WHEN terms */
  73823. Expr opCompare; /* The X==Ei expression */
  73824. Expr cacheX; /* Cached expression X */
  73825. Expr *pX; /* The X expression */
  73826. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  73827. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  73828. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  73829. assert(pExpr->x.pList->nExpr > 0);
  73830. pEList = pExpr->x.pList;
  73831. aListelem = pEList->a;
  73832. nExpr = pEList->nExpr;
  73833. endLabel = sqlite3VdbeMakeLabel(v);
  73834. if( (pX = pExpr->pLeft)!=0 ){
  73835. cacheX = *pX;
  73836. testcase( pX->op==TK_COLUMN );
  73837. testcase( pX->op==TK_REGISTER );
  73838. exprToRegister(&cacheX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  73839. testcase( regFree1==0 );
  73840. opCompare.op = TK_EQ;
  73841. opCompare.pLeft = &cacheX;
  73842. pTest = &opCompare;
  73843. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  73844. ** The value in regFree1 might get SCopy-ed into the file result.
  73845. ** So make sure that the regFree1 register is not reused for other
  73846. ** purposes and possibly overwritten. */
  73847. regFree1 = 0;
  73848. }
  73849. for(i=0; i<nExpr-1; i=i+2){
  73850. sqlite3ExprCachePush(pParse);
  73851. if( pX ){
  73852. assert( pTest!=0 );
  73853. opCompare.pRight = aListelem[i].pExpr;
  73854. }else{
  73855. pTest = aListelem[i].pExpr;
  73856. }
  73857. nextCase = sqlite3VdbeMakeLabel(v);
  73858. testcase( pTest->op==TK_COLUMN );
  73859. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  73860. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  73861. testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  73862. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  73863. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  73864. sqlite3ExprCachePop(pParse, 1);
  73865. sqlite3VdbeResolveLabel(v, nextCase);
  73866. }
  73867. if( (nExpr&1)!=0 ){
  73868. sqlite3ExprCachePush(pParse);
  73869. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  73870. sqlite3ExprCachePop(pParse, 1);
  73871. }else{
  73872. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  73873. }
  73874. assert( db->mallocFailed || pParse->nErr>0
  73875. || pParse->iCacheLevel==iCacheLevel );
  73876. sqlite3VdbeResolveLabel(v, endLabel);
  73877. break;
  73878. }
  73879. #ifndef SQLITE_OMIT_TRIGGER
  73880. case TK_RAISE: {
  73881. assert( pExpr->affinity==OE_Rollback
  73882. || pExpr->affinity==OE_Abort
  73883. || pExpr->affinity==OE_Fail
  73884. || pExpr->affinity==OE_Ignore
  73885. );
  73886. if( !pParse->pTriggerTab ){
  73887. sqlite3ErrorMsg(pParse,
  73888. "RAISE() may only be used within a trigger-program");
  73889. return 0;
  73890. }
  73891. if( pExpr->affinity==OE_Abort ){
  73892. sqlite3MayAbort(pParse);
  73893. }
  73894. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  73895. if( pExpr->affinity==OE_Ignore ){
  73896. sqlite3VdbeAddOp4(
  73897. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  73898. }else{
  73899. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  73900. pExpr->affinity, pExpr->u.zToken, 0);
  73901. }
  73902. break;
  73903. }
  73904. #endif
  73905. }
  73906. sqlite3ReleaseTempReg(pParse, regFree1);
  73907. sqlite3ReleaseTempReg(pParse, regFree2);
  73908. return inReg;
  73909. }
  73910. /*
  73911. ** Generate code to evaluate an expression and store the results
  73912. ** into a register. Return the register number where the results
  73913. ** are stored.
  73914. **
  73915. ** If the register is a temporary register that can be deallocated,
  73916. ** then write its number into *pReg. If the result register is not
  73917. ** a temporary, then set *pReg to zero.
  73918. */
  73919. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  73920. int r1 = sqlite3GetTempReg(pParse);
  73921. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  73922. if( r2==r1 ){
  73923. *pReg = r1;
  73924. }else{
  73925. sqlite3ReleaseTempReg(pParse, r1);
  73926. *pReg = 0;
  73927. }
  73928. return r2;
  73929. }
  73930. /*
  73931. ** Generate code that will evaluate expression pExpr and store the
  73932. ** results in register target. The results are guaranteed to appear
  73933. ** in register target.
  73934. */
  73935. SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  73936. int inReg;
  73937. assert( target>0 && target<=pParse->nMem );
  73938. if( pExpr && pExpr->op==TK_REGISTER ){
  73939. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  73940. }else{
  73941. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  73942. assert( pParse->pVdbe || pParse->db->mallocFailed );
  73943. if( inReg!=target && pParse->pVdbe ){
  73944. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  73945. }
  73946. }
  73947. return target;
  73948. }
  73949. /*
  73950. ** Generate code that evalutes the given expression and puts the result
  73951. ** in register target.
  73952. **
  73953. ** Also make a copy of the expression results into another "cache" register
  73954. ** and modify the expression so that the next time it is evaluated,
  73955. ** the result is a copy of the cache register.
  73956. **
  73957. ** This routine is used for expressions that are used multiple
  73958. ** times. They are evaluated once and the results of the expression
  73959. ** are reused.
  73960. */
  73961. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  73962. Vdbe *v = pParse->pVdbe;
  73963. int inReg;
  73964. inReg = sqlite3ExprCode(pParse, pExpr, target);
  73965. assert( target>0 );
  73966. /* This routine is called for terms to INSERT or UPDATE. And the only
  73967. ** other place where expressions can be converted into TK_REGISTER is
  73968. ** in WHERE clause processing. So as currently implemented, there is
  73969. ** no way for a TK_REGISTER to exist here. But it seems prudent to
  73970. ** keep the ALWAYS() in case the conditions above change with future
  73971. ** modifications or enhancements. */
  73972. if( ALWAYS(pExpr->op!=TK_REGISTER) ){
  73973. int iMem;
  73974. iMem = ++pParse->nMem;
  73975. sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  73976. exprToRegister(pExpr, iMem);
  73977. }
  73978. return inReg;
  73979. }
  73980. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  73981. /*
  73982. ** Generate a human-readable explanation of an expression tree.
  73983. */
  73984. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
  73985. int op; /* The opcode being coded */
  73986. const char *zBinOp = 0; /* Binary operator */
  73987. const char *zUniOp = 0; /* Unary operator */
  73988. if( pExpr==0 ){
  73989. op = TK_NULL;
  73990. }else{
  73991. op = pExpr->op;
  73992. }
  73993. switch( op ){
  73994. case TK_AGG_COLUMN: {
  73995. sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
  73996. pExpr->iTable, pExpr->iColumn);
  73997. break;
  73998. }
  73999. case TK_COLUMN: {
  74000. if( pExpr->iTable<0 ){
  74001. /* This only happens when coding check constraints */
  74002. sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
  74003. }else{
  74004. sqlite3ExplainPrintf(pOut, "{%d:%d}",
  74005. pExpr->iTable, pExpr->iColumn);
  74006. }
  74007. break;
  74008. }
  74009. case TK_INTEGER: {
  74010. if( pExpr->flags & EP_IntValue ){
  74011. sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
  74012. }else{
  74013. sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
  74014. }
  74015. break;
  74016. }
  74017. #ifndef SQLITE_OMIT_FLOATING_POINT
  74018. case TK_FLOAT: {
  74019. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  74020. break;
  74021. }
  74022. #endif
  74023. case TK_STRING: {
  74024. sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
  74025. break;
  74026. }
  74027. case TK_NULL: {
  74028. sqlite3ExplainPrintf(pOut,"NULL");
  74029. break;
  74030. }
  74031. #ifndef SQLITE_OMIT_BLOB_LITERAL
  74032. case TK_BLOB: {
  74033. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  74034. break;
  74035. }
  74036. #endif
  74037. case TK_VARIABLE: {
  74038. sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
  74039. pExpr->u.zToken, pExpr->iColumn);
  74040. break;
  74041. }
  74042. case TK_REGISTER: {
  74043. sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
  74044. break;
  74045. }
  74046. case TK_AS: {
  74047. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  74048. break;
  74049. }
  74050. #ifndef SQLITE_OMIT_CAST
  74051. case TK_CAST: {
  74052. /* Expressions of the form: CAST(pLeft AS token) */
  74053. const char *zAff = "unk";
  74054. switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
  74055. case SQLITE_AFF_TEXT: zAff = "TEXT"; break;
  74056. case SQLITE_AFF_NONE: zAff = "NONE"; break;
  74057. case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break;
  74058. case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break;
  74059. case SQLITE_AFF_REAL: zAff = "REAL"; break;
  74060. }
  74061. sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
  74062. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  74063. sqlite3ExplainPrintf(pOut, ")");
  74064. break;
  74065. }
  74066. #endif /* SQLITE_OMIT_CAST */
  74067. case TK_LT: zBinOp = "LT"; break;
  74068. case TK_LE: zBinOp = "LE"; break;
  74069. case TK_GT: zBinOp = "GT"; break;
  74070. case TK_GE: zBinOp = "GE"; break;
  74071. case TK_NE: zBinOp = "NE"; break;
  74072. case TK_EQ: zBinOp = "EQ"; break;
  74073. case TK_IS: zBinOp = "IS"; break;
  74074. case TK_ISNOT: zBinOp = "ISNOT"; break;
  74075. case TK_AND: zBinOp = "AND"; break;
  74076. case TK_OR: zBinOp = "OR"; break;
  74077. case TK_PLUS: zBinOp = "ADD"; break;
  74078. case TK_STAR: zBinOp = "MUL"; break;
  74079. case TK_MINUS: zBinOp = "SUB"; break;
  74080. case TK_REM: zBinOp = "REM"; break;
  74081. case TK_BITAND: zBinOp = "BITAND"; break;
  74082. case TK_BITOR: zBinOp = "BITOR"; break;
  74083. case TK_SLASH: zBinOp = "DIV"; break;
  74084. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  74085. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  74086. case TK_CONCAT: zBinOp = "CONCAT"; break;
  74087. case TK_UMINUS: zUniOp = "UMINUS"; break;
  74088. case TK_UPLUS: zUniOp = "UPLUS"; break;
  74089. case TK_BITNOT: zUniOp = "BITNOT"; break;
  74090. case TK_NOT: zUniOp = "NOT"; break;
  74091. case TK_ISNULL: zUniOp = "ISNULL"; break;
  74092. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  74093. case TK_COLLATE: {
  74094. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  74095. sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
  74096. break;
  74097. }
  74098. case TK_AGG_FUNCTION:
  74099. case TK_CONST_FUNC:
  74100. case TK_FUNCTION: {
  74101. ExprList *pFarg; /* List of function arguments */
  74102. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  74103. pFarg = 0;
  74104. }else{
  74105. pFarg = pExpr->x.pList;
  74106. }
  74107. if( op==TK_AGG_FUNCTION ){
  74108. sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
  74109. pExpr->op2, pExpr->u.zToken);
  74110. }else{
  74111. sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
  74112. }
  74113. if( pFarg ){
  74114. sqlite3ExplainExprList(pOut, pFarg);
  74115. }
  74116. sqlite3ExplainPrintf(pOut, ")");
  74117. break;
  74118. }
  74119. #ifndef SQLITE_OMIT_SUBQUERY
  74120. case TK_EXISTS: {
  74121. sqlite3ExplainPrintf(pOut, "EXISTS(");
  74122. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  74123. sqlite3ExplainPrintf(pOut,")");
  74124. break;
  74125. }
  74126. case TK_SELECT: {
  74127. sqlite3ExplainPrintf(pOut, "(");
  74128. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  74129. sqlite3ExplainPrintf(pOut, ")");
  74130. break;
  74131. }
  74132. case TK_IN: {
  74133. sqlite3ExplainPrintf(pOut, "IN(");
  74134. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  74135. sqlite3ExplainPrintf(pOut, ",");
  74136. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  74137. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  74138. }else{
  74139. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  74140. }
  74141. sqlite3ExplainPrintf(pOut, ")");
  74142. break;
  74143. }
  74144. #endif /* SQLITE_OMIT_SUBQUERY */
  74145. /*
  74146. ** x BETWEEN y AND z
  74147. **
  74148. ** This is equivalent to
  74149. **
  74150. ** x>=y AND x<=z
  74151. **
  74152. ** X is stored in pExpr->pLeft.
  74153. ** Y is stored in pExpr->pList->a[0].pExpr.
  74154. ** Z is stored in pExpr->pList->a[1].pExpr.
  74155. */
  74156. case TK_BETWEEN: {
  74157. Expr *pX = pExpr->pLeft;
  74158. Expr *pY = pExpr->x.pList->a[0].pExpr;
  74159. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  74160. sqlite3ExplainPrintf(pOut, "BETWEEN(");
  74161. sqlite3ExplainExpr(pOut, pX);
  74162. sqlite3ExplainPrintf(pOut, ",");
  74163. sqlite3ExplainExpr(pOut, pY);
  74164. sqlite3ExplainPrintf(pOut, ",");
  74165. sqlite3ExplainExpr(pOut, pZ);
  74166. sqlite3ExplainPrintf(pOut, ")");
  74167. break;
  74168. }
  74169. case TK_TRIGGER: {
  74170. /* If the opcode is TK_TRIGGER, then the expression is a reference
  74171. ** to a column in the new.* or old.* pseudo-tables available to
  74172. ** trigger programs. In this case Expr.iTable is set to 1 for the
  74173. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  74174. ** is set to the column of the pseudo-table to read, or to -1 to
  74175. ** read the rowid field.
  74176. */
  74177. sqlite3ExplainPrintf(pOut, "%s(%d)",
  74178. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  74179. break;
  74180. }
  74181. case TK_CASE: {
  74182. sqlite3ExplainPrintf(pOut, "CASE(");
  74183. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  74184. sqlite3ExplainPrintf(pOut, ",");
  74185. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  74186. break;
  74187. }
  74188. #ifndef SQLITE_OMIT_TRIGGER
  74189. case TK_RAISE: {
  74190. const char *zType = "unk";
  74191. switch( pExpr->affinity ){
  74192. case OE_Rollback: zType = "rollback"; break;
  74193. case OE_Abort: zType = "abort"; break;
  74194. case OE_Fail: zType = "fail"; break;
  74195. case OE_Ignore: zType = "ignore"; break;
  74196. }
  74197. sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
  74198. break;
  74199. }
  74200. #endif
  74201. }
  74202. if( zBinOp ){
  74203. sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
  74204. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  74205. sqlite3ExplainPrintf(pOut,",");
  74206. sqlite3ExplainExpr(pOut, pExpr->pRight);
  74207. sqlite3ExplainPrintf(pOut,")");
  74208. }else if( zUniOp ){
  74209. sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
  74210. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  74211. sqlite3ExplainPrintf(pOut,")");
  74212. }
  74213. }
  74214. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  74215. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  74216. /*
  74217. ** Generate a human-readable explanation of an expression list.
  74218. */
  74219. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
  74220. int i;
  74221. if( pList==0 || pList->nExpr==0 ){
  74222. sqlite3ExplainPrintf(pOut, "(empty-list)");
  74223. return;
  74224. }else if( pList->nExpr==1 ){
  74225. sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
  74226. }else{
  74227. sqlite3ExplainPush(pOut);
  74228. for(i=0; i<pList->nExpr; i++){
  74229. sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
  74230. sqlite3ExplainPush(pOut);
  74231. sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
  74232. sqlite3ExplainPop(pOut);
  74233. if( pList->a[i].zName ){
  74234. sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
  74235. }
  74236. if( pList->a[i].bSpanIsTab ){
  74237. sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
  74238. }
  74239. if( i<pList->nExpr-1 ){
  74240. sqlite3ExplainNL(pOut);
  74241. }
  74242. }
  74243. sqlite3ExplainPop(pOut);
  74244. }
  74245. }
  74246. #endif /* SQLITE_DEBUG */
  74247. /*
  74248. ** Return TRUE if pExpr is an constant expression that is appropriate
  74249. ** for factoring out of a loop. Appropriate expressions are:
  74250. **
  74251. ** * Any expression that evaluates to two or more opcodes.
  74252. **
  74253. ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
  74254. ** or OP_Variable that does not need to be placed in a
  74255. ** specific register.
  74256. **
  74257. ** There is no point in factoring out single-instruction constant
  74258. ** expressions that need to be placed in a particular register.
  74259. ** We could factor them out, but then we would end up adding an
  74260. ** OP_SCopy instruction to move the value into the correct register
  74261. ** later. We might as well just use the original instruction and
  74262. ** avoid the OP_SCopy.
  74263. */
  74264. static int isAppropriateForFactoring(Expr *p){
  74265. if( !sqlite3ExprIsConstantNotJoin(p) ){
  74266. return 0; /* Only constant expressions are appropriate for factoring */
  74267. }
  74268. if( (p->flags & EP_FixedDest)==0 ){
  74269. return 1; /* Any constant without a fixed destination is appropriate */
  74270. }
  74271. while( p->op==TK_UPLUS ) p = p->pLeft;
  74272. switch( p->op ){
  74273. #ifndef SQLITE_OMIT_BLOB_LITERAL
  74274. case TK_BLOB:
  74275. #endif
  74276. case TK_VARIABLE:
  74277. case TK_INTEGER:
  74278. case TK_FLOAT:
  74279. case TK_NULL:
  74280. case TK_STRING: {
  74281. testcase( p->op==TK_BLOB );
  74282. testcase( p->op==TK_VARIABLE );
  74283. testcase( p->op==TK_INTEGER );
  74284. testcase( p->op==TK_FLOAT );
  74285. testcase( p->op==TK_NULL );
  74286. testcase( p->op==TK_STRING );
  74287. /* Single-instruction constants with a fixed destination are
  74288. ** better done in-line. If we factor them, they will just end
  74289. ** up generating an OP_SCopy to move the value to the destination
  74290. ** register. */
  74291. return 0;
  74292. }
  74293. case TK_UMINUS: {
  74294. if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  74295. return 0;
  74296. }
  74297. break;
  74298. }
  74299. default: {
  74300. break;
  74301. }
  74302. }
  74303. return 1;
  74304. }
  74305. /*
  74306. ** If pExpr is a constant expression that is appropriate for
  74307. ** factoring out of a loop, then evaluate the expression
  74308. ** into a register and convert the expression into a TK_REGISTER
  74309. ** expression.
  74310. */
  74311. static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  74312. Parse *pParse = pWalker->pParse;
  74313. switch( pExpr->op ){
  74314. case TK_IN:
  74315. case TK_REGISTER: {
  74316. return WRC_Prune;
  74317. }
  74318. case TK_COLLATE: {
  74319. return WRC_Continue;
  74320. }
  74321. case TK_FUNCTION:
  74322. case TK_AGG_FUNCTION:
  74323. case TK_CONST_FUNC: {
  74324. /* The arguments to a function have a fixed destination.
  74325. ** Mark them this way to avoid generated unneeded OP_SCopy
  74326. ** instructions.
  74327. */
  74328. ExprList *pList = pExpr->x.pList;
  74329. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  74330. if( pList ){
  74331. int i = pList->nExpr;
  74332. struct ExprList_item *pItem = pList->a;
  74333. for(; i>0; i--, pItem++){
  74334. if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
  74335. }
  74336. }
  74337. break;
  74338. }
  74339. }
  74340. if( isAppropriateForFactoring(pExpr) ){
  74341. int r1 = ++pParse->nMem;
  74342. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  74343. /* If r2!=r1, it means that register r1 is never used. That is harmless
  74344. ** but suboptimal, so we want to know about the situation to fix it.
  74345. ** Hence the following assert: */
  74346. assert( r2==r1 );
  74347. exprToRegister(pExpr, r2);
  74348. return WRC_Prune;
  74349. }
  74350. return WRC_Continue;
  74351. }
  74352. /*
  74353. ** Preevaluate constant subexpressions within pExpr and store the
  74354. ** results in registers. Modify pExpr so that the constant subexpresions
  74355. ** are TK_REGISTER opcodes that refer to the precomputed values.
  74356. **
  74357. ** This routine is a no-op if the jump to the cookie-check code has
  74358. ** already occur. Since the cookie-check jump is generated prior to
  74359. ** any other serious processing, this check ensures that there is no
  74360. ** way to accidently bypass the constant initializations.
  74361. **
  74362. ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
  74363. ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
  74364. ** interface. This allows test logic to verify that the same answer is
  74365. ** obtained for queries regardless of whether or not constants are
  74366. ** precomputed into registers or if they are inserted in-line.
  74367. */
  74368. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  74369. Walker w;
  74370. if( pParse->cookieGoto ) return;
  74371. if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
  74372. memset(&w, 0, sizeof(w));
  74373. w.xExprCallback = evalConstExpr;
  74374. w.pParse = pParse;
  74375. sqlite3WalkExpr(&w, pExpr);
  74376. }
  74377. /*
  74378. ** Generate code that pushes the value of every element of the given
  74379. ** expression list into a sequence of registers beginning at target.
  74380. **
  74381. ** Return the number of elements evaluated.
  74382. */
  74383. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  74384. Parse *pParse, /* Parsing context */
  74385. ExprList *pList, /* The expression list to be coded */
  74386. int target, /* Where to write results */
  74387. int doHardCopy /* Make a hard copy of every element */
  74388. ){
  74389. struct ExprList_item *pItem;
  74390. int i, n;
  74391. assert( pList!=0 );
  74392. assert( target>0 );
  74393. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  74394. n = pList->nExpr;
  74395. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  74396. Expr *pExpr = pItem->pExpr;
  74397. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  74398. if( inReg!=target+i ){
  74399. sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
  74400. inReg, target+i);
  74401. }
  74402. }
  74403. return n;
  74404. }
  74405. /*
  74406. ** Generate code for a BETWEEN operator.
  74407. **
  74408. ** x BETWEEN y AND z
  74409. **
  74410. ** The above is equivalent to
  74411. **
  74412. ** x>=y AND x<=z
  74413. **
  74414. ** Code it as such, taking care to do the common subexpression
  74415. ** elementation of x.
  74416. */
  74417. static void exprCodeBetween(
  74418. Parse *pParse, /* Parsing and code generating context */
  74419. Expr *pExpr, /* The BETWEEN expression */
  74420. int dest, /* Jump here if the jump is taken */
  74421. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  74422. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  74423. ){
  74424. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  74425. Expr compLeft; /* The x>=y term */
  74426. Expr compRight; /* The x<=z term */
  74427. Expr exprX; /* The x subexpression */
  74428. int regFree1 = 0; /* Temporary use register */
  74429. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  74430. exprX = *pExpr->pLeft;
  74431. exprAnd.op = TK_AND;
  74432. exprAnd.pLeft = &compLeft;
  74433. exprAnd.pRight = &compRight;
  74434. compLeft.op = TK_GE;
  74435. compLeft.pLeft = &exprX;
  74436. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  74437. compRight.op = TK_LE;
  74438. compRight.pLeft = &exprX;
  74439. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  74440. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  74441. if( jumpIfTrue ){
  74442. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  74443. }else{
  74444. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  74445. }
  74446. sqlite3ReleaseTempReg(pParse, regFree1);
  74447. /* Ensure adequate test coverage */
  74448. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  74449. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  74450. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  74451. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  74452. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  74453. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  74454. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  74455. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  74456. }
  74457. /*
  74458. ** Generate code for a boolean expression such that a jump is made
  74459. ** to the label "dest" if the expression is true but execution
  74460. ** continues straight thru if the expression is false.
  74461. **
  74462. ** If the expression evaluates to NULL (neither true nor false), then
  74463. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  74464. **
  74465. ** This code depends on the fact that certain token values (ex: TK_EQ)
  74466. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  74467. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  74468. ** the make process cause these values to align. Assert()s in the code
  74469. ** below verify that the numbers are aligned correctly.
  74470. */
  74471. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  74472. Vdbe *v = pParse->pVdbe;
  74473. int op = 0;
  74474. int regFree1 = 0;
  74475. int regFree2 = 0;
  74476. int r1, r2;
  74477. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  74478. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  74479. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  74480. op = pExpr->op;
  74481. switch( op ){
  74482. case TK_AND: {
  74483. int d2 = sqlite3VdbeMakeLabel(v);
  74484. testcase( jumpIfNull==0 );
  74485. sqlite3ExprCachePush(pParse);
  74486. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  74487. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  74488. sqlite3VdbeResolveLabel(v, d2);
  74489. sqlite3ExprCachePop(pParse, 1);
  74490. break;
  74491. }
  74492. case TK_OR: {
  74493. testcase( jumpIfNull==0 );
  74494. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  74495. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  74496. break;
  74497. }
  74498. case TK_NOT: {
  74499. testcase( jumpIfNull==0 );
  74500. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  74501. break;
  74502. }
  74503. case TK_LT:
  74504. case TK_LE:
  74505. case TK_GT:
  74506. case TK_GE:
  74507. case TK_NE:
  74508. case TK_EQ: {
  74509. assert( TK_LT==OP_Lt );
  74510. assert( TK_LE==OP_Le );
  74511. assert( TK_GT==OP_Gt );
  74512. assert( TK_GE==OP_Ge );
  74513. assert( TK_EQ==OP_Eq );
  74514. assert( TK_NE==OP_Ne );
  74515. testcase( op==TK_LT );
  74516. testcase( op==TK_LE );
  74517. testcase( op==TK_GT );
  74518. testcase( op==TK_GE );
  74519. testcase( op==TK_EQ );
  74520. testcase( op==TK_NE );
  74521. testcase( jumpIfNull==0 );
  74522. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  74523. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  74524. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  74525. r1, r2, dest, jumpIfNull);
  74526. testcase( regFree1==0 );
  74527. testcase( regFree2==0 );
  74528. break;
  74529. }
  74530. case TK_IS:
  74531. case TK_ISNOT: {
  74532. testcase( op==TK_IS );
  74533. testcase( op==TK_ISNOT );
  74534. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  74535. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  74536. op = (op==TK_IS) ? TK_EQ : TK_NE;
  74537. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  74538. r1, r2, dest, SQLITE_NULLEQ);
  74539. testcase( regFree1==0 );
  74540. testcase( regFree2==0 );
  74541. break;
  74542. }
  74543. case TK_ISNULL:
  74544. case TK_NOTNULL: {
  74545. assert( TK_ISNULL==OP_IsNull );
  74546. assert( TK_NOTNULL==OP_NotNull );
  74547. testcase( op==TK_ISNULL );
  74548. testcase( op==TK_NOTNULL );
  74549. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  74550. sqlite3VdbeAddOp2(v, op, r1, dest);
  74551. testcase( regFree1==0 );
  74552. break;
  74553. }
  74554. case TK_BETWEEN: {
  74555. testcase( jumpIfNull==0 );
  74556. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  74557. break;
  74558. }
  74559. #ifndef SQLITE_OMIT_SUBQUERY
  74560. case TK_IN: {
  74561. int destIfFalse = sqlite3VdbeMakeLabel(v);
  74562. int destIfNull = jumpIfNull ? dest : destIfFalse;
  74563. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  74564. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  74565. sqlite3VdbeResolveLabel(v, destIfFalse);
  74566. break;
  74567. }
  74568. #endif
  74569. default: {
  74570. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  74571. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  74572. testcase( regFree1==0 );
  74573. testcase( jumpIfNull==0 );
  74574. break;
  74575. }
  74576. }
  74577. sqlite3ReleaseTempReg(pParse, regFree1);
  74578. sqlite3ReleaseTempReg(pParse, regFree2);
  74579. }
  74580. /*
  74581. ** Generate code for a boolean expression such that a jump is made
  74582. ** to the label "dest" if the expression is false but execution
  74583. ** continues straight thru if the expression is true.
  74584. **
  74585. ** If the expression evaluates to NULL (neither true nor false) then
  74586. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  74587. ** is 0.
  74588. */
  74589. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  74590. Vdbe *v = pParse->pVdbe;
  74591. int op = 0;
  74592. int regFree1 = 0;
  74593. int regFree2 = 0;
  74594. int r1, r2;
  74595. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  74596. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  74597. if( pExpr==0 ) return;
  74598. /* The value of pExpr->op and op are related as follows:
  74599. **
  74600. ** pExpr->op op
  74601. ** --------- ----------
  74602. ** TK_ISNULL OP_NotNull
  74603. ** TK_NOTNULL OP_IsNull
  74604. ** TK_NE OP_Eq
  74605. ** TK_EQ OP_Ne
  74606. ** TK_GT OP_Le
  74607. ** TK_LE OP_Gt
  74608. ** TK_GE OP_Lt
  74609. ** TK_LT OP_Ge
  74610. **
  74611. ** For other values of pExpr->op, op is undefined and unused.
  74612. ** The value of TK_ and OP_ constants are arranged such that we
  74613. ** can compute the mapping above using the following expression.
  74614. ** Assert()s verify that the computation is correct.
  74615. */
  74616. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  74617. /* Verify correct alignment of TK_ and OP_ constants
  74618. */
  74619. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  74620. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  74621. assert( pExpr->op!=TK_NE || op==OP_Eq );
  74622. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  74623. assert( pExpr->op!=TK_LT || op==OP_Ge );
  74624. assert( pExpr->op!=TK_LE || op==OP_Gt );
  74625. assert( pExpr->op!=TK_GT || op==OP_Le );
  74626. assert( pExpr->op!=TK_GE || op==OP_Lt );
  74627. switch( pExpr->op ){
  74628. case TK_AND: {
  74629. testcase( jumpIfNull==0 );
  74630. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  74631. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  74632. break;
  74633. }
  74634. case TK_OR: {
  74635. int d2 = sqlite3VdbeMakeLabel(v);
  74636. testcase( jumpIfNull==0 );
  74637. sqlite3ExprCachePush(pParse);
  74638. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  74639. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  74640. sqlite3VdbeResolveLabel(v, d2);
  74641. sqlite3ExprCachePop(pParse, 1);
  74642. break;
  74643. }
  74644. case TK_NOT: {
  74645. testcase( jumpIfNull==0 );
  74646. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  74647. break;
  74648. }
  74649. case TK_LT:
  74650. case TK_LE:
  74651. case TK_GT:
  74652. case TK_GE:
  74653. case TK_NE:
  74654. case TK_EQ: {
  74655. testcase( op==TK_LT );
  74656. testcase( op==TK_LE );
  74657. testcase( op==TK_GT );
  74658. testcase( op==TK_GE );
  74659. testcase( op==TK_EQ );
  74660. testcase( op==TK_NE );
  74661. testcase( jumpIfNull==0 );
  74662. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  74663. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  74664. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  74665. r1, r2, dest, jumpIfNull);
  74666. testcase( regFree1==0 );
  74667. testcase( regFree2==0 );
  74668. break;
  74669. }
  74670. case TK_IS:
  74671. case TK_ISNOT: {
  74672. testcase( pExpr->op==TK_IS );
  74673. testcase( pExpr->op==TK_ISNOT );
  74674. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  74675. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  74676. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  74677. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  74678. r1, r2, dest, SQLITE_NULLEQ);
  74679. testcase( regFree1==0 );
  74680. testcase( regFree2==0 );
  74681. break;
  74682. }
  74683. case TK_ISNULL:
  74684. case TK_NOTNULL: {
  74685. testcase( op==TK_ISNULL );
  74686. testcase( op==TK_NOTNULL );
  74687. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  74688. sqlite3VdbeAddOp2(v, op, r1, dest);
  74689. testcase( regFree1==0 );
  74690. break;
  74691. }
  74692. case TK_BETWEEN: {
  74693. testcase( jumpIfNull==0 );
  74694. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  74695. break;
  74696. }
  74697. #ifndef SQLITE_OMIT_SUBQUERY
  74698. case TK_IN: {
  74699. if( jumpIfNull ){
  74700. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  74701. }else{
  74702. int destIfNull = sqlite3VdbeMakeLabel(v);
  74703. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  74704. sqlite3VdbeResolveLabel(v, destIfNull);
  74705. }
  74706. break;
  74707. }
  74708. #endif
  74709. default: {
  74710. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  74711. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  74712. testcase( regFree1==0 );
  74713. testcase( jumpIfNull==0 );
  74714. break;
  74715. }
  74716. }
  74717. sqlite3ReleaseTempReg(pParse, regFree1);
  74718. sqlite3ReleaseTempReg(pParse, regFree2);
  74719. }
  74720. /*
  74721. ** Do a deep comparison of two expression trees. Return 0 if the two
  74722. ** expressions are completely identical. Return 1 if they differ only
  74723. ** by a COLLATE operator at the top level. Return 2 if there are differences
  74724. ** other than the top-level COLLATE operator.
  74725. **
  74726. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  74727. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  74728. **
  74729. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  74730. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  74731. **
  74732. ** Sometimes this routine will return 2 even if the two expressions
  74733. ** really are equivalent. If we cannot prove that the expressions are
  74734. ** identical, we return 2 just to be safe. So if this routine
  74735. ** returns 2, then you do not really know for certain if the two
  74736. ** expressions are the same. But if you get a 0 or 1 return, then you
  74737. ** can be sure the expressions are the same. In the places where
  74738. ** this routine is used, it does not hurt to get an extra 2 - that
  74739. ** just might result in some slightly slower code. But returning
  74740. ** an incorrect 0 or 1 could lead to a malfunction.
  74741. */
  74742. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  74743. if( pA==0||pB==0 ){
  74744. return pB==pA ? 0 : 2;
  74745. }
  74746. assert( !ExprHasProperty(pA, EP_TokenOnly|EP_Reduced) );
  74747. assert( !ExprHasProperty(pB, EP_TokenOnly|EP_Reduced) );
  74748. if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
  74749. return 2;
  74750. }
  74751. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  74752. if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){
  74753. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  74754. return 1;
  74755. }
  74756. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  74757. return 1;
  74758. }
  74759. return 2;
  74760. }
  74761. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  74762. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  74763. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  74764. if( pA->iColumn!=pB->iColumn ) return 2;
  74765. if( pA->iTable!=pB->iTable
  74766. && pA->op!=TK_REGISTER
  74767. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  74768. if( ExprHasProperty(pA, EP_IntValue) ){
  74769. if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
  74770. return 2;
  74771. }
  74772. }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
  74773. if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
  74774. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  74775. return pA->op==TK_COLLATE ? 1 : 2;
  74776. }
  74777. }
  74778. return 0;
  74779. }
  74780. /*
  74781. ** Compare two ExprList objects. Return 0 if they are identical and
  74782. ** non-zero if they differ in any way.
  74783. **
  74784. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  74785. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  74786. **
  74787. ** This routine might return non-zero for equivalent ExprLists. The
  74788. ** only consequence will be disabled optimizations. But this routine
  74789. ** must never return 0 if the two ExprList objects are different, or
  74790. ** a malfunction will result.
  74791. **
  74792. ** Two NULL pointers are considered to be the same. But a NULL pointer
  74793. ** always differs from a non-NULL pointer.
  74794. */
  74795. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  74796. int i;
  74797. if( pA==0 && pB==0 ) return 0;
  74798. if( pA==0 || pB==0 ) return 1;
  74799. if( pA->nExpr!=pB->nExpr ) return 1;
  74800. for(i=0; i<pA->nExpr; i++){
  74801. Expr *pExprA = pA->a[i].pExpr;
  74802. Expr *pExprB = pB->a[i].pExpr;
  74803. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  74804. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  74805. }
  74806. return 0;
  74807. }
  74808. /*
  74809. ** Return true if we can prove the pE2 will always be true if pE1 is
  74810. ** true. Return false if we cannot complete the proof or if pE2 might
  74811. ** be false. Examples:
  74812. **
  74813. ** pE1: x==5 pE2: x==5 Result: true
  74814. ** pE1: x>0 pE2: x==5 Result: false
  74815. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  74816. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  74817. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  74818. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  74819. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  74820. **
  74821. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  74822. ** Expr.iTable<0 then assume a table number given by iTab.
  74823. **
  74824. ** When in doubt, return false. Returning true might give a performance
  74825. ** improvement. Returning false might cause a performance reduction, but
  74826. ** it will always give the correct answer and is hence always safe.
  74827. */
  74828. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  74829. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  74830. return 1;
  74831. }
  74832. if( pE2->op==TK_OR
  74833. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  74834. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  74835. ){
  74836. return 1;
  74837. }
  74838. if( pE2->op==TK_NOTNULL
  74839. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  74840. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  74841. ){
  74842. return 1;
  74843. }
  74844. return 0;
  74845. }
  74846. /*
  74847. ** An instance of the following structure is used by the tree walker
  74848. ** to count references to table columns in the arguments of an
  74849. ** aggregate function, in order to implement the
  74850. ** sqlite3FunctionThisSrc() routine.
  74851. */
  74852. struct SrcCount {
  74853. SrcList *pSrc; /* One particular FROM clause in a nested query */
  74854. int nThis; /* Number of references to columns in pSrcList */
  74855. int nOther; /* Number of references to columns in other FROM clauses */
  74856. };
  74857. /*
  74858. ** Count the number of references to columns.
  74859. */
  74860. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  74861. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  74862. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  74863. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  74864. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  74865. ** NEVER() will need to be removed. */
  74866. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  74867. int i;
  74868. struct SrcCount *p = pWalker->u.pSrcCount;
  74869. SrcList *pSrc = p->pSrc;
  74870. for(i=0; i<pSrc->nSrc; i++){
  74871. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  74872. }
  74873. if( i<pSrc->nSrc ){
  74874. p->nThis++;
  74875. }else{
  74876. p->nOther++;
  74877. }
  74878. }
  74879. return WRC_Continue;
  74880. }
  74881. /*
  74882. ** Determine if any of the arguments to the pExpr Function reference
  74883. ** pSrcList. Return true if they do. Also return true if the function
  74884. ** has no arguments or has only constant arguments. Return false if pExpr
  74885. ** references columns but not columns of tables found in pSrcList.
  74886. */
  74887. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  74888. Walker w;
  74889. struct SrcCount cnt;
  74890. assert( pExpr->op==TK_AGG_FUNCTION );
  74891. memset(&w, 0, sizeof(w));
  74892. w.xExprCallback = exprSrcCount;
  74893. w.u.pSrcCount = &cnt;
  74894. cnt.pSrc = pSrcList;
  74895. cnt.nThis = 0;
  74896. cnt.nOther = 0;
  74897. sqlite3WalkExprList(&w, pExpr->x.pList);
  74898. return cnt.nThis>0 || cnt.nOther==0;
  74899. }
  74900. /*
  74901. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  74902. ** the new element. Return a negative number if malloc fails.
  74903. */
  74904. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  74905. int i;
  74906. pInfo->aCol = sqlite3ArrayAllocate(
  74907. db,
  74908. pInfo->aCol,
  74909. sizeof(pInfo->aCol[0]),
  74910. &pInfo->nColumn,
  74911. &i
  74912. );
  74913. return i;
  74914. }
  74915. /*
  74916. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  74917. ** the new element. Return a negative number if malloc fails.
  74918. */
  74919. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  74920. int i;
  74921. pInfo->aFunc = sqlite3ArrayAllocate(
  74922. db,
  74923. pInfo->aFunc,
  74924. sizeof(pInfo->aFunc[0]),
  74925. &pInfo->nFunc,
  74926. &i
  74927. );
  74928. return i;
  74929. }
  74930. /*
  74931. ** This is the xExprCallback for a tree walker. It is used to
  74932. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  74933. ** for additional information.
  74934. */
  74935. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  74936. int i;
  74937. NameContext *pNC = pWalker->u.pNC;
  74938. Parse *pParse = pNC->pParse;
  74939. SrcList *pSrcList = pNC->pSrcList;
  74940. AggInfo *pAggInfo = pNC->pAggInfo;
  74941. switch( pExpr->op ){
  74942. case TK_AGG_COLUMN:
  74943. case TK_COLUMN: {
  74944. testcase( pExpr->op==TK_AGG_COLUMN );
  74945. testcase( pExpr->op==TK_COLUMN );
  74946. /* Check to see if the column is in one of the tables in the FROM
  74947. ** clause of the aggregate query */
  74948. if( ALWAYS(pSrcList!=0) ){
  74949. struct SrcList_item *pItem = pSrcList->a;
  74950. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  74951. struct AggInfo_col *pCol;
  74952. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  74953. if( pExpr->iTable==pItem->iCursor ){
  74954. /* If we reach this point, it means that pExpr refers to a table
  74955. ** that is in the FROM clause of the aggregate query.
  74956. **
  74957. ** Make an entry for the column in pAggInfo->aCol[] if there
  74958. ** is not an entry there already.
  74959. */
  74960. int k;
  74961. pCol = pAggInfo->aCol;
  74962. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  74963. if( pCol->iTable==pExpr->iTable &&
  74964. pCol->iColumn==pExpr->iColumn ){
  74965. break;
  74966. }
  74967. }
  74968. if( (k>=pAggInfo->nColumn)
  74969. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  74970. ){
  74971. pCol = &pAggInfo->aCol[k];
  74972. pCol->pTab = pExpr->pTab;
  74973. pCol->iTable = pExpr->iTable;
  74974. pCol->iColumn = pExpr->iColumn;
  74975. pCol->iMem = ++pParse->nMem;
  74976. pCol->iSorterColumn = -1;
  74977. pCol->pExpr = pExpr;
  74978. if( pAggInfo->pGroupBy ){
  74979. int j, n;
  74980. ExprList *pGB = pAggInfo->pGroupBy;
  74981. struct ExprList_item *pTerm = pGB->a;
  74982. n = pGB->nExpr;
  74983. for(j=0; j<n; j++, pTerm++){
  74984. Expr *pE = pTerm->pExpr;
  74985. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  74986. pE->iColumn==pExpr->iColumn ){
  74987. pCol->iSorterColumn = j;
  74988. break;
  74989. }
  74990. }
  74991. }
  74992. if( pCol->iSorterColumn<0 ){
  74993. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  74994. }
  74995. }
  74996. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  74997. ** because it was there before or because we just created it).
  74998. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  74999. ** pAggInfo->aCol[] entry.
  75000. */
  75001. ExprSetVVAProperty(pExpr, EP_NoReduce);
  75002. pExpr->pAggInfo = pAggInfo;
  75003. pExpr->op = TK_AGG_COLUMN;
  75004. pExpr->iAgg = (i16)k;
  75005. break;
  75006. } /* endif pExpr->iTable==pItem->iCursor */
  75007. } /* end loop over pSrcList */
  75008. }
  75009. return WRC_Prune;
  75010. }
  75011. case TK_AGG_FUNCTION: {
  75012. if( (pNC->ncFlags & NC_InAggFunc)==0
  75013. && pWalker->walkerDepth==pExpr->op2
  75014. ){
  75015. /* Check to see if pExpr is a duplicate of another aggregate
  75016. ** function that is already in the pAggInfo structure
  75017. */
  75018. struct AggInfo_func *pItem = pAggInfo->aFunc;
  75019. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  75020. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  75021. break;
  75022. }
  75023. }
  75024. if( i>=pAggInfo->nFunc ){
  75025. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  75026. */
  75027. u8 enc = ENC(pParse->db);
  75028. i = addAggInfoFunc(pParse->db, pAggInfo);
  75029. if( i>=0 ){
  75030. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  75031. pItem = &pAggInfo->aFunc[i];
  75032. pItem->pExpr = pExpr;
  75033. pItem->iMem = ++pParse->nMem;
  75034. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  75035. pItem->pFunc = sqlite3FindFunction(pParse->db,
  75036. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  75037. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  75038. if( pExpr->flags & EP_Distinct ){
  75039. pItem->iDistinct = pParse->nTab++;
  75040. }else{
  75041. pItem->iDistinct = -1;
  75042. }
  75043. }
  75044. }
  75045. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  75046. */
  75047. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  75048. ExprSetVVAProperty(pExpr, EP_NoReduce);
  75049. pExpr->iAgg = (i16)i;
  75050. pExpr->pAggInfo = pAggInfo;
  75051. return WRC_Prune;
  75052. }else{
  75053. return WRC_Continue;
  75054. }
  75055. }
  75056. }
  75057. return WRC_Continue;
  75058. }
  75059. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  75060. UNUSED_PARAMETER(pWalker);
  75061. UNUSED_PARAMETER(pSelect);
  75062. return WRC_Continue;
  75063. }
  75064. /*
  75065. ** Analyze the pExpr expression looking for aggregate functions and
  75066. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  75067. ** points to. Additional entries are made on the AggInfo object as
  75068. ** necessary.
  75069. **
  75070. ** This routine should only be called after the expression has been
  75071. ** analyzed by sqlite3ResolveExprNames().
  75072. */
  75073. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  75074. Walker w;
  75075. memset(&w, 0, sizeof(w));
  75076. w.xExprCallback = analyzeAggregate;
  75077. w.xSelectCallback = analyzeAggregatesInSelect;
  75078. w.u.pNC = pNC;
  75079. assert( pNC->pSrcList!=0 );
  75080. sqlite3WalkExpr(&w, pExpr);
  75081. }
  75082. /*
  75083. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  75084. ** expression list. Return the number of errors.
  75085. **
  75086. ** If an error is found, the analysis is cut short.
  75087. */
  75088. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  75089. struct ExprList_item *pItem;
  75090. int i;
  75091. if( pList ){
  75092. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  75093. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  75094. }
  75095. }
  75096. }
  75097. /*
  75098. ** Allocate a single new register for use to hold some intermediate result.
  75099. */
  75100. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  75101. if( pParse->nTempReg==0 ){
  75102. return ++pParse->nMem;
  75103. }
  75104. return pParse->aTempReg[--pParse->nTempReg];
  75105. }
  75106. /*
  75107. ** Deallocate a register, making available for reuse for some other
  75108. ** purpose.
  75109. **
  75110. ** If a register is currently being used by the column cache, then
  75111. ** the dallocation is deferred until the column cache line that uses
  75112. ** the register becomes stale.
  75113. */
  75114. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  75115. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  75116. int i;
  75117. struct yColCache *p;
  75118. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  75119. if( p->iReg==iReg ){
  75120. p->tempReg = 1;
  75121. return;
  75122. }
  75123. }
  75124. pParse->aTempReg[pParse->nTempReg++] = iReg;
  75125. }
  75126. }
  75127. /*
  75128. ** Allocate or deallocate a block of nReg consecutive registers
  75129. */
  75130. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  75131. int i, n;
  75132. i = pParse->iRangeReg;
  75133. n = pParse->nRangeReg;
  75134. if( nReg<=n ){
  75135. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  75136. pParse->iRangeReg += nReg;
  75137. pParse->nRangeReg -= nReg;
  75138. }else{
  75139. i = pParse->nMem+1;
  75140. pParse->nMem += nReg;
  75141. }
  75142. return i;
  75143. }
  75144. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  75145. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  75146. if( nReg>pParse->nRangeReg ){
  75147. pParse->nRangeReg = nReg;
  75148. pParse->iRangeReg = iReg;
  75149. }
  75150. }
  75151. /*
  75152. ** Mark all temporary registers as being unavailable for reuse.
  75153. */
  75154. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  75155. pParse->nTempReg = 0;
  75156. pParse->nRangeReg = 0;
  75157. }
  75158. /************** End of expr.c ************************************************/
  75159. /************** Begin file alter.c *******************************************/
  75160. /*
  75161. ** 2005 February 15
  75162. **
  75163. ** The author disclaims copyright to this source code. In place of
  75164. ** a legal notice, here is a blessing:
  75165. **
  75166. ** May you do good and not evil.
  75167. ** May you find forgiveness for yourself and forgive others.
  75168. ** May you share freely, never taking more than you give.
  75169. **
  75170. *************************************************************************
  75171. ** This file contains C code routines that used to generate VDBE code
  75172. ** that implements the ALTER TABLE command.
  75173. */
  75174. /*
  75175. ** The code in this file only exists if we are not omitting the
  75176. ** ALTER TABLE logic from the build.
  75177. */
  75178. #ifndef SQLITE_OMIT_ALTERTABLE
  75179. /*
  75180. ** This function is used by SQL generated to implement the
  75181. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  75182. ** CREATE INDEX command. The second is a table name. The table name in
  75183. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  75184. ** argument and the result returned. Examples:
  75185. **
  75186. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  75187. ** -> 'CREATE TABLE def(a, b, c)'
  75188. **
  75189. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  75190. ** -> 'CREATE INDEX i ON def(a, b, c)'
  75191. */
  75192. static void renameTableFunc(
  75193. sqlite3_context *context,
  75194. int NotUsed,
  75195. sqlite3_value **argv
  75196. ){
  75197. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  75198. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  75199. int token;
  75200. Token tname;
  75201. unsigned char const *zCsr = zSql;
  75202. int len = 0;
  75203. char *zRet;
  75204. sqlite3 *db = sqlite3_context_db_handle(context);
  75205. UNUSED_PARAMETER(NotUsed);
  75206. /* The principle used to locate the table name in the CREATE TABLE
  75207. ** statement is that the table name is the first non-space token that
  75208. ** is immediately followed by a TK_LP or TK_USING token.
  75209. */
  75210. if( zSql ){
  75211. do {
  75212. if( !*zCsr ){
  75213. /* Ran out of input before finding an opening bracket. Return NULL. */
  75214. return;
  75215. }
  75216. /* Store the token that zCsr points to in tname. */
  75217. tname.z = (char*)zCsr;
  75218. tname.n = len;
  75219. /* Advance zCsr to the next token. Store that token type in 'token',
  75220. ** and its length in 'len' (to be used next iteration of this loop).
  75221. */
  75222. do {
  75223. zCsr += len;
  75224. len = sqlite3GetToken(zCsr, &token);
  75225. } while( token==TK_SPACE );
  75226. assert( len>0 );
  75227. } while( token!=TK_LP && token!=TK_USING );
  75228. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  75229. zTableName, tname.z+tname.n);
  75230. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  75231. }
  75232. }
  75233. /*
  75234. ** This C function implements an SQL user function that is used by SQL code
  75235. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  75236. ** of any foreign key constraints that use the table being renamed as the
  75237. ** parent table. It is passed three arguments:
  75238. **
  75239. ** 1) The complete text of the CREATE TABLE statement being modified,
  75240. ** 2) The old name of the table being renamed, and
  75241. ** 3) The new name of the table being renamed.
  75242. **
  75243. ** It returns the new CREATE TABLE statement. For example:
  75244. **
  75245. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  75246. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  75247. */
  75248. #ifndef SQLITE_OMIT_FOREIGN_KEY
  75249. static void renameParentFunc(
  75250. sqlite3_context *context,
  75251. int NotUsed,
  75252. sqlite3_value **argv
  75253. ){
  75254. sqlite3 *db = sqlite3_context_db_handle(context);
  75255. char *zOutput = 0;
  75256. char *zResult;
  75257. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  75258. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  75259. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  75260. unsigned const char *z; /* Pointer to token */
  75261. int n; /* Length of token z */
  75262. int token; /* Type of token */
  75263. UNUSED_PARAMETER(NotUsed);
  75264. for(z=zInput; *z; z=z+n){
  75265. n = sqlite3GetToken(z, &token);
  75266. if( token==TK_REFERENCES ){
  75267. char *zParent;
  75268. do {
  75269. z += n;
  75270. n = sqlite3GetToken(z, &token);
  75271. }while( token==TK_SPACE );
  75272. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  75273. if( zParent==0 ) break;
  75274. sqlite3Dequote(zParent);
  75275. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  75276. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  75277. (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
  75278. );
  75279. sqlite3DbFree(db, zOutput);
  75280. zOutput = zOut;
  75281. zInput = &z[n];
  75282. }
  75283. sqlite3DbFree(db, zParent);
  75284. }
  75285. }
  75286. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  75287. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  75288. sqlite3DbFree(db, zOutput);
  75289. }
  75290. #endif
  75291. #ifndef SQLITE_OMIT_TRIGGER
  75292. /* This function is used by SQL generated to implement the
  75293. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  75294. ** statement. The second is a table name. The table name in the CREATE
  75295. ** TRIGGER statement is replaced with the third argument and the result
  75296. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  75297. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  75298. */
  75299. static void renameTriggerFunc(
  75300. sqlite3_context *context,
  75301. int NotUsed,
  75302. sqlite3_value **argv
  75303. ){
  75304. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  75305. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  75306. int token;
  75307. Token tname;
  75308. int dist = 3;
  75309. unsigned char const *zCsr = zSql;
  75310. int len = 0;
  75311. char *zRet;
  75312. sqlite3 *db = sqlite3_context_db_handle(context);
  75313. UNUSED_PARAMETER(NotUsed);
  75314. /* The principle used to locate the table name in the CREATE TRIGGER
  75315. ** statement is that the table name is the first token that is immediatedly
  75316. ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  75317. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  75318. */
  75319. if( zSql ){
  75320. do {
  75321. if( !*zCsr ){
  75322. /* Ran out of input before finding the table name. Return NULL. */
  75323. return;
  75324. }
  75325. /* Store the token that zCsr points to in tname. */
  75326. tname.z = (char*)zCsr;
  75327. tname.n = len;
  75328. /* Advance zCsr to the next token. Store that token type in 'token',
  75329. ** and its length in 'len' (to be used next iteration of this loop).
  75330. */
  75331. do {
  75332. zCsr += len;
  75333. len = sqlite3GetToken(zCsr, &token);
  75334. }while( token==TK_SPACE );
  75335. assert( len>0 );
  75336. /* Variable 'dist' stores the number of tokens read since the most
  75337. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  75338. ** token is read and 'dist' equals 2, the condition stated above
  75339. ** to be met.
  75340. **
  75341. ** Note that ON cannot be a database, table or column name, so
  75342. ** there is no need to worry about syntax like
  75343. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  75344. */
  75345. dist++;
  75346. if( token==TK_DOT || token==TK_ON ){
  75347. dist = 0;
  75348. }
  75349. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  75350. /* Variable tname now contains the token that is the old table-name
  75351. ** in the CREATE TRIGGER statement.
  75352. */
  75353. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  75354. zTableName, tname.z+tname.n);
  75355. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  75356. }
  75357. }
  75358. #endif /* !SQLITE_OMIT_TRIGGER */
  75359. /*
  75360. ** Register built-in functions used to help implement ALTER TABLE
  75361. */
  75362. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  75363. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  75364. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  75365. #ifndef SQLITE_OMIT_TRIGGER
  75366. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  75367. #endif
  75368. #ifndef SQLITE_OMIT_FOREIGN_KEY
  75369. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  75370. #endif
  75371. };
  75372. int i;
  75373. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  75374. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  75375. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  75376. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  75377. }
  75378. }
  75379. /*
  75380. ** This function is used to create the text of expressions of the form:
  75381. **
  75382. ** name=<constant1> OR name=<constant2> OR ...
  75383. **
  75384. ** If argument zWhere is NULL, then a pointer string containing the text
  75385. ** "name=<constant>" is returned, where <constant> is the quoted version
  75386. ** of the string passed as argument zConstant. The returned buffer is
  75387. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  75388. ** caller to ensure that it is eventually freed.
  75389. **
  75390. ** If argument zWhere is not NULL, then the string returned is
  75391. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  75392. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  75393. **
  75394. */
  75395. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  75396. char *zNew;
  75397. if( !zWhere ){
  75398. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  75399. }else{
  75400. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  75401. sqlite3DbFree(db, zWhere);
  75402. }
  75403. return zNew;
  75404. }
  75405. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  75406. /*
  75407. ** Generate the text of a WHERE expression which can be used to select all
  75408. ** tables that have foreign key constraints that refer to table pTab (i.e.
  75409. ** constraints for which pTab is the parent table) from the sqlite_master
  75410. ** table.
  75411. */
  75412. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  75413. FKey *p;
  75414. char *zWhere = 0;
  75415. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  75416. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  75417. }
  75418. return zWhere;
  75419. }
  75420. #endif
  75421. /*
  75422. ** Generate the text of a WHERE expression which can be used to select all
  75423. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  75424. ** table pTab has no temporary triggers, or is itself stored in the
  75425. ** temporary database, NULL is returned.
  75426. */
  75427. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  75428. Trigger *pTrig;
  75429. char *zWhere = 0;
  75430. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  75431. /* If the table is not located in the temp-db (in which case NULL is
  75432. ** returned, loop through the tables list of triggers. For each trigger
  75433. ** that is not part of the temp-db schema, add a clause to the WHERE
  75434. ** expression being built up in zWhere.
  75435. */
  75436. if( pTab->pSchema!=pTempSchema ){
  75437. sqlite3 *db = pParse->db;
  75438. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  75439. if( pTrig->pSchema==pTempSchema ){
  75440. zWhere = whereOrName(db, zWhere, pTrig->zName);
  75441. }
  75442. }
  75443. }
  75444. if( zWhere ){
  75445. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  75446. sqlite3DbFree(pParse->db, zWhere);
  75447. zWhere = zNew;
  75448. }
  75449. return zWhere;
  75450. }
  75451. /*
  75452. ** Generate code to drop and reload the internal representation of table
  75453. ** pTab from the database, including triggers and temporary triggers.
  75454. ** Argument zName is the name of the table in the database schema at
  75455. ** the time the generated code is executed. This can be different from
  75456. ** pTab->zName if this function is being called to code part of an
  75457. ** "ALTER TABLE RENAME TO" statement.
  75458. */
  75459. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  75460. Vdbe *v;
  75461. char *zWhere;
  75462. int iDb; /* Index of database containing pTab */
  75463. #ifndef SQLITE_OMIT_TRIGGER
  75464. Trigger *pTrig;
  75465. #endif
  75466. v = sqlite3GetVdbe(pParse);
  75467. if( NEVER(v==0) ) return;
  75468. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  75469. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  75470. assert( iDb>=0 );
  75471. #ifndef SQLITE_OMIT_TRIGGER
  75472. /* Drop any table triggers from the internal schema. */
  75473. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  75474. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  75475. assert( iTrigDb==iDb || iTrigDb==1 );
  75476. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  75477. }
  75478. #endif
  75479. /* Drop the table and index from the internal schema. */
  75480. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  75481. /* Reload the table, index and permanent trigger schemas. */
  75482. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  75483. if( !zWhere ) return;
  75484. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  75485. #ifndef SQLITE_OMIT_TRIGGER
  75486. /* Now, if the table is not stored in the temp database, reload any temp
  75487. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  75488. */
  75489. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  75490. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  75491. }
  75492. #endif
  75493. }
  75494. /*
  75495. ** Parameter zName is the name of a table that is about to be altered
  75496. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  75497. ** If the table is a system table, this function leaves an error message
  75498. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  75499. **
  75500. ** Or, if zName is not a system table, zero is returned.
  75501. */
  75502. static int isSystemTable(Parse *pParse, const char *zName){
  75503. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  75504. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  75505. return 1;
  75506. }
  75507. return 0;
  75508. }
  75509. /*
  75510. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  75511. ** command.
  75512. */
  75513. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  75514. Parse *pParse, /* Parser context. */
  75515. SrcList *pSrc, /* The table to rename. */
  75516. Token *pName /* The new table name. */
  75517. ){
  75518. int iDb; /* Database that contains the table */
  75519. char *zDb; /* Name of database iDb */
  75520. Table *pTab; /* Table being renamed */
  75521. char *zName = 0; /* NULL-terminated version of pName */
  75522. sqlite3 *db = pParse->db; /* Database connection */
  75523. int nTabName; /* Number of UTF-8 characters in zTabName */
  75524. const char *zTabName; /* Original name of the table */
  75525. Vdbe *v;
  75526. #ifndef SQLITE_OMIT_TRIGGER
  75527. char *zWhere = 0; /* Where clause to locate temp triggers */
  75528. #endif
  75529. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  75530. int savedDbFlags; /* Saved value of db->flags */
  75531. savedDbFlags = db->flags;
  75532. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  75533. assert( pSrc->nSrc==1 );
  75534. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  75535. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  75536. if( !pTab ) goto exit_rename_table;
  75537. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  75538. zDb = db->aDb[iDb].zName;
  75539. db->flags |= SQLITE_PreferBuiltin;
  75540. /* Get a NULL terminated version of the new table name. */
  75541. zName = sqlite3NameFromToken(db, pName);
  75542. if( !zName ) goto exit_rename_table;
  75543. /* Check that a table or index named 'zName' does not already exist
  75544. ** in database iDb. If so, this is an error.
  75545. */
  75546. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  75547. sqlite3ErrorMsg(pParse,
  75548. "there is already another table or index with this name: %s", zName);
  75549. goto exit_rename_table;
  75550. }
  75551. /* Make sure it is not a system table being altered, or a reserved name
  75552. ** that the table is being renamed to.
  75553. */
  75554. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  75555. goto exit_rename_table;
  75556. }
  75557. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  75558. exit_rename_table;
  75559. }
  75560. #ifndef SQLITE_OMIT_VIEW
  75561. if( pTab->pSelect ){
  75562. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  75563. goto exit_rename_table;
  75564. }
  75565. #endif
  75566. #ifndef SQLITE_OMIT_AUTHORIZATION
  75567. /* Invoke the authorization callback. */
  75568. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  75569. goto exit_rename_table;
  75570. }
  75571. #endif
  75572. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75573. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  75574. goto exit_rename_table;
  75575. }
  75576. if( IsVirtual(pTab) ){
  75577. pVTab = sqlite3GetVTable(db, pTab);
  75578. if( pVTab->pVtab->pModule->xRename==0 ){
  75579. pVTab = 0;
  75580. }
  75581. }
  75582. #endif
  75583. /* Begin a transaction and code the VerifyCookie for database iDb.
  75584. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  75585. ** schema). Open a statement transaction if the table is a virtual
  75586. ** table.
  75587. */
  75588. v = sqlite3GetVdbe(pParse);
  75589. if( v==0 ){
  75590. goto exit_rename_table;
  75591. }
  75592. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  75593. sqlite3ChangeCookie(pParse, iDb);
  75594. /* If this is a virtual table, invoke the xRename() function if
  75595. ** one is defined. The xRename() callback will modify the names
  75596. ** of any resources used by the v-table implementation (including other
  75597. ** SQLite tables) that are identified by the name of the virtual table.
  75598. */
  75599. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75600. if( pVTab ){
  75601. int i = ++pParse->nMem;
  75602. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  75603. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  75604. sqlite3MayAbort(pParse);
  75605. }
  75606. #endif
  75607. /* figure out how many UTF-8 characters are in zName */
  75608. zTabName = pTab->zName;
  75609. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  75610. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  75611. if( db->flags&SQLITE_ForeignKeys ){
  75612. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  75613. ** statements corresponding to all child tables of foreign key constraints
  75614. ** for which the renamed table is the parent table. */
  75615. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  75616. sqlite3NestedParse(pParse,
  75617. "UPDATE \"%w\".%s SET "
  75618. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  75619. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  75620. sqlite3DbFree(db, zWhere);
  75621. }
  75622. }
  75623. #endif
  75624. /* Modify the sqlite_master table to use the new table name. */
  75625. sqlite3NestedParse(pParse,
  75626. "UPDATE %Q.%s SET "
  75627. #ifdef SQLITE_OMIT_TRIGGER
  75628. "sql = sqlite_rename_table(sql, %Q), "
  75629. #else
  75630. "sql = CASE "
  75631. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  75632. "ELSE sqlite_rename_table(sql, %Q) END, "
  75633. #endif
  75634. "tbl_name = %Q, "
  75635. "name = CASE "
  75636. "WHEN type='table' THEN %Q "
  75637. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  75638. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  75639. "ELSE name END "
  75640. "WHERE tbl_name=%Q COLLATE nocase AND "
  75641. "(type='table' OR type='index' OR type='trigger');",
  75642. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  75643. #ifndef SQLITE_OMIT_TRIGGER
  75644. zName,
  75645. #endif
  75646. zName, nTabName, zTabName
  75647. );
  75648. #ifndef SQLITE_OMIT_AUTOINCREMENT
  75649. /* If the sqlite_sequence table exists in this database, then update
  75650. ** it with the new table name.
  75651. */
  75652. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  75653. sqlite3NestedParse(pParse,
  75654. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  75655. zDb, zName, pTab->zName);
  75656. }
  75657. #endif
  75658. #ifndef SQLITE_OMIT_TRIGGER
  75659. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  75660. ** table. Don't do this if the table being ALTERed is itself located in
  75661. ** the temp database.
  75662. */
  75663. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  75664. sqlite3NestedParse(pParse,
  75665. "UPDATE sqlite_temp_master SET "
  75666. "sql = sqlite_rename_trigger(sql, %Q), "
  75667. "tbl_name = %Q "
  75668. "WHERE %s;", zName, zName, zWhere);
  75669. sqlite3DbFree(db, zWhere);
  75670. }
  75671. #endif
  75672. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  75673. if( db->flags&SQLITE_ForeignKeys ){
  75674. FKey *p;
  75675. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  75676. Table *pFrom = p->pFrom;
  75677. if( pFrom!=pTab ){
  75678. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  75679. }
  75680. }
  75681. }
  75682. #endif
  75683. /* Drop and reload the internal table schema. */
  75684. reloadTableSchema(pParse, pTab, zName);
  75685. exit_rename_table:
  75686. sqlite3SrcListDelete(db, pSrc);
  75687. sqlite3DbFree(db, zName);
  75688. db->flags = savedDbFlags;
  75689. }
  75690. /*
  75691. ** Generate code to make sure the file format number is at least minFormat.
  75692. ** The generated code will increase the file format number if necessary.
  75693. */
  75694. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  75695. Vdbe *v;
  75696. v = sqlite3GetVdbe(pParse);
  75697. /* The VDBE should have been allocated before this routine is called.
  75698. ** If that allocation failed, we would have quit before reaching this
  75699. ** point */
  75700. if( ALWAYS(v) ){
  75701. int r1 = sqlite3GetTempReg(pParse);
  75702. int r2 = sqlite3GetTempReg(pParse);
  75703. int j1;
  75704. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  75705. sqlite3VdbeUsesBtree(v, iDb);
  75706. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  75707. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  75708. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  75709. sqlite3VdbeJumpHere(v, j1);
  75710. sqlite3ReleaseTempReg(pParse, r1);
  75711. sqlite3ReleaseTempReg(pParse, r2);
  75712. }
  75713. }
  75714. /*
  75715. ** This function is called after an "ALTER TABLE ... ADD" statement
  75716. ** has been parsed. Argument pColDef contains the text of the new
  75717. ** column definition.
  75718. **
  75719. ** The Table structure pParse->pNewTable was extended to include
  75720. ** the new column during parsing.
  75721. */
  75722. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  75723. Table *pNew; /* Copy of pParse->pNewTable */
  75724. Table *pTab; /* Table being altered */
  75725. int iDb; /* Database number */
  75726. const char *zDb; /* Database name */
  75727. const char *zTab; /* Table name */
  75728. char *zCol; /* Null-terminated column definition */
  75729. Column *pCol; /* The new column */
  75730. Expr *pDflt; /* Default value for the new column */
  75731. sqlite3 *db; /* The database connection; */
  75732. db = pParse->db;
  75733. if( pParse->nErr || db->mallocFailed ) return;
  75734. pNew = pParse->pNewTable;
  75735. assert( pNew );
  75736. assert( sqlite3BtreeHoldsAllMutexes(db) );
  75737. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  75738. zDb = db->aDb[iDb].zName;
  75739. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  75740. pCol = &pNew->aCol[pNew->nCol-1];
  75741. pDflt = pCol->pDflt;
  75742. pTab = sqlite3FindTable(db, zTab, zDb);
  75743. assert( pTab );
  75744. #ifndef SQLITE_OMIT_AUTHORIZATION
  75745. /* Invoke the authorization callback. */
  75746. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  75747. return;
  75748. }
  75749. #endif
  75750. /* If the default value for the new column was specified with a
  75751. ** literal NULL, then set pDflt to 0. This simplifies checking
  75752. ** for an SQL NULL default below.
  75753. */
  75754. if( pDflt && pDflt->op==TK_NULL ){
  75755. pDflt = 0;
  75756. }
  75757. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  75758. ** If there is a NOT NULL constraint, then the default value for the
  75759. ** column must not be NULL.
  75760. */
  75761. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  75762. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  75763. return;
  75764. }
  75765. if( pNew->pIndex ){
  75766. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  75767. return;
  75768. }
  75769. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  75770. sqlite3ErrorMsg(pParse,
  75771. "Cannot add a REFERENCES column with non-NULL default value");
  75772. return;
  75773. }
  75774. if( pCol->notNull && !pDflt ){
  75775. sqlite3ErrorMsg(pParse,
  75776. "Cannot add a NOT NULL column with default value NULL");
  75777. return;
  75778. }
  75779. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  75780. ** can handle (i.e. not CURRENT_TIME etc.)
  75781. */
  75782. if( pDflt ){
  75783. sqlite3_value *pVal = 0;
  75784. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  75785. db->mallocFailed = 1;
  75786. return;
  75787. }
  75788. if( !pVal ){
  75789. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  75790. return;
  75791. }
  75792. sqlite3ValueFree(pVal);
  75793. }
  75794. /* Modify the CREATE TABLE statement. */
  75795. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  75796. if( zCol ){
  75797. char *zEnd = &zCol[pColDef->n-1];
  75798. int savedDbFlags = db->flags;
  75799. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  75800. *zEnd-- = '\0';
  75801. }
  75802. db->flags |= SQLITE_PreferBuiltin;
  75803. sqlite3NestedParse(pParse,
  75804. "UPDATE \"%w\".%s SET "
  75805. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  75806. "WHERE type = 'table' AND name = %Q",
  75807. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  75808. zTab
  75809. );
  75810. sqlite3DbFree(db, zCol);
  75811. db->flags = savedDbFlags;
  75812. }
  75813. /* If the default value of the new column is NULL, then set the file
  75814. ** format to 2. If the default value of the new column is not NULL,
  75815. ** the file format becomes 3.
  75816. */
  75817. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  75818. /* Reload the schema of the modified table. */
  75819. reloadTableSchema(pParse, pTab, pTab->zName);
  75820. }
  75821. /*
  75822. ** This function is called by the parser after the table-name in
  75823. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  75824. ** pSrc is the full-name of the table being altered.
  75825. **
  75826. ** This routine makes a (partial) copy of the Table structure
  75827. ** for the table being altered and sets Parse.pNewTable to point
  75828. ** to it. Routines called by the parser as the column definition
  75829. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  75830. ** the copy. The copy of the Table structure is deleted by tokenize.c
  75831. ** after parsing is finished.
  75832. **
  75833. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  75834. ** coding the "ALTER TABLE ... ADD" statement.
  75835. */
  75836. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  75837. Table *pNew;
  75838. Table *pTab;
  75839. Vdbe *v;
  75840. int iDb;
  75841. int i;
  75842. int nAlloc;
  75843. sqlite3 *db = pParse->db;
  75844. /* Look up the table being altered. */
  75845. assert( pParse->pNewTable==0 );
  75846. assert( sqlite3BtreeHoldsAllMutexes(db) );
  75847. if( db->mallocFailed ) goto exit_begin_add_column;
  75848. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  75849. if( !pTab ) goto exit_begin_add_column;
  75850. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75851. if( IsVirtual(pTab) ){
  75852. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  75853. goto exit_begin_add_column;
  75854. }
  75855. #endif
  75856. /* Make sure this is not an attempt to ALTER a view. */
  75857. if( pTab->pSelect ){
  75858. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  75859. goto exit_begin_add_column;
  75860. }
  75861. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  75862. goto exit_begin_add_column;
  75863. }
  75864. assert( pTab->addColOffset>0 );
  75865. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  75866. /* Put a copy of the Table struct in Parse.pNewTable for the
  75867. ** sqlite3AddColumn() function and friends to modify. But modify
  75868. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  75869. ** prefix, we insure that the name will not collide with an existing
  75870. ** table because user table are not allowed to have the "sqlite_"
  75871. ** prefix on their name.
  75872. */
  75873. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  75874. if( !pNew ) goto exit_begin_add_column;
  75875. pParse->pNewTable = pNew;
  75876. pNew->nRef = 1;
  75877. pNew->nCol = pTab->nCol;
  75878. assert( pNew->nCol>0 );
  75879. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  75880. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  75881. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  75882. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  75883. if( !pNew->aCol || !pNew->zName ){
  75884. db->mallocFailed = 1;
  75885. goto exit_begin_add_column;
  75886. }
  75887. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  75888. for(i=0; i<pNew->nCol; i++){
  75889. Column *pCol = &pNew->aCol[i];
  75890. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  75891. pCol->zColl = 0;
  75892. pCol->zType = 0;
  75893. pCol->pDflt = 0;
  75894. pCol->zDflt = 0;
  75895. }
  75896. pNew->pSchema = db->aDb[iDb].pSchema;
  75897. pNew->addColOffset = pTab->addColOffset;
  75898. pNew->nRef = 1;
  75899. /* Begin a transaction and increment the schema cookie. */
  75900. sqlite3BeginWriteOperation(pParse, 0, iDb);
  75901. v = sqlite3GetVdbe(pParse);
  75902. if( !v ) goto exit_begin_add_column;
  75903. sqlite3ChangeCookie(pParse, iDb);
  75904. exit_begin_add_column:
  75905. sqlite3SrcListDelete(db, pSrc);
  75906. return;
  75907. }
  75908. #endif /* SQLITE_ALTER_TABLE */
  75909. /************** End of alter.c ***********************************************/
  75910. /************** Begin file analyze.c *****************************************/
  75911. /*
  75912. ** 2005-07-08
  75913. **
  75914. ** The author disclaims copyright to this source code. In place of
  75915. ** a legal notice, here is a blessing:
  75916. **
  75917. ** May you do good and not evil.
  75918. ** May you find forgiveness for yourself and forgive others.
  75919. ** May you share freely, never taking more than you give.
  75920. **
  75921. *************************************************************************
  75922. ** This file contains code associated with the ANALYZE command.
  75923. **
  75924. ** The ANALYZE command gather statistics about the content of tables
  75925. ** and indices. These statistics are made available to the query planner
  75926. ** to help it make better decisions about how to perform queries.
  75927. **
  75928. ** The following system tables are or have been supported:
  75929. **
  75930. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  75931. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  75932. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  75933. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  75934. **
  75935. ** Additional tables might be added in future releases of SQLite.
  75936. ** The sqlite_stat2 table is not created or used unless the SQLite version
  75937. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  75938. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  75939. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  75940. ** created and used by SQLite versions 3.7.9 and later and with
  75941. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  75942. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  75943. ** version of sqlite_stat3 and is only available when compiled with
  75944. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  75945. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  75946. ** are both enabled, then STAT4 takes precedence.
  75947. **
  75948. ** For most applications, sqlite_stat1 provides all the statisics required
  75949. ** for the query planner to make good choices.
  75950. **
  75951. ** Format of sqlite_stat1:
  75952. **
  75953. ** There is normally one row per index, with the index identified by the
  75954. ** name in the idx column. The tbl column is the name of the table to
  75955. ** which the index belongs. In each such row, the stat column will be
  75956. ** a string consisting of a list of integers. The first integer in this
  75957. ** list is the number of rows in the index. (This is the same as the
  75958. ** number of rows in the table, except for partial indices.) The second
  75959. ** integer is the average number of rows in the index that have the same
  75960. ** value in the first column of the index. The third integer is the average
  75961. ** number of rows in the index that have the same value for the first two
  75962. ** columns. The N-th integer (for N>1) is the average number of rows in
  75963. ** the index which have the same value for the first N-1 columns. For
  75964. ** a K-column index, there will be K+1 integers in the stat column. If
  75965. ** the index is unique, then the last integer will be 1.
  75966. **
  75967. ** The list of integers in the stat column can optionally be followed
  75968. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  75969. ** must be separated from the last integer by a single space. If the
  75970. ** "unordered" keyword is present, then the query planner assumes that
  75971. ** the index is unordered and will not use the index for a range query.
  75972. **
  75973. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  75974. ** column contains a single integer which is the (estimated) number of
  75975. ** rows in the table identified by sqlite_stat1.tbl.
  75976. **
  75977. ** Format of sqlite_stat2:
  75978. **
  75979. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  75980. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  75981. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  75982. ** about the distribution of keys within an index. The index is identified by
  75983. ** the "idx" column and the "tbl" column is the name of the table to which
  75984. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  75985. ** table for each index.
  75986. **
  75987. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  75988. ** inclusive are samples of the left-most key value in the index taken at
  75989. ** evenly spaced points along the index. Let the number of samples be S
  75990. ** (10 in the standard build) and let C be the number of rows in the index.
  75991. ** Then the sampled rows are given by:
  75992. **
  75993. ** rownumber = (i*C*2 + C)/(S*2)
  75994. **
  75995. ** For i between 0 and S-1. Conceptually, the index space is divided into
  75996. ** S uniform buckets and the samples are the middle row from each bucket.
  75997. **
  75998. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  75999. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  76000. ** writes the sqlite_stat2 table. This version of SQLite only supports
  76001. ** sqlite_stat3.
  76002. **
  76003. ** Format for sqlite_stat3:
  76004. **
  76005. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  76006. ** sqlite_stat4 format will be described first. Further information
  76007. ** about sqlite_stat3 follows the sqlite_stat4 description.
  76008. **
  76009. ** Format for sqlite_stat4:
  76010. **
  76011. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  76012. ** to aid the query planner in choosing good indices based on the values
  76013. ** that indexed columns are compared against in the WHERE clauses of
  76014. ** queries.
  76015. **
  76016. ** The sqlite_stat4 table contains multiple entries for each index.
  76017. ** The idx column names the index and the tbl column is the table of the
  76018. ** index. If the idx and tbl columns are the same, then the sample is
  76019. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  76020. ** binary encoding of a key from the index. The nEq column is a
  76021. ** list of integers. The first integer is the approximate number
  76022. ** of entries in the index whose left-most column exactly matches
  76023. ** the left-most column of the sample. The second integer in nEq
  76024. ** is the approximate number of entries in the index where the
  76025. ** first two columns match the first two columns of the sample.
  76026. ** And so forth. nLt is another list of integers that show the approximate
  76027. ** number of entries that are strictly less than the sample. The first
  76028. ** integer in nLt contains the number of entries in the index where the
  76029. ** left-most column is less than the left-most column of the sample.
  76030. ** The K-th integer in the nLt entry is the number of index entries
  76031. ** where the first K columns are less than the first K columns of the
  76032. ** sample. The nDLt column is like nLt except that it contains the
  76033. ** number of distinct entries in the index that are less than the
  76034. ** sample.
  76035. **
  76036. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  76037. ** The ANALYZE command will typically generate sqlite_stat4 tables
  76038. ** that contain between 10 and 40 samples which are distributed across
  76039. ** the key space, though not uniformly, and which include samples with
  76040. ** large nEq values.
  76041. **
  76042. ** Format for sqlite_stat3 redux:
  76043. **
  76044. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  76045. ** looks at the left-most column of the index. The sqlite_stat3.sample
  76046. ** column contains the actual value of the left-most column instead
  76047. ** of a blob encoding of the complete index key as is found in
  76048. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  76049. ** all contain just a single integer which is the same as the first
  76050. ** integer in the equivalent columns in sqlite_stat4.
  76051. */
  76052. #ifndef SQLITE_OMIT_ANALYZE
  76053. #if defined(SQLITE_ENABLE_STAT4)
  76054. # define IsStat4 1
  76055. # define IsStat3 0
  76056. #elif defined(SQLITE_ENABLE_STAT3)
  76057. # define IsStat4 0
  76058. # define IsStat3 1
  76059. #else
  76060. # define IsStat4 0
  76061. # define IsStat3 0
  76062. # undef SQLITE_STAT4_SAMPLES
  76063. # define SQLITE_STAT4_SAMPLES 1
  76064. #endif
  76065. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  76066. /*
  76067. ** This routine generates code that opens the sqlite_statN tables.
  76068. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  76069. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  76070. ** appropriate compile-time options are provided.
  76071. **
  76072. ** If the sqlite_statN tables do not previously exist, it is created.
  76073. **
  76074. ** Argument zWhere may be a pointer to a buffer containing a table name,
  76075. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  76076. ** the sqlite_statN tables associated with the named table are deleted.
  76077. ** If zWhere==0, then code is generated to delete all stat table entries.
  76078. */
  76079. static void openStatTable(
  76080. Parse *pParse, /* Parsing context */
  76081. int iDb, /* The database we are looking in */
  76082. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  76083. const char *zWhere, /* Delete entries for this table or index */
  76084. const char *zWhereType /* Either "tbl" or "idx" */
  76085. ){
  76086. static const struct {
  76087. const char *zName;
  76088. const char *zCols;
  76089. } aTable[] = {
  76090. { "sqlite_stat1", "tbl,idx,stat" },
  76091. #if defined(SQLITE_ENABLE_STAT4)
  76092. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  76093. { "sqlite_stat3", 0 },
  76094. #elif defined(SQLITE_ENABLE_STAT3)
  76095. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  76096. { "sqlite_stat4", 0 },
  76097. #else
  76098. { "sqlite_stat3", 0 },
  76099. { "sqlite_stat4", 0 },
  76100. #endif
  76101. };
  76102. int i;
  76103. sqlite3 *db = pParse->db;
  76104. Db *pDb;
  76105. Vdbe *v = sqlite3GetVdbe(pParse);
  76106. int aRoot[ArraySize(aTable)];
  76107. u8 aCreateTbl[ArraySize(aTable)];
  76108. if( v==0 ) return;
  76109. assert( sqlite3BtreeHoldsAllMutexes(db) );
  76110. assert( sqlite3VdbeDb(v)==db );
  76111. pDb = &db->aDb[iDb];
  76112. /* Create new statistic tables if they do not exist, or clear them
  76113. ** if they do already exist.
  76114. */
  76115. for(i=0; i<ArraySize(aTable); i++){
  76116. const char *zTab = aTable[i].zName;
  76117. Table *pStat;
  76118. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  76119. if( aTable[i].zCols ){
  76120. /* The sqlite_statN table does not exist. Create it. Note that a
  76121. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  76122. ** of the new table in register pParse->regRoot. This is important
  76123. ** because the OpenWrite opcode below will be needing it. */
  76124. sqlite3NestedParse(pParse,
  76125. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  76126. );
  76127. aRoot[i] = pParse->regRoot;
  76128. aCreateTbl[i] = OPFLAG_P2ISREG;
  76129. }
  76130. }else{
  76131. /* The table already exists. If zWhere is not NULL, delete all entries
  76132. ** associated with the table zWhere. If zWhere is NULL, delete the
  76133. ** entire contents of the table. */
  76134. aRoot[i] = pStat->tnum;
  76135. aCreateTbl[i] = 0;
  76136. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  76137. if( zWhere ){
  76138. sqlite3NestedParse(pParse,
  76139. "DELETE FROM %Q.%s WHERE %s=%Q",
  76140. pDb->zName, zTab, zWhereType, zWhere
  76141. );
  76142. }else{
  76143. /* The sqlite_stat[134] table already exists. Delete all rows. */
  76144. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  76145. }
  76146. }
  76147. }
  76148. /* Open the sqlite_stat[134] tables for writing. */
  76149. for(i=0; aTable[i].zCols; i++){
  76150. assert( i<ArraySize(aTable) );
  76151. sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
  76152. sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
  76153. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  76154. }
  76155. }
  76156. /*
  76157. ** Recommended number of samples for sqlite_stat4
  76158. */
  76159. #ifndef SQLITE_STAT4_SAMPLES
  76160. # define SQLITE_STAT4_SAMPLES 24
  76161. #endif
  76162. /*
  76163. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  76164. ** share an instance of the following structure to hold their state
  76165. ** information.
  76166. */
  76167. typedef struct Stat4Accum Stat4Accum;
  76168. typedef struct Stat4Sample Stat4Sample;
  76169. struct Stat4Sample {
  76170. tRowcnt *anEq; /* sqlite_stat4.nEq */
  76171. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  76172. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76173. tRowcnt *anLt; /* sqlite_stat4.nLt */
  76174. i64 iRowid; /* Rowid in main table of the key */
  76175. u8 isPSample; /* True if a periodic sample */
  76176. int iCol; /* If !isPSample, the reason for inclusion */
  76177. u32 iHash; /* Tiebreaker hash */
  76178. #endif
  76179. };
  76180. struct Stat4Accum {
  76181. tRowcnt nRow; /* Number of rows in the entire table */
  76182. tRowcnt nPSample; /* How often to do a periodic sample */
  76183. int nCol; /* Number of columns in index + rowid */
  76184. int mxSample; /* Maximum number of samples to accumulate */
  76185. Stat4Sample current; /* Current row as a Stat4Sample */
  76186. u32 iPrn; /* Pseudo-random number used for sampling */
  76187. Stat4Sample *aBest; /* Array of (nCol-1) best samples */
  76188. int iMin; /* Index in a[] of entry with minimum score */
  76189. int nSample; /* Current number of samples */
  76190. int iGet; /* Index of current sample accessed by stat_get() */
  76191. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  76192. };
  76193. /*
  76194. ** Implementation of the stat_init(N,C) SQL function. The two parameters
  76195. ** are the number of rows in the table or index (C) and the number of columns
  76196. ** in the index (N). The second argument (C) is only used for STAT3 and STAT4.
  76197. **
  76198. ** This routine allocates the Stat4Accum object in heap memory. The return
  76199. ** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
  76200. ** the size of the blob is sizeof(void*) bytes).
  76201. */
  76202. static void statInit(
  76203. sqlite3_context *context,
  76204. int argc,
  76205. sqlite3_value **argv
  76206. ){
  76207. Stat4Accum *p;
  76208. int nCol; /* Number of columns in index being sampled */
  76209. int nColUp; /* nCol rounded up for alignment */
  76210. int n; /* Bytes of space to allocate */
  76211. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76212. int mxSample = SQLITE_STAT4_SAMPLES;
  76213. #endif
  76214. /* Decode the three function arguments */
  76215. UNUSED_PARAMETER(argc);
  76216. nCol = sqlite3_value_int(argv[0]);
  76217. assert( nCol>1 ); /* >1 because it includes the rowid column */
  76218. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  76219. /* Allocate the space required for the Stat4Accum object */
  76220. n = sizeof(*p)
  76221. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  76222. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  76223. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76224. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  76225. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  76226. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  76227. #endif
  76228. ;
  76229. p = sqlite3MallocZero(n);
  76230. if( p==0 ){
  76231. sqlite3_result_error_nomem(context);
  76232. return;
  76233. }
  76234. p->nRow = 0;
  76235. p->nCol = nCol;
  76236. p->current.anDLt = (tRowcnt*)&p[1];
  76237. p->current.anEq = &p->current.anDLt[nColUp];
  76238. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76239. {
  76240. u8 *pSpace; /* Allocated space not yet assigned */
  76241. int i; /* Used to iterate through p->aSample[] */
  76242. p->iGet = -1;
  76243. p->mxSample = mxSample;
  76244. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1);
  76245. p->current.anLt = &p->current.anEq[nColUp];
  76246. p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[1])*0xd0944565;
  76247. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  76248. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  76249. p->aBest = &p->a[mxSample];
  76250. pSpace = (u8*)(&p->a[mxSample+nCol]);
  76251. for(i=0; i<(mxSample+nCol); i++){
  76252. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  76253. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  76254. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  76255. }
  76256. assert( (pSpace - (u8*)p)==n );
  76257. for(i=0; i<nCol; i++){
  76258. p->aBest[i].iCol = i;
  76259. }
  76260. }
  76261. #endif
  76262. /* Return a pointer to the allocated object to the caller */
  76263. sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
  76264. }
  76265. static const FuncDef statInitFuncdef = {
  76266. 1+IsStat34, /* nArg */
  76267. SQLITE_UTF8, /* funcFlags */
  76268. 0, /* pUserData */
  76269. 0, /* pNext */
  76270. statInit, /* xFunc */
  76271. 0, /* xStep */
  76272. 0, /* xFinalize */
  76273. "stat_init", /* zName */
  76274. 0, /* pHash */
  76275. 0 /* pDestructor */
  76276. };
  76277. #ifdef SQLITE_ENABLE_STAT4
  76278. /*
  76279. ** pNew and pOld are both candidate non-periodic samples selected for
  76280. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  76281. ** considering only any trailing columns and the sample hash value, this
  76282. ** function returns true if sample pNew is to be preferred over pOld.
  76283. ** In other words, if we assume that the cardinalities of the selected
  76284. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  76285. **
  76286. ** This function assumes that for each argument sample, the contents of
  76287. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  76288. */
  76289. static int sampleIsBetterPost(
  76290. Stat4Accum *pAccum,
  76291. Stat4Sample *pNew,
  76292. Stat4Sample *pOld
  76293. ){
  76294. int nCol = pAccum->nCol;
  76295. int i;
  76296. assert( pNew->iCol==pOld->iCol );
  76297. for(i=pNew->iCol+1; i<nCol; i++){
  76298. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  76299. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  76300. }
  76301. if( pNew->iHash>pOld->iHash ) return 1;
  76302. return 0;
  76303. }
  76304. #endif
  76305. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76306. /*
  76307. ** Return true if pNew is to be preferred over pOld.
  76308. **
  76309. ** This function assumes that for each argument sample, the contents of
  76310. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  76311. */
  76312. static int sampleIsBetter(
  76313. Stat4Accum *pAccum,
  76314. Stat4Sample *pNew,
  76315. Stat4Sample *pOld
  76316. ){
  76317. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  76318. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  76319. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  76320. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  76321. if( (nEqNew>nEqOld) ) return 1;
  76322. #ifdef SQLITE_ENABLE_STAT4
  76323. if( nEqNew==nEqOld ){
  76324. if( pNew->iCol<pOld->iCol ) return 1;
  76325. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  76326. }
  76327. return 0;
  76328. #else
  76329. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  76330. #endif
  76331. }
  76332. /*
  76333. ** Copy the contents of object (*pFrom) into (*pTo).
  76334. */
  76335. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  76336. pTo->iRowid = pFrom->iRowid;
  76337. pTo->isPSample = pFrom->isPSample;
  76338. pTo->iCol = pFrom->iCol;
  76339. pTo->iHash = pFrom->iHash;
  76340. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  76341. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  76342. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  76343. }
  76344. /*
  76345. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  76346. ** remove the least desirable sample from p->a[] to make room.
  76347. */
  76348. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  76349. Stat4Sample *pSample;
  76350. int i;
  76351. assert( IsStat4 || nEqZero==0 );
  76352. #ifdef SQLITE_ENABLE_STAT4
  76353. if( pNew->isPSample==0 ){
  76354. Stat4Sample *pUpgrade = 0;
  76355. assert( pNew->anEq[pNew->iCol]>0 );
  76356. /* This sample is being added because the prefix that ends in column
  76357. ** iCol occurs many times in the table. However, if we have already
  76358. ** added a sample that shares this prefix, there is no need to add
  76359. ** this one. Instead, upgrade the priority of the highest priority
  76360. ** existing sample that shares this prefix. */
  76361. for(i=p->nSample-1; i>=0; i--){
  76362. Stat4Sample *pOld = &p->a[i];
  76363. if( pOld->anEq[pNew->iCol]==0 ){
  76364. if( pOld->isPSample ) return;
  76365. assert( pOld->iCol>pNew->iCol );
  76366. assert( sampleIsBetter(p, pNew, pOld) );
  76367. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  76368. pUpgrade = pOld;
  76369. }
  76370. }
  76371. }
  76372. if( pUpgrade ){
  76373. pUpgrade->iCol = pNew->iCol;
  76374. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  76375. goto find_new_min;
  76376. }
  76377. }
  76378. #endif
  76379. /* If necessary, remove sample iMin to make room for the new sample. */
  76380. if( p->nSample>=p->mxSample ){
  76381. Stat4Sample *pMin = &p->a[p->iMin];
  76382. tRowcnt *anEq = pMin->anEq;
  76383. tRowcnt *anLt = pMin->anLt;
  76384. tRowcnt *anDLt = pMin->anDLt;
  76385. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  76386. pSample = &p->a[p->nSample-1];
  76387. pSample->anEq = anEq;
  76388. pSample->anDLt = anDLt;
  76389. pSample->anLt = anLt;
  76390. p->nSample = p->mxSample-1;
  76391. }
  76392. /* The "rows less-than" for the rowid column must be greater than that
  76393. ** for the last sample in the p->a[] array. Otherwise, the samples would
  76394. ** be out of order. */
  76395. #ifdef SQLITE_ENABLE_STAT4
  76396. assert( p->nSample==0
  76397. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  76398. #endif
  76399. /* Insert the new sample */
  76400. pSample = &p->a[p->nSample];
  76401. sampleCopy(p, pSample, pNew);
  76402. p->nSample++;
  76403. /* Zero the first nEqZero entries in the anEq[] array. */
  76404. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  76405. #ifdef SQLITE_ENABLE_STAT4
  76406. find_new_min:
  76407. #endif
  76408. if( p->nSample>=p->mxSample ){
  76409. int iMin = -1;
  76410. for(i=0; i<p->mxSample; i++){
  76411. if( p->a[i].isPSample ) continue;
  76412. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  76413. iMin = i;
  76414. }
  76415. }
  76416. assert( iMin>=0 );
  76417. p->iMin = iMin;
  76418. }
  76419. }
  76420. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  76421. /*
  76422. ** Field iChng of the index being scanned has changed. So at this point
  76423. ** p->current contains a sample that reflects the previous row of the
  76424. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  76425. ** correct at this point.
  76426. */
  76427. static void samplePushPrevious(Stat4Accum *p, int iChng){
  76428. #ifdef SQLITE_ENABLE_STAT4
  76429. int i;
  76430. /* Check if any samples from the aBest[] array should be pushed
  76431. ** into IndexSample.a[] at this point. */
  76432. for(i=(p->nCol-2); i>=iChng; i--){
  76433. Stat4Sample *pBest = &p->aBest[i];
  76434. pBest->anEq[i] = p->current.anEq[i];
  76435. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  76436. sampleInsert(p, pBest, i);
  76437. }
  76438. }
  76439. /* Update the anEq[] fields of any samples already collected. */
  76440. for(i=p->nSample-1; i>=0; i--){
  76441. int j;
  76442. for(j=iChng; j<p->nCol; j++){
  76443. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  76444. }
  76445. }
  76446. #endif
  76447. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  76448. if( iChng==0 ){
  76449. tRowcnt nLt = p->current.anLt[0];
  76450. tRowcnt nEq = p->current.anEq[0];
  76451. /* Check if this is to be a periodic sample. If so, add it. */
  76452. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  76453. p->current.isPSample = 1;
  76454. sampleInsert(p, &p->current, 0);
  76455. p->current.isPSample = 0;
  76456. }else
  76457. /* Or if it is a non-periodic sample. Add it in this case too. */
  76458. if( p->nSample<p->mxSample
  76459. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  76460. ){
  76461. sampleInsert(p, &p->current, 0);
  76462. }
  76463. }
  76464. #endif
  76465. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  76466. UNUSED_PARAMETER( p );
  76467. UNUSED_PARAMETER( iChng );
  76468. #endif
  76469. }
  76470. /*
  76471. ** Implementation of the stat_push SQL function: stat_push(P,R,C)
  76472. ** Arguments:
  76473. **
  76474. ** P Pointer to the Stat4Accum object created by stat_init()
  76475. ** C Index of left-most column to differ from previous row
  76476. ** R Rowid for the current row
  76477. **
  76478. ** The SQL function always returns NULL.
  76479. **
  76480. ** The R parameter is only used for STAT3 and STAT4.
  76481. */
  76482. static void statPush(
  76483. sqlite3_context *context,
  76484. int argc,
  76485. sqlite3_value **argv
  76486. ){
  76487. int i;
  76488. /* The three function arguments */
  76489. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  76490. int iChng = sqlite3_value_int(argv[1]);
  76491. UNUSED_PARAMETER( argc );
  76492. UNUSED_PARAMETER( context );
  76493. assert( p->nCol>1 ); /* Includes rowid field */
  76494. assert( iChng<p->nCol );
  76495. if( p->nRow==0 ){
  76496. /* This is the first call to this function. Do initialization. */
  76497. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  76498. }else{
  76499. /* Second and subsequent calls get processed here */
  76500. samplePushPrevious(p, iChng);
  76501. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  76502. ** to the current row of the index. */
  76503. for(i=0; i<iChng; i++){
  76504. p->current.anEq[i]++;
  76505. }
  76506. for(i=iChng; i<p->nCol; i++){
  76507. p->current.anDLt[i]++;
  76508. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76509. p->current.anLt[i] += p->current.anEq[i];
  76510. #endif
  76511. p->current.anEq[i] = 1;
  76512. }
  76513. }
  76514. p->nRow++;
  76515. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76516. p->current.iRowid = sqlite3_value_int64(argv[2]);
  76517. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  76518. #endif
  76519. #ifdef SQLITE_ENABLE_STAT4
  76520. {
  76521. tRowcnt nLt = p->current.anLt[p->nCol-1];
  76522. /* Check if this is to be a periodic sample. If so, add it. */
  76523. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  76524. p->current.isPSample = 1;
  76525. p->current.iCol = 0;
  76526. sampleInsert(p, &p->current, p->nCol-1);
  76527. p->current.isPSample = 0;
  76528. }
  76529. /* Update the aBest[] array. */
  76530. for(i=0; i<(p->nCol-1); i++){
  76531. p->current.iCol = i;
  76532. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  76533. sampleCopy(p, &p->aBest[i], &p->current);
  76534. }
  76535. }
  76536. }
  76537. #endif
  76538. }
  76539. static const FuncDef statPushFuncdef = {
  76540. 2+IsStat34, /* nArg */
  76541. SQLITE_UTF8, /* funcFlags */
  76542. 0, /* pUserData */
  76543. 0, /* pNext */
  76544. statPush, /* xFunc */
  76545. 0, /* xStep */
  76546. 0, /* xFinalize */
  76547. "stat_push", /* zName */
  76548. 0, /* pHash */
  76549. 0 /* pDestructor */
  76550. };
  76551. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  76552. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  76553. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  76554. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  76555. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  76556. /*
  76557. ** Implementation of the stat_get(P,J) SQL function. This routine is
  76558. ** used to query the results. Content is returned for parameter J
  76559. ** which is one of the STAT_GET_xxxx values defined above.
  76560. **
  76561. ** If neither STAT3 nor STAT4 are enabled, then J is always
  76562. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  76563. ** a one-parameter function, stat_get(P), that always returns the
  76564. ** stat1 table entry information.
  76565. */
  76566. static void statGet(
  76567. sqlite3_context *context,
  76568. int argc,
  76569. sqlite3_value **argv
  76570. ){
  76571. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  76572. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76573. /* STAT3 and STAT4 have a parameter on this routine. */
  76574. int eCall = sqlite3_value_int(argv[1]);
  76575. assert( argc==2 );
  76576. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  76577. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  76578. || eCall==STAT_GET_NDLT
  76579. );
  76580. if( eCall==STAT_GET_STAT1 )
  76581. #else
  76582. assert( argc==1 );
  76583. #endif
  76584. {
  76585. /* Return the value to store in the "stat" column of the sqlite_stat1
  76586. ** table for this index.
  76587. **
  76588. ** The value is a string composed of a list of integers describing
  76589. ** the index. The first integer in the list is the total number of
  76590. ** entries in the index. There is one additional integer in the list
  76591. ** for each indexed column. This additional integer is an estimate of
  76592. ** the number of rows matched by a stabbing query on the index using
  76593. ** a key with the corresponding number of fields. In other words,
  76594. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  76595. ** "100 10 2", then SQLite estimates that:
  76596. **
  76597. ** * the index contains 100 rows,
  76598. ** * "WHERE a=?" matches 10 rows, and
  76599. ** * "WHERE a=? AND b=?" matches 2 rows.
  76600. **
  76601. ** If D is the count of distinct values and K is the total number of
  76602. ** rows, then each estimate is computed as:
  76603. **
  76604. ** I = (K+D-1)/D
  76605. */
  76606. char *z;
  76607. int i;
  76608. char *zRet = sqlite3MallocZero(p->nCol * 25);
  76609. if( zRet==0 ){
  76610. sqlite3_result_error_nomem(context);
  76611. return;
  76612. }
  76613. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  76614. z = zRet + sqlite3Strlen30(zRet);
  76615. for(i=0; i<(p->nCol-1); i++){
  76616. u64 nDistinct = p->current.anDLt[i] + 1;
  76617. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  76618. sqlite3_snprintf(24, z, " %llu", iVal);
  76619. z += sqlite3Strlen30(z);
  76620. assert( p->current.anEq[i] );
  76621. }
  76622. assert( z[0]=='\0' && z>zRet );
  76623. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  76624. }
  76625. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76626. else if( eCall==STAT_GET_ROWID ){
  76627. if( p->iGet<0 ){
  76628. samplePushPrevious(p, 0);
  76629. p->iGet = 0;
  76630. }
  76631. if( p->iGet<p->nSample ){
  76632. sqlite3_result_int64(context, p->a[p->iGet].iRowid);
  76633. }
  76634. }else{
  76635. tRowcnt *aCnt = 0;
  76636. assert( p->iGet<p->nSample );
  76637. switch( eCall ){
  76638. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  76639. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  76640. default: {
  76641. aCnt = p->a[p->iGet].anDLt;
  76642. p->iGet++;
  76643. break;
  76644. }
  76645. }
  76646. if( IsStat3 ){
  76647. sqlite3_result_int64(context, (i64)aCnt[0]);
  76648. }else{
  76649. char *zRet = sqlite3MallocZero(p->nCol * 25);
  76650. if( zRet==0 ){
  76651. sqlite3_result_error_nomem(context);
  76652. }else{
  76653. int i;
  76654. char *z = zRet;
  76655. for(i=0; i<p->nCol; i++){
  76656. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  76657. z += sqlite3Strlen30(z);
  76658. }
  76659. assert( z[0]=='\0' && z>zRet );
  76660. z[-1] = '\0';
  76661. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  76662. }
  76663. }
  76664. }
  76665. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  76666. #ifndef SQLITE_DEBUG
  76667. UNUSED_PARAMETER( argc );
  76668. #endif
  76669. }
  76670. static const FuncDef statGetFuncdef = {
  76671. 1+IsStat34, /* nArg */
  76672. SQLITE_UTF8, /* funcFlags */
  76673. 0, /* pUserData */
  76674. 0, /* pNext */
  76675. statGet, /* xFunc */
  76676. 0, /* xStep */
  76677. 0, /* xFinalize */
  76678. "stat_get", /* zName */
  76679. 0, /* pHash */
  76680. 0 /* pDestructor */
  76681. };
  76682. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  76683. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  76684. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76685. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  76686. #elif SQLITE_DEBUG
  76687. assert( iParam==STAT_GET_STAT1 );
  76688. #else
  76689. UNUSED_PARAMETER( iParam );
  76690. #endif
  76691. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
  76692. sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
  76693. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  76694. }
  76695. /*
  76696. ** Generate code to do an analysis of all indices associated with
  76697. ** a single table.
  76698. */
  76699. static void analyzeOneTable(
  76700. Parse *pParse, /* Parser context */
  76701. Table *pTab, /* Table whose indices are to be analyzed */
  76702. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  76703. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  76704. int iMem, /* Available memory locations begin here */
  76705. int iTab /* Next available cursor */
  76706. ){
  76707. sqlite3 *db = pParse->db; /* Database handle */
  76708. Index *pIdx; /* An index to being analyzed */
  76709. int iIdxCur; /* Cursor open on index being analyzed */
  76710. int iTabCur; /* Table cursor */
  76711. Vdbe *v; /* The virtual machine being built up */
  76712. int i; /* Loop counter */
  76713. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  76714. int iDb; /* Index of database containing pTab */
  76715. u8 needTableCnt = 1; /* True to count the table */
  76716. int regNewRowid = iMem++; /* Rowid for the inserted record */
  76717. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  76718. int regChng = iMem++; /* Index of changed index field */
  76719. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76720. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  76721. #endif
  76722. int regTemp = iMem++; /* Temporary use register */
  76723. int regTabname = iMem++; /* Register containing table name */
  76724. int regIdxname = iMem++; /* Register containing index name */
  76725. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  76726. int regPrev = iMem; /* MUST BE LAST (see below) */
  76727. pParse->nMem = MAX(pParse->nMem, iMem);
  76728. v = sqlite3GetVdbe(pParse);
  76729. if( v==0 || NEVER(pTab==0) ){
  76730. return;
  76731. }
  76732. if( pTab->tnum==0 ){
  76733. /* Do not gather statistics on views or virtual tables */
  76734. return;
  76735. }
  76736. if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
  76737. /* Do not gather statistics on system tables */
  76738. return;
  76739. }
  76740. assert( sqlite3BtreeHoldsAllMutexes(db) );
  76741. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  76742. assert( iDb>=0 );
  76743. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  76744. #ifndef SQLITE_OMIT_AUTHORIZATION
  76745. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  76746. db->aDb[iDb].zName ) ){
  76747. return;
  76748. }
  76749. #endif
  76750. /* Establish a read-lock on the table at the shared-cache level.
  76751. ** Open a read-only cursor on the table. Also allocate a cursor number
  76752. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  76753. ** this time though. */
  76754. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  76755. iTabCur = iTab++;
  76756. iIdxCur = iTab++;
  76757. pParse->nTab = MAX(pParse->nTab, iTab);
  76758. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  76759. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  76760. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  76761. int nCol; /* Number of columns indexed by pIdx */
  76762. KeyInfo *pKey; /* KeyInfo structure for pIdx */
  76763. int *aGotoChng; /* Array of jump instruction addresses */
  76764. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  76765. int addrGotoChng0; /* Address of "Goto addr_chng_0" */
  76766. int addrNextRow; /* Address of "next_row:" */
  76767. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  76768. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  76769. VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
  76770. nCol = pIdx->nColumn;
  76771. aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
  76772. if( aGotoChng==0 ) continue;
  76773. pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  76774. /* Populate the register containing the index name. */
  76775. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
  76776. /*
  76777. ** Pseudo-code for loop that calls stat_push():
  76778. **
  76779. ** Rewind csr
  76780. ** if eof(csr) goto end_of_scan;
  76781. ** regChng = 0
  76782. ** goto chng_addr_0;
  76783. **
  76784. ** next_row:
  76785. ** regChng = 0
  76786. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  76787. ** regChng = 1
  76788. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  76789. ** ...
  76790. ** regChng = N
  76791. ** goto chng_addr_N
  76792. **
  76793. ** chng_addr_0:
  76794. ** regPrev(0) = idx(0)
  76795. ** chng_addr_1:
  76796. ** regPrev(1) = idx(1)
  76797. ** ...
  76798. **
  76799. ** chng_addr_N:
  76800. ** regRowid = idx(rowid)
  76801. ** stat_push(P, regChng, regRowid)
  76802. ** Next csr
  76803. ** if !eof(csr) goto next_row;
  76804. **
  76805. ** end_of_scan:
  76806. */
  76807. /* Make sure there are enough memory cells allocated to accommodate
  76808. ** the regPrev array and a trailing rowid (the rowid slot is required
  76809. ** when building a record to insert into the sample column of
  76810. ** the sqlite_stat4 table. */
  76811. pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
  76812. /* Open a read-only cursor on the index being analyzed. */
  76813. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  76814. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  76815. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  76816. VdbeComment((v, "%s", pIdx->zName));
  76817. /* Invoke the stat_init() function. The arguments are:
  76818. **
  76819. ** (1) the number of columns in the index including the rowid,
  76820. ** (2) the number of rows in the index,
  76821. **
  76822. ** The second argument is only used for STAT3 and STAT4
  76823. */
  76824. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76825. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2);
  76826. #endif
  76827. sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1);
  76828. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
  76829. sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
  76830. sqlite3VdbeChangeP5(v, 1+IsStat34);
  76831. /* Implementation of the following:
  76832. **
  76833. ** Rewind csr
  76834. ** if eof(csr) goto end_of_scan;
  76835. ** regChng = 0
  76836. ** goto next_push_0;
  76837. **
  76838. */
  76839. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  76840. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  76841. addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
  76842. /*
  76843. ** next_row:
  76844. ** regChng = 0
  76845. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  76846. ** regChng = 1
  76847. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  76848. ** ...
  76849. ** regChng = N
  76850. ** goto chng_addr_N
  76851. */
  76852. addrNextRow = sqlite3VdbeCurrentAddr(v);
  76853. for(i=0; i<nCol; i++){
  76854. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  76855. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  76856. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  76857. aGotoChng[i] =
  76858. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  76859. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  76860. }
  76861. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
  76862. aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
  76863. /*
  76864. ** chng_addr_0:
  76865. ** regPrev(0) = idx(0)
  76866. ** chng_addr_1:
  76867. ** regPrev(1) = idx(1)
  76868. ** ...
  76869. */
  76870. sqlite3VdbeJumpHere(v, addrGotoChng0);
  76871. for(i=0; i<nCol; i++){
  76872. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  76873. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  76874. }
  76875. /*
  76876. ** chng_addr_N:
  76877. ** regRowid = idx(rowid) // STAT34 only
  76878. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  76879. ** Next csr
  76880. ** if !eof(csr) goto next_row;
  76881. */
  76882. sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
  76883. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76884. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  76885. assert( regRowid==(regStat4+2) );
  76886. #endif
  76887. assert( regChng==(regStat4+1) );
  76888. sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
  76889. sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  76890. sqlite3VdbeChangeP5(v, 2+IsStat34);
  76891. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow);
  76892. /* Add the entry to the stat1 table. */
  76893. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  76894. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  76895. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  76896. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  76897. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  76898. /* Add the entries to the stat3 or stat4 table. */
  76899. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76900. {
  76901. int regEq = regStat1;
  76902. int regLt = regStat1+1;
  76903. int regDLt = regStat1+2;
  76904. int regSample = regStat1+3;
  76905. int regCol = regStat1+4;
  76906. int regSampleRowid = regCol + nCol;
  76907. int addrNext;
  76908. int addrIsNull;
  76909. pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
  76910. addrNext = sqlite3VdbeCurrentAddr(v);
  76911. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  76912. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  76913. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  76914. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  76915. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  76916. sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, addrNext, regSampleRowid);
  76917. #ifdef SQLITE_ENABLE_STAT3
  76918. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  76919. pIdx->aiColumn[0], regSample);
  76920. #else
  76921. for(i=0; i<nCol; i++){
  76922. int iCol = pIdx->aiColumn[i];
  76923. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
  76924. }
  76925. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
  76926. #endif
  76927. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0);
  76928. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  76929. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  76930. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
  76931. sqlite3VdbeJumpHere(v, addrIsNull);
  76932. }
  76933. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  76934. /* End of analysis */
  76935. sqlite3VdbeJumpHere(v, addrRewind);
  76936. sqlite3DbFree(db, aGotoChng);
  76937. }
  76938. /* Create a single sqlite_stat1 entry containing NULL as the index
  76939. ** name and the row count as the content.
  76940. */
  76941. if( pOnlyIdx==0 && needTableCnt ){
  76942. VdbeComment((v, "%s", pTab->zName));
  76943. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  76944. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
  76945. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  76946. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  76947. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  76948. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  76949. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  76950. sqlite3VdbeJumpHere(v, jZeroRows);
  76951. }
  76952. }
  76953. /*
  76954. ** Generate code that will cause the most recent index analysis to
  76955. ** be loaded into internal hash tables where is can be used.
  76956. */
  76957. static void loadAnalysis(Parse *pParse, int iDb){
  76958. Vdbe *v = sqlite3GetVdbe(pParse);
  76959. if( v ){
  76960. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  76961. }
  76962. }
  76963. /*
  76964. ** Generate code that will do an analysis of an entire database
  76965. */
  76966. static void analyzeDatabase(Parse *pParse, int iDb){
  76967. sqlite3 *db = pParse->db;
  76968. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  76969. HashElem *k;
  76970. int iStatCur;
  76971. int iMem;
  76972. int iTab;
  76973. sqlite3BeginWriteOperation(pParse, 0, iDb);
  76974. iStatCur = pParse->nTab;
  76975. pParse->nTab += 3;
  76976. openStatTable(pParse, iDb, iStatCur, 0, 0);
  76977. iMem = pParse->nMem+1;
  76978. iTab = pParse->nTab;
  76979. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  76980. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  76981. Table *pTab = (Table*)sqliteHashData(k);
  76982. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  76983. }
  76984. loadAnalysis(pParse, iDb);
  76985. }
  76986. /*
  76987. ** Generate code that will do an analysis of a single table in
  76988. ** a database. If pOnlyIdx is not NULL then it is a single index
  76989. ** in pTab that should be analyzed.
  76990. */
  76991. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  76992. int iDb;
  76993. int iStatCur;
  76994. assert( pTab!=0 );
  76995. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  76996. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  76997. sqlite3BeginWriteOperation(pParse, 0, iDb);
  76998. iStatCur = pParse->nTab;
  76999. pParse->nTab += 3;
  77000. if( pOnlyIdx ){
  77001. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  77002. }else{
  77003. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  77004. }
  77005. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  77006. loadAnalysis(pParse, iDb);
  77007. }
  77008. /*
  77009. ** Generate code for the ANALYZE command. The parser calls this routine
  77010. ** when it recognizes an ANALYZE command.
  77011. **
  77012. ** ANALYZE -- 1
  77013. ** ANALYZE <database> -- 2
  77014. ** ANALYZE ?<database>.?<tablename> -- 3
  77015. **
  77016. ** Form 1 causes all indices in all attached databases to be analyzed.
  77017. ** Form 2 analyzes all indices the single database named.
  77018. ** Form 3 analyzes all indices associated with the named table.
  77019. */
  77020. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  77021. sqlite3 *db = pParse->db;
  77022. int iDb;
  77023. int i;
  77024. char *z, *zDb;
  77025. Table *pTab;
  77026. Index *pIdx;
  77027. Token *pTableName;
  77028. /* Read the database schema. If an error occurs, leave an error message
  77029. ** and code in pParse and return NULL. */
  77030. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  77031. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  77032. return;
  77033. }
  77034. assert( pName2!=0 || pName1==0 );
  77035. if( pName1==0 ){
  77036. /* Form 1: Analyze everything */
  77037. for(i=0; i<db->nDb; i++){
  77038. if( i==1 ) continue; /* Do not analyze the TEMP database */
  77039. analyzeDatabase(pParse, i);
  77040. }
  77041. }else if( pName2->n==0 ){
  77042. /* Form 2: Analyze the database or table named */
  77043. iDb = sqlite3FindDb(db, pName1);
  77044. if( iDb>=0 ){
  77045. analyzeDatabase(pParse, iDb);
  77046. }else{
  77047. z = sqlite3NameFromToken(db, pName1);
  77048. if( z ){
  77049. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  77050. analyzeTable(pParse, pIdx->pTable, pIdx);
  77051. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  77052. analyzeTable(pParse, pTab, 0);
  77053. }
  77054. sqlite3DbFree(db, z);
  77055. }
  77056. }
  77057. }else{
  77058. /* Form 3: Analyze the fully qualified table name */
  77059. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  77060. if( iDb>=0 ){
  77061. zDb = db->aDb[iDb].zName;
  77062. z = sqlite3NameFromToken(db, pTableName);
  77063. if( z ){
  77064. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  77065. analyzeTable(pParse, pIdx->pTable, pIdx);
  77066. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  77067. analyzeTable(pParse, pTab, 0);
  77068. }
  77069. sqlite3DbFree(db, z);
  77070. }
  77071. }
  77072. }
  77073. }
  77074. /*
  77075. ** Used to pass information from the analyzer reader through to the
  77076. ** callback routine.
  77077. */
  77078. typedef struct analysisInfo analysisInfo;
  77079. struct analysisInfo {
  77080. sqlite3 *db;
  77081. const char *zDatabase;
  77082. };
  77083. /*
  77084. ** The first argument points to a nul-terminated string containing a
  77085. ** list of space separated integers. Read the first nOut of these into
  77086. ** the array aOut[].
  77087. */
  77088. static void decodeIntArray(
  77089. char *zIntArray, /* String containing int array to decode */
  77090. int nOut, /* Number of slots in aOut[] */
  77091. tRowcnt *aOut, /* Store integers here */
  77092. Index *pIndex /* Handle extra flags for this index, if not NULL */
  77093. ){
  77094. char *z = zIntArray;
  77095. int c;
  77096. int i;
  77097. tRowcnt v;
  77098. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  77099. if( z==0 ) z = "";
  77100. #else
  77101. if( NEVER(z==0) ) z = "";
  77102. #endif
  77103. for(i=0; *z && i<nOut; i++){
  77104. v = 0;
  77105. while( (c=z[0])>='0' && c<='9' ){
  77106. v = v*10 + c - '0';
  77107. z++;
  77108. }
  77109. aOut[i] = v;
  77110. if( *z==' ' ) z++;
  77111. }
  77112. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  77113. assert( pIndex!=0 );
  77114. #else
  77115. if( pIndex )
  77116. #endif
  77117. {
  77118. if( strcmp(z, "unordered")==0 ){
  77119. pIndex->bUnordered = 1;
  77120. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  77121. int v32 = 0;
  77122. sqlite3GetInt32(z+3, &v32);
  77123. pIndex->szIdxRow = sqlite3LogEst(v32);
  77124. }
  77125. }
  77126. }
  77127. /*
  77128. ** This callback is invoked once for each index when reading the
  77129. ** sqlite_stat1 table.
  77130. **
  77131. ** argv[0] = name of the table
  77132. ** argv[1] = name of the index (might be NULL)
  77133. ** argv[2] = results of analysis - on integer for each column
  77134. **
  77135. ** Entries for which argv[1]==NULL simply record the number of rows in
  77136. ** the table.
  77137. */
  77138. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  77139. analysisInfo *pInfo = (analysisInfo*)pData;
  77140. Index *pIndex;
  77141. Table *pTable;
  77142. const char *z;
  77143. assert( argc==3 );
  77144. UNUSED_PARAMETER2(NotUsed, argc);
  77145. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  77146. return 0;
  77147. }
  77148. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  77149. if( pTable==0 ){
  77150. return 0;
  77151. }
  77152. if( argv[1] ){
  77153. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  77154. }else{
  77155. pIndex = 0;
  77156. }
  77157. z = argv[2];
  77158. if( pIndex ){
  77159. decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst, pIndex);
  77160. if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0];
  77161. }else{
  77162. Index fakeIdx;
  77163. fakeIdx.szIdxRow = pTable->szTabRow;
  77164. decodeIntArray((char*)z, 1, &pTable->nRowEst, &fakeIdx);
  77165. pTable->szTabRow = fakeIdx.szIdxRow;
  77166. }
  77167. return 0;
  77168. }
  77169. /*
  77170. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  77171. ** and its contents.
  77172. */
  77173. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  77174. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  77175. if( pIdx->aSample ){
  77176. int j;
  77177. for(j=0; j<pIdx->nSample; j++){
  77178. IndexSample *p = &pIdx->aSample[j];
  77179. sqlite3DbFree(db, p->p);
  77180. }
  77181. sqlite3DbFree(db, pIdx->aSample);
  77182. }
  77183. if( db && db->pnBytesFreed==0 ){
  77184. pIdx->nSample = 0;
  77185. pIdx->aSample = 0;
  77186. }
  77187. #else
  77188. UNUSED_PARAMETER(db);
  77189. UNUSED_PARAMETER(pIdx);
  77190. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  77191. }
  77192. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  77193. /*
  77194. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  77195. ** stored in pIdx->aSample[].
  77196. */
  77197. static void initAvgEq(Index *pIdx){
  77198. if( pIdx ){
  77199. IndexSample *aSample = pIdx->aSample;
  77200. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  77201. int iCol;
  77202. for(iCol=0; iCol<pIdx->nColumn; iCol++){
  77203. int i; /* Used to iterate through samples */
  77204. tRowcnt sumEq = 0; /* Sum of the nEq values */
  77205. tRowcnt nSum = 0; /* Number of terms contributing to sumEq */
  77206. tRowcnt avgEq = 0;
  77207. tRowcnt nDLt = pFinal->anDLt[iCol];
  77208. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  77209. ** occur in the stat4 table for this index before pFinal. Set
  77210. ** sumEq to the sum of the nEq values for column iCol for the same
  77211. ** set (adding the value only once where there exist dupicate
  77212. ** prefixes). */
  77213. for(i=0; i<(pIdx->nSample-1); i++){
  77214. if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
  77215. sumEq += aSample[i].anEq[iCol];
  77216. nSum++;
  77217. }
  77218. }
  77219. if( nDLt>nSum ){
  77220. avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
  77221. }
  77222. if( avgEq==0 ) avgEq = 1;
  77223. pIdx->aAvgEq[iCol] = avgEq;
  77224. if( pIdx->nSampleCol==1 ) break;
  77225. }
  77226. }
  77227. }
  77228. /*
  77229. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  77230. ** into the relevant Index.aSample[] arrays.
  77231. **
  77232. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  77233. ** data equivalent to the following (statements are different for stat3,
  77234. ** see the caller of this function for details):
  77235. **
  77236. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  77237. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  77238. **
  77239. ** where %Q is replaced with the database name before the SQL is executed.
  77240. */
  77241. static int loadStatTbl(
  77242. sqlite3 *db, /* Database handle */
  77243. int bStat3, /* Assume single column records only */
  77244. const char *zSql1, /* SQL statement 1 (see above) */
  77245. const char *zSql2, /* SQL statement 2 (see above) */
  77246. const char *zDb /* Database name (e.g. "main") */
  77247. ){
  77248. int rc; /* Result codes from subroutines */
  77249. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  77250. char *zSql; /* Text of the SQL statement */
  77251. Index *pPrevIdx = 0; /* Previous index in the loop */
  77252. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  77253. assert( db->lookaside.bEnabled==0 );
  77254. zSql = sqlite3MPrintf(db, zSql1, zDb);
  77255. if( !zSql ){
  77256. return SQLITE_NOMEM;
  77257. }
  77258. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  77259. sqlite3DbFree(db, zSql);
  77260. if( rc ) return rc;
  77261. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  77262. int nIdxCol = 1; /* Number of columns in stat4 records */
  77263. int nAvgCol = 1; /* Number of entries in Index.aAvgEq */
  77264. char *zIndex; /* Index name */
  77265. Index *pIdx; /* Pointer to the index object */
  77266. int nSample; /* Number of samples */
  77267. int nByte; /* Bytes of space required */
  77268. int i; /* Bytes of space required */
  77269. tRowcnt *pSpace;
  77270. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  77271. if( zIndex==0 ) continue;
  77272. nSample = sqlite3_column_int(pStmt, 1);
  77273. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  77274. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  77275. /* Index.nSample is non-zero at this point if data has already been
  77276. ** loaded from the stat4 table. In this case ignore stat3 data. */
  77277. if( pIdx==0 || pIdx->nSample ) continue;
  77278. if( bStat3==0 ){
  77279. nIdxCol = pIdx->nColumn+1;
  77280. nAvgCol = pIdx->nColumn;
  77281. }
  77282. pIdx->nSampleCol = nIdxCol;
  77283. nByte = sizeof(IndexSample) * nSample;
  77284. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  77285. nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  77286. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  77287. if( pIdx->aSample==0 ){
  77288. sqlite3_finalize(pStmt);
  77289. return SQLITE_NOMEM;
  77290. }
  77291. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  77292. pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
  77293. for(i=0; i<nSample; i++){
  77294. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  77295. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  77296. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  77297. }
  77298. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  77299. }
  77300. rc = sqlite3_finalize(pStmt);
  77301. if( rc ) return rc;
  77302. zSql = sqlite3MPrintf(db, zSql2, zDb);
  77303. if( !zSql ){
  77304. return SQLITE_NOMEM;
  77305. }
  77306. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  77307. sqlite3DbFree(db, zSql);
  77308. if( rc ) return rc;
  77309. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  77310. char *zIndex; /* Index name */
  77311. Index *pIdx; /* Pointer to the index object */
  77312. int nCol = 1; /* Number of columns in index */
  77313. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  77314. if( zIndex==0 ) continue;
  77315. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  77316. if( pIdx==0 ) continue;
  77317. /* This next condition is true if data has already been loaded from
  77318. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  77319. nCol = pIdx->nSampleCol;
  77320. if( bStat3 && nCol>1 ) continue;
  77321. if( pIdx!=pPrevIdx ){
  77322. initAvgEq(pPrevIdx);
  77323. pPrevIdx = pIdx;
  77324. }
  77325. pSample = &pIdx->aSample[pIdx->nSample];
  77326. decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0);
  77327. decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0);
  77328. decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0);
  77329. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  77330. ** This is in case the sample record is corrupted. In that case, the
  77331. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  77332. ** end of the allocated buffer before it realizes it is dealing with
  77333. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  77334. ** a buffer overread. */
  77335. pSample->n = sqlite3_column_bytes(pStmt, 4);
  77336. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  77337. if( pSample->p==0 ){
  77338. sqlite3_finalize(pStmt);
  77339. return SQLITE_NOMEM;
  77340. }
  77341. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  77342. pIdx->nSample++;
  77343. }
  77344. rc = sqlite3_finalize(pStmt);
  77345. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  77346. return rc;
  77347. }
  77348. /*
  77349. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  77350. ** the Index.aSample[] arrays of all indices.
  77351. */
  77352. static int loadStat4(sqlite3 *db, const char *zDb){
  77353. int rc = SQLITE_OK; /* Result codes from subroutines */
  77354. assert( db->lookaside.bEnabled==0 );
  77355. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  77356. rc = loadStatTbl(db, 0,
  77357. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  77358. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  77359. zDb
  77360. );
  77361. }
  77362. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  77363. rc = loadStatTbl(db, 1,
  77364. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  77365. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  77366. zDb
  77367. );
  77368. }
  77369. return rc;
  77370. }
  77371. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  77372. /*
  77373. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  77374. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  77375. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  77376. ** Index.aSample[] arrays.
  77377. **
  77378. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  77379. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  77380. ** during compilation and the sqlite_stat3/4 table is present, no data is
  77381. ** read from it.
  77382. **
  77383. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  77384. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  77385. ** returned. However, in this case, data is read from the sqlite_stat1
  77386. ** table (if it is present) before returning.
  77387. **
  77388. ** If an OOM error occurs, this function always sets db->mallocFailed.
  77389. ** This means if the caller does not care about other errors, the return
  77390. ** code may be ignored.
  77391. */
  77392. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  77393. analysisInfo sInfo;
  77394. HashElem *i;
  77395. char *zSql;
  77396. int rc;
  77397. assert( iDb>=0 && iDb<db->nDb );
  77398. assert( db->aDb[iDb].pBt!=0 );
  77399. /* Clear any prior statistics */
  77400. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  77401. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  77402. Index *pIdx = sqliteHashData(i);
  77403. sqlite3DefaultRowEst(pIdx);
  77404. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  77405. sqlite3DeleteIndexSamples(db, pIdx);
  77406. pIdx->aSample = 0;
  77407. #endif
  77408. }
  77409. /* Check to make sure the sqlite_stat1 table exists */
  77410. sInfo.db = db;
  77411. sInfo.zDatabase = db->aDb[iDb].zName;
  77412. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  77413. return SQLITE_ERROR;
  77414. }
  77415. /* Load new statistics out of the sqlite_stat1 table */
  77416. zSql = sqlite3MPrintf(db,
  77417. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  77418. if( zSql==0 ){
  77419. rc = SQLITE_NOMEM;
  77420. }else{
  77421. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  77422. sqlite3DbFree(db, zSql);
  77423. }
  77424. /* Load the statistics from the sqlite_stat4 table. */
  77425. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  77426. if( rc==SQLITE_OK ){
  77427. int lookasideEnabled = db->lookaside.bEnabled;
  77428. db->lookaside.bEnabled = 0;
  77429. rc = loadStat4(db, sInfo.zDatabase);
  77430. db->lookaside.bEnabled = lookasideEnabled;
  77431. }
  77432. #endif
  77433. if( rc==SQLITE_NOMEM ){
  77434. db->mallocFailed = 1;
  77435. }
  77436. return rc;
  77437. }
  77438. #endif /* SQLITE_OMIT_ANALYZE */
  77439. /************** End of analyze.c *********************************************/
  77440. /************** Begin file attach.c ******************************************/
  77441. /*
  77442. ** 2003 April 6
  77443. **
  77444. ** The author disclaims copyright to this source code. In place of
  77445. ** a legal notice, here is a blessing:
  77446. **
  77447. ** May you do good and not evil.
  77448. ** May you find forgiveness for yourself and forgive others.
  77449. ** May you share freely, never taking more than you give.
  77450. **
  77451. *************************************************************************
  77452. ** This file contains code used to implement the ATTACH and DETACH commands.
  77453. */
  77454. #ifndef SQLITE_OMIT_ATTACH
  77455. /*
  77456. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  77457. ** is slightly different from resolving a normal SQL expression, because simple
  77458. ** identifiers are treated as strings, not possible column names or aliases.
  77459. **
  77460. ** i.e. if the parser sees:
  77461. **
  77462. ** ATTACH DATABASE abc AS def
  77463. **
  77464. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  77465. ** looking for columns of the same name.
  77466. **
  77467. ** This only applies to the root node of pExpr, so the statement:
  77468. **
  77469. ** ATTACH DATABASE abc||def AS 'db2'
  77470. **
  77471. ** will fail because neither abc or def can be resolved.
  77472. */
  77473. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  77474. {
  77475. int rc = SQLITE_OK;
  77476. if( pExpr ){
  77477. if( pExpr->op!=TK_ID ){
  77478. rc = sqlite3ResolveExprNames(pName, pExpr);
  77479. if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
  77480. sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
  77481. return SQLITE_ERROR;
  77482. }
  77483. }else{
  77484. pExpr->op = TK_STRING;
  77485. }
  77486. }
  77487. return rc;
  77488. }
  77489. /*
  77490. ** An SQL user-function registered to do the work of an ATTACH statement. The
  77491. ** three arguments to the function come directly from an attach statement:
  77492. **
  77493. ** ATTACH DATABASE x AS y KEY z
  77494. **
  77495. ** SELECT sqlite_attach(x, y, z)
  77496. **
  77497. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  77498. ** third argument.
  77499. */
  77500. static void attachFunc(
  77501. sqlite3_context *context,
  77502. int NotUsed,
  77503. sqlite3_value **argv
  77504. ){
  77505. int i;
  77506. int rc = 0;
  77507. sqlite3 *db = sqlite3_context_db_handle(context);
  77508. const char *zName;
  77509. const char *zFile;
  77510. char *zPath = 0;
  77511. char *zErr = 0;
  77512. unsigned int flags;
  77513. Db *aNew;
  77514. char *zErrDyn = 0;
  77515. sqlite3_vfs *pVfs;
  77516. UNUSED_PARAMETER(NotUsed);
  77517. zFile = (const char *)sqlite3_value_text(argv[0]);
  77518. zName = (const char *)sqlite3_value_text(argv[1]);
  77519. if( zFile==0 ) zFile = "";
  77520. if( zName==0 ) zName = "";
  77521. /* Check for the following errors:
  77522. **
  77523. ** * Too many attached databases,
  77524. ** * Transaction currently open
  77525. ** * Specified database name already being used.
  77526. */
  77527. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  77528. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  77529. db->aLimit[SQLITE_LIMIT_ATTACHED]
  77530. );
  77531. goto attach_error;
  77532. }
  77533. if( !db->autoCommit ){
  77534. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  77535. goto attach_error;
  77536. }
  77537. for(i=0; i<db->nDb; i++){
  77538. char *z = db->aDb[i].zName;
  77539. assert( z && zName );
  77540. if( sqlite3StrICmp(z, zName)==0 ){
  77541. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  77542. goto attach_error;
  77543. }
  77544. }
  77545. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  77546. ** hash tables.
  77547. */
  77548. if( db->aDb==db->aDbStatic ){
  77549. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  77550. if( aNew==0 ) return;
  77551. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  77552. }else{
  77553. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  77554. if( aNew==0 ) return;
  77555. }
  77556. db->aDb = aNew;
  77557. aNew = &db->aDb[db->nDb];
  77558. memset(aNew, 0, sizeof(*aNew));
  77559. /* Open the database file. If the btree is successfully opened, use
  77560. ** it to obtain the database schema. At this point the schema may
  77561. ** or may not be initialized.
  77562. */
  77563. flags = db->openFlags;
  77564. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  77565. if( rc!=SQLITE_OK ){
  77566. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  77567. sqlite3_result_error(context, zErr, -1);
  77568. sqlite3_free(zErr);
  77569. return;
  77570. }
  77571. assert( pVfs );
  77572. flags |= SQLITE_OPEN_MAIN_DB;
  77573. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  77574. sqlite3_free( zPath );
  77575. db->nDb++;
  77576. if( rc==SQLITE_CONSTRAINT ){
  77577. rc = SQLITE_ERROR;
  77578. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  77579. }else if( rc==SQLITE_OK ){
  77580. Pager *pPager;
  77581. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  77582. if( !aNew->pSchema ){
  77583. rc = SQLITE_NOMEM;
  77584. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  77585. zErrDyn = sqlite3MPrintf(db,
  77586. "attached databases must use the same text encoding as main database");
  77587. rc = SQLITE_ERROR;
  77588. }
  77589. pPager = sqlite3BtreePager(aNew->pBt);
  77590. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  77591. sqlite3BtreeSecureDelete(aNew->pBt,
  77592. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  77593. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  77594. sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
  77595. #endif
  77596. }
  77597. aNew->safety_level = 3;
  77598. aNew->zName = sqlite3DbStrDup(db, zName);
  77599. if( rc==SQLITE_OK && aNew->zName==0 ){
  77600. rc = SQLITE_NOMEM;
  77601. }
  77602. #ifdef SQLITE_HAS_CODEC
  77603. if( rc==SQLITE_OK ){
  77604. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  77605. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  77606. int nKey;
  77607. char *zKey;
  77608. int t = sqlite3_value_type(argv[2]);
  77609. switch( t ){
  77610. case SQLITE_INTEGER:
  77611. case SQLITE_FLOAT:
  77612. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  77613. rc = SQLITE_ERROR;
  77614. break;
  77615. case SQLITE_TEXT:
  77616. case SQLITE_BLOB:
  77617. nKey = sqlite3_value_bytes(argv[2]);
  77618. zKey = (char *)sqlite3_value_blob(argv[2]);
  77619. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  77620. break;
  77621. case SQLITE_NULL:
  77622. /* No key specified. Use the key from the main database */
  77623. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  77624. if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
  77625. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  77626. }
  77627. break;
  77628. }
  77629. }
  77630. #endif
  77631. /* If the file was opened successfully, read the schema for the new database.
  77632. ** If this fails, or if opening the file failed, then close the file and
  77633. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  77634. ** we found it.
  77635. */
  77636. if( rc==SQLITE_OK ){
  77637. sqlite3BtreeEnterAll(db);
  77638. rc = sqlite3Init(db, &zErrDyn);
  77639. sqlite3BtreeLeaveAll(db);
  77640. }
  77641. if( rc ){
  77642. int iDb = db->nDb - 1;
  77643. assert( iDb>=2 );
  77644. if( db->aDb[iDb].pBt ){
  77645. sqlite3BtreeClose(db->aDb[iDb].pBt);
  77646. db->aDb[iDb].pBt = 0;
  77647. db->aDb[iDb].pSchema = 0;
  77648. }
  77649. sqlite3ResetAllSchemasOfConnection(db);
  77650. db->nDb = iDb;
  77651. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  77652. db->mallocFailed = 1;
  77653. sqlite3DbFree(db, zErrDyn);
  77654. zErrDyn = sqlite3MPrintf(db, "out of memory");
  77655. }else if( zErrDyn==0 ){
  77656. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  77657. }
  77658. goto attach_error;
  77659. }
  77660. return;
  77661. attach_error:
  77662. /* Return an error if we get here */
  77663. if( zErrDyn ){
  77664. sqlite3_result_error(context, zErrDyn, -1);
  77665. sqlite3DbFree(db, zErrDyn);
  77666. }
  77667. if( rc ) sqlite3_result_error_code(context, rc);
  77668. }
  77669. /*
  77670. ** An SQL user-function registered to do the work of an DETACH statement. The
  77671. ** three arguments to the function come directly from a detach statement:
  77672. **
  77673. ** DETACH DATABASE x
  77674. **
  77675. ** SELECT sqlite_detach(x)
  77676. */
  77677. static void detachFunc(
  77678. sqlite3_context *context,
  77679. int NotUsed,
  77680. sqlite3_value **argv
  77681. ){
  77682. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  77683. sqlite3 *db = sqlite3_context_db_handle(context);
  77684. int i;
  77685. Db *pDb = 0;
  77686. char zErr[128];
  77687. UNUSED_PARAMETER(NotUsed);
  77688. if( zName==0 ) zName = "";
  77689. for(i=0; i<db->nDb; i++){
  77690. pDb = &db->aDb[i];
  77691. if( pDb->pBt==0 ) continue;
  77692. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  77693. }
  77694. if( i>=db->nDb ){
  77695. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  77696. goto detach_error;
  77697. }
  77698. if( i<2 ){
  77699. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  77700. goto detach_error;
  77701. }
  77702. if( !db->autoCommit ){
  77703. sqlite3_snprintf(sizeof(zErr), zErr,
  77704. "cannot DETACH database within transaction");
  77705. goto detach_error;
  77706. }
  77707. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  77708. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  77709. goto detach_error;
  77710. }
  77711. sqlite3BtreeClose(pDb->pBt);
  77712. pDb->pBt = 0;
  77713. pDb->pSchema = 0;
  77714. sqlite3ResetAllSchemasOfConnection(db);
  77715. return;
  77716. detach_error:
  77717. sqlite3_result_error(context, zErr, -1);
  77718. }
  77719. /*
  77720. ** This procedure generates VDBE code for a single invocation of either the
  77721. ** sqlite_detach() or sqlite_attach() SQL user functions.
  77722. */
  77723. static void codeAttach(
  77724. Parse *pParse, /* The parser context */
  77725. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  77726. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  77727. Expr *pAuthArg, /* Expression to pass to authorization callback */
  77728. Expr *pFilename, /* Name of database file */
  77729. Expr *pDbname, /* Name of the database to use internally */
  77730. Expr *pKey /* Database key for encryption extension */
  77731. ){
  77732. int rc;
  77733. NameContext sName;
  77734. Vdbe *v;
  77735. sqlite3* db = pParse->db;
  77736. int regArgs;
  77737. memset(&sName, 0, sizeof(NameContext));
  77738. sName.pParse = pParse;
  77739. if(
  77740. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  77741. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  77742. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  77743. ){
  77744. pParse->nErr++;
  77745. goto attach_end;
  77746. }
  77747. #ifndef SQLITE_OMIT_AUTHORIZATION
  77748. if( pAuthArg ){
  77749. char *zAuthArg;
  77750. if( pAuthArg->op==TK_STRING ){
  77751. zAuthArg = pAuthArg->u.zToken;
  77752. }else{
  77753. zAuthArg = 0;
  77754. }
  77755. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  77756. if(rc!=SQLITE_OK ){
  77757. goto attach_end;
  77758. }
  77759. }
  77760. #endif /* SQLITE_OMIT_AUTHORIZATION */
  77761. v = sqlite3GetVdbe(pParse);
  77762. regArgs = sqlite3GetTempRange(pParse, 4);
  77763. sqlite3ExprCode(pParse, pFilename, regArgs);
  77764. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  77765. sqlite3ExprCode(pParse, pKey, regArgs+2);
  77766. assert( v || db->mallocFailed );
  77767. if( v ){
  77768. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  77769. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  77770. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  77771. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  77772. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  77773. ** statement only). For DETACH, set it to false (expire all existing
  77774. ** statements).
  77775. */
  77776. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  77777. }
  77778. attach_end:
  77779. sqlite3ExprDelete(db, pFilename);
  77780. sqlite3ExprDelete(db, pDbname);
  77781. sqlite3ExprDelete(db, pKey);
  77782. }
  77783. /*
  77784. ** Called by the parser to compile a DETACH statement.
  77785. **
  77786. ** DETACH pDbname
  77787. */
  77788. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  77789. static const FuncDef detach_func = {
  77790. 1, /* nArg */
  77791. SQLITE_UTF8, /* funcFlags */
  77792. 0, /* pUserData */
  77793. 0, /* pNext */
  77794. detachFunc, /* xFunc */
  77795. 0, /* xStep */
  77796. 0, /* xFinalize */
  77797. "sqlite_detach", /* zName */
  77798. 0, /* pHash */
  77799. 0 /* pDestructor */
  77800. };
  77801. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  77802. }
  77803. /*
  77804. ** Called by the parser to compile an ATTACH statement.
  77805. **
  77806. ** ATTACH p AS pDbname KEY pKey
  77807. */
  77808. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  77809. static const FuncDef attach_func = {
  77810. 3, /* nArg */
  77811. SQLITE_UTF8, /* funcFlags */
  77812. 0, /* pUserData */
  77813. 0, /* pNext */
  77814. attachFunc, /* xFunc */
  77815. 0, /* xStep */
  77816. 0, /* xFinalize */
  77817. "sqlite_attach", /* zName */
  77818. 0, /* pHash */
  77819. 0 /* pDestructor */
  77820. };
  77821. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  77822. }
  77823. #endif /* SQLITE_OMIT_ATTACH */
  77824. /*
  77825. ** Initialize a DbFixer structure. This routine must be called prior
  77826. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  77827. */
  77828. SQLITE_PRIVATE void sqlite3FixInit(
  77829. DbFixer *pFix, /* The fixer to be initialized */
  77830. Parse *pParse, /* Error messages will be written here */
  77831. int iDb, /* This is the database that must be used */
  77832. const char *zType, /* "view", "trigger", or "index" */
  77833. const Token *pName /* Name of the view, trigger, or index */
  77834. ){
  77835. sqlite3 *db;
  77836. db = pParse->db;
  77837. assert( db->nDb>iDb );
  77838. pFix->pParse = pParse;
  77839. pFix->zDb = db->aDb[iDb].zName;
  77840. pFix->pSchema = db->aDb[iDb].pSchema;
  77841. pFix->zType = zType;
  77842. pFix->pName = pName;
  77843. pFix->bVarOnly = (iDb==1);
  77844. }
  77845. /*
  77846. ** The following set of routines walk through the parse tree and assign
  77847. ** a specific database to all table references where the database name
  77848. ** was left unspecified in the original SQL statement. The pFix structure
  77849. ** must have been initialized by a prior call to sqlite3FixInit().
  77850. **
  77851. ** These routines are used to make sure that an index, trigger, or
  77852. ** view in one database does not refer to objects in a different database.
  77853. ** (Exception: indices, triggers, and views in the TEMP database are
  77854. ** allowed to refer to anything.) If a reference is explicitly made
  77855. ** to an object in a different database, an error message is added to
  77856. ** pParse->zErrMsg and these routines return non-zero. If everything
  77857. ** checks out, these routines return 0.
  77858. */
  77859. SQLITE_PRIVATE int sqlite3FixSrcList(
  77860. DbFixer *pFix, /* Context of the fixation */
  77861. SrcList *pList /* The Source list to check and modify */
  77862. ){
  77863. int i;
  77864. const char *zDb;
  77865. struct SrcList_item *pItem;
  77866. if( NEVER(pList==0) ) return 0;
  77867. zDb = pFix->zDb;
  77868. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  77869. if( pFix->bVarOnly==0 ){
  77870. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  77871. sqlite3ErrorMsg(pFix->pParse,
  77872. "%s %T cannot reference objects in database %s",
  77873. pFix->zType, pFix->pName, pItem->zDatabase);
  77874. return 1;
  77875. }
  77876. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  77877. pItem->zDatabase = 0;
  77878. pItem->pSchema = pFix->pSchema;
  77879. }
  77880. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  77881. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  77882. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  77883. #endif
  77884. }
  77885. return 0;
  77886. }
  77887. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  77888. SQLITE_PRIVATE int sqlite3FixSelect(
  77889. DbFixer *pFix, /* Context of the fixation */
  77890. Select *pSelect /* The SELECT statement to be fixed to one database */
  77891. ){
  77892. while( pSelect ){
  77893. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  77894. return 1;
  77895. }
  77896. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  77897. return 1;
  77898. }
  77899. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  77900. return 1;
  77901. }
  77902. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  77903. return 1;
  77904. }
  77905. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  77906. return 1;
  77907. }
  77908. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  77909. return 1;
  77910. }
  77911. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  77912. return 1;
  77913. }
  77914. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  77915. return 1;
  77916. }
  77917. pSelect = pSelect->pPrior;
  77918. }
  77919. return 0;
  77920. }
  77921. SQLITE_PRIVATE int sqlite3FixExpr(
  77922. DbFixer *pFix, /* Context of the fixation */
  77923. Expr *pExpr /* The expression to be fixed to one database */
  77924. ){
  77925. while( pExpr ){
  77926. if( pExpr->op==TK_VARIABLE ){
  77927. if( pFix->pParse->db->init.busy ){
  77928. pExpr->op = TK_NULL;
  77929. }else{
  77930. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  77931. return 1;
  77932. }
  77933. }
  77934. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  77935. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  77936. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  77937. }else{
  77938. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  77939. }
  77940. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  77941. return 1;
  77942. }
  77943. pExpr = pExpr->pLeft;
  77944. }
  77945. return 0;
  77946. }
  77947. SQLITE_PRIVATE int sqlite3FixExprList(
  77948. DbFixer *pFix, /* Context of the fixation */
  77949. ExprList *pList /* The expression to be fixed to one database */
  77950. ){
  77951. int i;
  77952. struct ExprList_item *pItem;
  77953. if( pList==0 ) return 0;
  77954. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  77955. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  77956. return 1;
  77957. }
  77958. }
  77959. return 0;
  77960. }
  77961. #endif
  77962. #ifndef SQLITE_OMIT_TRIGGER
  77963. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  77964. DbFixer *pFix, /* Context of the fixation */
  77965. TriggerStep *pStep /* The trigger step be fixed to one database */
  77966. ){
  77967. while( pStep ){
  77968. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  77969. return 1;
  77970. }
  77971. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  77972. return 1;
  77973. }
  77974. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  77975. return 1;
  77976. }
  77977. pStep = pStep->pNext;
  77978. }
  77979. return 0;
  77980. }
  77981. #endif
  77982. /************** End of attach.c **********************************************/
  77983. /************** Begin file auth.c ********************************************/
  77984. /*
  77985. ** 2003 January 11
  77986. **
  77987. ** The author disclaims copyright to this source code. In place of
  77988. ** a legal notice, here is a blessing:
  77989. **
  77990. ** May you do good and not evil.
  77991. ** May you find forgiveness for yourself and forgive others.
  77992. ** May you share freely, never taking more than you give.
  77993. **
  77994. *************************************************************************
  77995. ** This file contains code used to implement the sqlite3_set_authorizer()
  77996. ** API. This facility is an optional feature of the library. Embedded
  77997. ** systems that do not need this facility may omit it by recompiling
  77998. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  77999. */
  78000. /*
  78001. ** All of the code in this file may be omitted by defining a single
  78002. ** macro.
  78003. */
  78004. #ifndef SQLITE_OMIT_AUTHORIZATION
  78005. /*
  78006. ** Set or clear the access authorization function.
  78007. **
  78008. ** The access authorization function is be called during the compilation
  78009. ** phase to verify that the user has read and/or write access permission on
  78010. ** various fields of the database. The first argument to the auth function
  78011. ** is a copy of the 3rd argument to this routine. The second argument
  78012. ** to the auth function is one of these constants:
  78013. **
  78014. ** SQLITE_CREATE_INDEX
  78015. ** SQLITE_CREATE_TABLE
  78016. ** SQLITE_CREATE_TEMP_INDEX
  78017. ** SQLITE_CREATE_TEMP_TABLE
  78018. ** SQLITE_CREATE_TEMP_TRIGGER
  78019. ** SQLITE_CREATE_TEMP_VIEW
  78020. ** SQLITE_CREATE_TRIGGER
  78021. ** SQLITE_CREATE_VIEW
  78022. ** SQLITE_DELETE
  78023. ** SQLITE_DROP_INDEX
  78024. ** SQLITE_DROP_TABLE
  78025. ** SQLITE_DROP_TEMP_INDEX
  78026. ** SQLITE_DROP_TEMP_TABLE
  78027. ** SQLITE_DROP_TEMP_TRIGGER
  78028. ** SQLITE_DROP_TEMP_VIEW
  78029. ** SQLITE_DROP_TRIGGER
  78030. ** SQLITE_DROP_VIEW
  78031. ** SQLITE_INSERT
  78032. ** SQLITE_PRAGMA
  78033. ** SQLITE_READ
  78034. ** SQLITE_SELECT
  78035. ** SQLITE_TRANSACTION
  78036. ** SQLITE_UPDATE
  78037. **
  78038. ** The third and fourth arguments to the auth function are the name of
  78039. ** the table and the column that are being accessed. The auth function
  78040. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  78041. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  78042. ** means that the SQL statement will never-run - the sqlite3_exec() call
  78043. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  78044. ** should run but attempts to read the specified column will return NULL
  78045. ** and attempts to write the column will be ignored.
  78046. **
  78047. ** Setting the auth function to NULL disables this hook. The default
  78048. ** setting of the auth function is NULL.
  78049. */
  78050. SQLITE_API int sqlite3_set_authorizer(
  78051. sqlite3 *db,
  78052. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  78053. void *pArg
  78054. ){
  78055. sqlite3_mutex_enter(db->mutex);
  78056. db->xAuth = xAuth;
  78057. db->pAuthArg = pArg;
  78058. sqlite3ExpirePreparedStatements(db);
  78059. sqlite3_mutex_leave(db->mutex);
  78060. return SQLITE_OK;
  78061. }
  78062. /*
  78063. ** Write an error message into pParse->zErrMsg that explains that the
  78064. ** user-supplied authorization function returned an illegal value.
  78065. */
  78066. static void sqliteAuthBadReturnCode(Parse *pParse){
  78067. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  78068. pParse->rc = SQLITE_ERROR;
  78069. }
  78070. /*
  78071. ** Invoke the authorization callback for permission to read column zCol from
  78072. ** table zTab in database zDb. This function assumes that an authorization
  78073. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  78074. **
  78075. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  78076. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  78077. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  78078. */
  78079. SQLITE_PRIVATE int sqlite3AuthReadCol(
  78080. Parse *pParse, /* The parser context */
  78081. const char *zTab, /* Table name */
  78082. const char *zCol, /* Column name */
  78083. int iDb /* Index of containing database. */
  78084. ){
  78085. sqlite3 *db = pParse->db; /* Database handle */
  78086. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  78087. int rc; /* Auth callback return code */
  78088. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
  78089. if( rc==SQLITE_DENY ){
  78090. if( db->nDb>2 || iDb!=0 ){
  78091. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  78092. }else{
  78093. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  78094. }
  78095. pParse->rc = SQLITE_AUTH;
  78096. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  78097. sqliteAuthBadReturnCode(pParse);
  78098. }
  78099. return rc;
  78100. }
  78101. /*
  78102. ** The pExpr should be a TK_COLUMN expression. The table referred to
  78103. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  78104. ** Check to see if it is OK to read this particular column.
  78105. **
  78106. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  78107. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  78108. ** then generate an error.
  78109. */
  78110. SQLITE_PRIVATE void sqlite3AuthRead(
  78111. Parse *pParse, /* The parser context */
  78112. Expr *pExpr, /* The expression to check authorization on */
  78113. Schema *pSchema, /* The schema of the expression */
  78114. SrcList *pTabList /* All table that pExpr might refer to */
  78115. ){
  78116. sqlite3 *db = pParse->db;
  78117. Table *pTab = 0; /* The table being read */
  78118. const char *zCol; /* Name of the column of the table */
  78119. int iSrc; /* Index in pTabList->a[] of table being read */
  78120. int iDb; /* The index of the database the expression refers to */
  78121. int iCol; /* Index of column in table */
  78122. if( db->xAuth==0 ) return;
  78123. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  78124. if( iDb<0 ){
  78125. /* An attempt to read a column out of a subquery or other
  78126. ** temporary table. */
  78127. return;
  78128. }
  78129. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  78130. if( pExpr->op==TK_TRIGGER ){
  78131. pTab = pParse->pTriggerTab;
  78132. }else{
  78133. assert( pTabList );
  78134. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  78135. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  78136. pTab = pTabList->a[iSrc].pTab;
  78137. break;
  78138. }
  78139. }
  78140. }
  78141. iCol = pExpr->iColumn;
  78142. if( NEVER(pTab==0) ) return;
  78143. if( iCol>=0 ){
  78144. assert( iCol<pTab->nCol );
  78145. zCol = pTab->aCol[iCol].zName;
  78146. }else if( pTab->iPKey>=0 ){
  78147. assert( pTab->iPKey<pTab->nCol );
  78148. zCol = pTab->aCol[pTab->iPKey].zName;
  78149. }else{
  78150. zCol = "ROWID";
  78151. }
  78152. assert( iDb>=0 && iDb<db->nDb );
  78153. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  78154. pExpr->op = TK_NULL;
  78155. }
  78156. }
  78157. /*
  78158. ** Do an authorization check using the code and arguments given. Return
  78159. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  78160. ** is returned, then the error count and error message in pParse are
  78161. ** modified appropriately.
  78162. */
  78163. SQLITE_PRIVATE int sqlite3AuthCheck(
  78164. Parse *pParse,
  78165. int code,
  78166. const char *zArg1,
  78167. const char *zArg2,
  78168. const char *zArg3
  78169. ){
  78170. sqlite3 *db = pParse->db;
  78171. int rc;
  78172. /* Don't do any authorization checks if the database is initialising
  78173. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  78174. */
  78175. if( db->init.busy || IN_DECLARE_VTAB ){
  78176. return SQLITE_OK;
  78177. }
  78178. if( db->xAuth==0 ){
  78179. return SQLITE_OK;
  78180. }
  78181. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  78182. if( rc==SQLITE_DENY ){
  78183. sqlite3ErrorMsg(pParse, "not authorized");
  78184. pParse->rc = SQLITE_AUTH;
  78185. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  78186. rc = SQLITE_DENY;
  78187. sqliteAuthBadReturnCode(pParse);
  78188. }
  78189. return rc;
  78190. }
  78191. /*
  78192. ** Push an authorization context. After this routine is called, the
  78193. ** zArg3 argument to authorization callbacks will be zContext until
  78194. ** popped. Or if pParse==0, this routine is a no-op.
  78195. */
  78196. SQLITE_PRIVATE void sqlite3AuthContextPush(
  78197. Parse *pParse,
  78198. AuthContext *pContext,
  78199. const char *zContext
  78200. ){
  78201. assert( pParse );
  78202. pContext->pParse = pParse;
  78203. pContext->zAuthContext = pParse->zAuthContext;
  78204. pParse->zAuthContext = zContext;
  78205. }
  78206. /*
  78207. ** Pop an authorization context that was previously pushed
  78208. ** by sqlite3AuthContextPush
  78209. */
  78210. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  78211. if( pContext->pParse ){
  78212. pContext->pParse->zAuthContext = pContext->zAuthContext;
  78213. pContext->pParse = 0;
  78214. }
  78215. }
  78216. #endif /* SQLITE_OMIT_AUTHORIZATION */
  78217. /************** End of auth.c ************************************************/
  78218. /************** Begin file build.c *******************************************/
  78219. /*
  78220. ** 2001 September 15
  78221. **
  78222. ** The author disclaims copyright to this source code. In place of
  78223. ** a legal notice, here is a blessing:
  78224. **
  78225. ** May you do good and not evil.
  78226. ** May you find forgiveness for yourself and forgive others.
  78227. ** May you share freely, never taking more than you give.
  78228. **
  78229. *************************************************************************
  78230. ** This file contains C code routines that are called by the SQLite parser
  78231. ** when syntax rules are reduced. The routines in this file handle the
  78232. ** following kinds of SQL syntax:
  78233. **
  78234. ** CREATE TABLE
  78235. ** DROP TABLE
  78236. ** CREATE INDEX
  78237. ** DROP INDEX
  78238. ** creating ID lists
  78239. ** BEGIN TRANSACTION
  78240. ** COMMIT
  78241. ** ROLLBACK
  78242. */
  78243. /*
  78244. ** This routine is called when a new SQL statement is beginning to
  78245. ** be parsed. Initialize the pParse structure as needed.
  78246. */
  78247. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  78248. pParse->explain = (u8)explainFlag;
  78249. pParse->nVar = 0;
  78250. }
  78251. #ifndef SQLITE_OMIT_SHARED_CACHE
  78252. /*
  78253. ** The TableLock structure is only used by the sqlite3TableLock() and
  78254. ** codeTableLocks() functions.
  78255. */
  78256. struct TableLock {
  78257. int iDb; /* The database containing the table to be locked */
  78258. int iTab; /* The root page of the table to be locked */
  78259. u8 isWriteLock; /* True for write lock. False for a read lock */
  78260. const char *zName; /* Name of the table */
  78261. };
  78262. /*
  78263. ** Record the fact that we want to lock a table at run-time.
  78264. **
  78265. ** The table to be locked has root page iTab and is found in database iDb.
  78266. ** A read or a write lock can be taken depending on isWritelock.
  78267. **
  78268. ** This routine just records the fact that the lock is desired. The
  78269. ** code to make the lock occur is generated by a later call to
  78270. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  78271. */
  78272. SQLITE_PRIVATE void sqlite3TableLock(
  78273. Parse *pParse, /* Parsing context */
  78274. int iDb, /* Index of the database containing the table to lock */
  78275. int iTab, /* Root page number of the table to be locked */
  78276. u8 isWriteLock, /* True for a write lock */
  78277. const char *zName /* Name of the table to be locked */
  78278. ){
  78279. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  78280. int i;
  78281. int nBytes;
  78282. TableLock *p;
  78283. assert( iDb>=0 );
  78284. for(i=0; i<pToplevel->nTableLock; i++){
  78285. p = &pToplevel->aTableLock[i];
  78286. if( p->iDb==iDb && p->iTab==iTab ){
  78287. p->isWriteLock = (p->isWriteLock || isWriteLock);
  78288. return;
  78289. }
  78290. }
  78291. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  78292. pToplevel->aTableLock =
  78293. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  78294. if( pToplevel->aTableLock ){
  78295. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  78296. p->iDb = iDb;
  78297. p->iTab = iTab;
  78298. p->isWriteLock = isWriteLock;
  78299. p->zName = zName;
  78300. }else{
  78301. pToplevel->nTableLock = 0;
  78302. pToplevel->db->mallocFailed = 1;
  78303. }
  78304. }
  78305. /*
  78306. ** Code an OP_TableLock instruction for each table locked by the
  78307. ** statement (configured by calls to sqlite3TableLock()).
  78308. */
  78309. static void codeTableLocks(Parse *pParse){
  78310. int i;
  78311. Vdbe *pVdbe;
  78312. pVdbe = sqlite3GetVdbe(pParse);
  78313. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  78314. for(i=0; i<pParse->nTableLock; i++){
  78315. TableLock *p = &pParse->aTableLock[i];
  78316. int p1 = p->iDb;
  78317. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  78318. p->zName, P4_STATIC);
  78319. }
  78320. }
  78321. #else
  78322. #define codeTableLocks(x)
  78323. #endif
  78324. /*
  78325. ** This routine is called after a single SQL statement has been
  78326. ** parsed and a VDBE program to execute that statement has been
  78327. ** prepared. This routine puts the finishing touches on the
  78328. ** VDBE program and resets the pParse structure for the next
  78329. ** parse.
  78330. **
  78331. ** Note that if an error occurred, it might be the case that
  78332. ** no VDBE code was generated.
  78333. */
  78334. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  78335. sqlite3 *db;
  78336. Vdbe *v;
  78337. assert( pParse->pToplevel==0 );
  78338. db = pParse->db;
  78339. if( db->mallocFailed ) return;
  78340. if( pParse->nested ) return;
  78341. if( pParse->nErr ) return;
  78342. /* Begin by generating some termination code at the end of the
  78343. ** vdbe program
  78344. */
  78345. v = sqlite3GetVdbe(pParse);
  78346. assert( !pParse->isMultiWrite
  78347. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  78348. if( v ){
  78349. sqlite3VdbeAddOp0(v, OP_Halt);
  78350. /* The cookie mask contains one bit for each database file open.
  78351. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  78352. ** set for each database that is used. Generate code to start a
  78353. ** transaction on each used database and to verify the schema cookie
  78354. ** on each used database.
  78355. */
  78356. if( pParse->cookieGoto>0 ){
  78357. yDbMask mask;
  78358. int iDb;
  78359. sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
  78360. for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
  78361. if( (mask & pParse->cookieMask)==0 ) continue;
  78362. sqlite3VdbeUsesBtree(v, iDb);
  78363. sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
  78364. if( db->init.busy==0 ){
  78365. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  78366. sqlite3VdbeAddOp3(v, OP_VerifyCookie,
  78367. iDb, pParse->cookieValue[iDb],
  78368. db->aDb[iDb].pSchema->iGeneration);
  78369. }
  78370. }
  78371. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78372. {
  78373. int i;
  78374. for(i=0; i<pParse->nVtabLock; i++){
  78375. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  78376. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  78377. }
  78378. pParse->nVtabLock = 0;
  78379. }
  78380. #endif
  78381. /* Once all the cookies have been verified and transactions opened,
  78382. ** obtain the required table-locks. This is a no-op unless the
  78383. ** shared-cache feature is enabled.
  78384. */
  78385. codeTableLocks(pParse);
  78386. /* Initialize any AUTOINCREMENT data structures required.
  78387. */
  78388. sqlite3AutoincrementBegin(pParse);
  78389. /* Finally, jump back to the beginning of the executable code. */
  78390. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
  78391. }
  78392. }
  78393. /* Get the VDBE program ready for execution
  78394. */
  78395. if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
  78396. #ifdef SQLITE_DEBUG
  78397. FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  78398. sqlite3VdbeTrace(v, trace);
  78399. #endif
  78400. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  78401. /* A minimum of one cursor is required if autoincrement is used
  78402. * See ticket [a696379c1f08866] */
  78403. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  78404. sqlite3VdbeMakeReady(v, pParse);
  78405. pParse->rc = SQLITE_DONE;
  78406. pParse->colNamesSet = 0;
  78407. }else{
  78408. pParse->rc = SQLITE_ERROR;
  78409. }
  78410. pParse->nTab = 0;
  78411. pParse->nMem = 0;
  78412. pParse->nSet = 0;
  78413. pParse->nVar = 0;
  78414. pParse->cookieMask = 0;
  78415. pParse->cookieGoto = 0;
  78416. }
  78417. /*
  78418. ** Run the parser and code generator recursively in order to generate
  78419. ** code for the SQL statement given onto the end of the pParse context
  78420. ** currently under construction. When the parser is run recursively
  78421. ** this way, the final OP_Halt is not appended and other initialization
  78422. ** and finalization steps are omitted because those are handling by the
  78423. ** outermost parser.
  78424. **
  78425. ** Not everything is nestable. This facility is designed to permit
  78426. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  78427. ** care if you decide to try to use this routine for some other purposes.
  78428. */
  78429. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  78430. va_list ap;
  78431. char *zSql;
  78432. char *zErrMsg = 0;
  78433. sqlite3 *db = pParse->db;
  78434. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  78435. char saveBuf[SAVE_SZ];
  78436. if( pParse->nErr ) return;
  78437. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  78438. va_start(ap, zFormat);
  78439. zSql = sqlite3VMPrintf(db, zFormat, ap);
  78440. va_end(ap);
  78441. if( zSql==0 ){
  78442. return; /* A malloc must have failed */
  78443. }
  78444. pParse->nested++;
  78445. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  78446. memset(&pParse->nVar, 0, SAVE_SZ);
  78447. sqlite3RunParser(pParse, zSql, &zErrMsg);
  78448. sqlite3DbFree(db, zErrMsg);
  78449. sqlite3DbFree(db, zSql);
  78450. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  78451. pParse->nested--;
  78452. }
  78453. /*
  78454. ** Locate the in-memory structure that describes a particular database
  78455. ** table given the name of that table and (optionally) the name of the
  78456. ** database containing the table. Return NULL if not found.
  78457. **
  78458. ** If zDatabase is 0, all databases are searched for the table and the
  78459. ** first matching table is returned. (No checking for duplicate table
  78460. ** names is done.) The search order is TEMP first, then MAIN, then any
  78461. ** auxiliary databases added using the ATTACH command.
  78462. **
  78463. ** See also sqlite3LocateTable().
  78464. */
  78465. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  78466. Table *p = 0;
  78467. int i;
  78468. int nName;
  78469. assert( zName!=0 );
  78470. nName = sqlite3Strlen30(zName);
  78471. /* All mutexes are required for schema access. Make sure we hold them. */
  78472. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  78473. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  78474. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  78475. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  78476. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  78477. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
  78478. if( p ) break;
  78479. }
  78480. return p;
  78481. }
  78482. /*
  78483. ** Locate the in-memory structure that describes a particular database
  78484. ** table given the name of that table and (optionally) the name of the
  78485. ** database containing the table. Return NULL if not found. Also leave an
  78486. ** error message in pParse->zErrMsg.
  78487. **
  78488. ** The difference between this routine and sqlite3FindTable() is that this
  78489. ** routine leaves an error message in pParse->zErrMsg where
  78490. ** sqlite3FindTable() does not.
  78491. */
  78492. SQLITE_PRIVATE Table *sqlite3LocateTable(
  78493. Parse *pParse, /* context in which to report errors */
  78494. int isView, /* True if looking for a VIEW rather than a TABLE */
  78495. const char *zName, /* Name of the table we are looking for */
  78496. const char *zDbase /* Name of the database. Might be NULL */
  78497. ){
  78498. Table *p;
  78499. /* Read the database schema. If an error occurs, leave an error message
  78500. ** and code in pParse and return NULL. */
  78501. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  78502. return 0;
  78503. }
  78504. p = sqlite3FindTable(pParse->db, zName, zDbase);
  78505. if( p==0 ){
  78506. const char *zMsg = isView ? "no such view" : "no such table";
  78507. if( zDbase ){
  78508. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  78509. }else{
  78510. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  78511. }
  78512. pParse->checkSchema = 1;
  78513. }
  78514. return p;
  78515. }
  78516. /*
  78517. ** Locate the table identified by *p.
  78518. **
  78519. ** This is a wrapper around sqlite3LocateTable(). The difference between
  78520. ** sqlite3LocateTable() and this function is that this function restricts
  78521. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  78522. ** non-NULL if it is part of a view or trigger program definition. See
  78523. ** sqlite3FixSrcList() for details.
  78524. */
  78525. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  78526. Parse *pParse,
  78527. int isView,
  78528. struct SrcList_item *p
  78529. ){
  78530. const char *zDb;
  78531. assert( p->pSchema==0 || p->zDatabase==0 );
  78532. if( p->pSchema ){
  78533. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  78534. zDb = pParse->db->aDb[iDb].zName;
  78535. }else{
  78536. zDb = p->zDatabase;
  78537. }
  78538. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  78539. }
  78540. /*
  78541. ** Locate the in-memory structure that describes
  78542. ** a particular index given the name of that index
  78543. ** and the name of the database that contains the index.
  78544. ** Return NULL if not found.
  78545. **
  78546. ** If zDatabase is 0, all databases are searched for the
  78547. ** table and the first matching index is returned. (No checking
  78548. ** for duplicate index names is done.) The search order is
  78549. ** TEMP first, then MAIN, then any auxiliary databases added
  78550. ** using the ATTACH command.
  78551. */
  78552. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  78553. Index *p = 0;
  78554. int i;
  78555. int nName = sqlite3Strlen30(zName);
  78556. /* All mutexes are required for schema access. Make sure we hold them. */
  78557. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  78558. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  78559. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  78560. Schema *pSchema = db->aDb[j].pSchema;
  78561. assert( pSchema );
  78562. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  78563. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  78564. p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
  78565. if( p ) break;
  78566. }
  78567. return p;
  78568. }
  78569. /*
  78570. ** Reclaim the memory used by an index
  78571. */
  78572. static void freeIndex(sqlite3 *db, Index *p){
  78573. #ifndef SQLITE_OMIT_ANALYZE
  78574. sqlite3DeleteIndexSamples(db, p);
  78575. #endif
  78576. sqlite3ExprDelete(db, p->pPartIdxWhere);
  78577. sqlite3DbFree(db, p->zColAff);
  78578. sqlite3DbFree(db, p);
  78579. }
  78580. /*
  78581. ** For the index called zIdxName which is found in the database iDb,
  78582. ** unlike that index from its Table then remove the index from
  78583. ** the index hash table and free all memory structures associated
  78584. ** with the index.
  78585. */
  78586. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  78587. Index *pIndex;
  78588. int len;
  78589. Hash *pHash;
  78590. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  78591. pHash = &db->aDb[iDb].pSchema->idxHash;
  78592. len = sqlite3Strlen30(zIdxName);
  78593. pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
  78594. if( ALWAYS(pIndex) ){
  78595. if( pIndex->pTable->pIndex==pIndex ){
  78596. pIndex->pTable->pIndex = pIndex->pNext;
  78597. }else{
  78598. Index *p;
  78599. /* Justification of ALWAYS(); The index must be on the list of
  78600. ** indices. */
  78601. p = pIndex->pTable->pIndex;
  78602. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  78603. if( ALWAYS(p && p->pNext==pIndex) ){
  78604. p->pNext = pIndex->pNext;
  78605. }
  78606. }
  78607. freeIndex(db, pIndex);
  78608. }
  78609. db->flags |= SQLITE_InternChanges;
  78610. }
  78611. /*
  78612. ** Look through the list of open database files in db->aDb[] and if
  78613. ** any have been closed, remove them from the list. Reallocate the
  78614. ** db->aDb[] structure to a smaller size, if possible.
  78615. **
  78616. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  78617. ** are never candidates for being collapsed.
  78618. */
  78619. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  78620. int i, j;
  78621. for(i=j=2; i<db->nDb; i++){
  78622. struct Db *pDb = &db->aDb[i];
  78623. if( pDb->pBt==0 ){
  78624. sqlite3DbFree(db, pDb->zName);
  78625. pDb->zName = 0;
  78626. continue;
  78627. }
  78628. if( j<i ){
  78629. db->aDb[j] = db->aDb[i];
  78630. }
  78631. j++;
  78632. }
  78633. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  78634. db->nDb = j;
  78635. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  78636. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  78637. sqlite3DbFree(db, db->aDb);
  78638. db->aDb = db->aDbStatic;
  78639. }
  78640. }
  78641. /*
  78642. ** Reset the schema for the database at index iDb. Also reset the
  78643. ** TEMP schema.
  78644. */
  78645. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  78646. Db *pDb;
  78647. assert( iDb<db->nDb );
  78648. /* Case 1: Reset the single schema identified by iDb */
  78649. pDb = &db->aDb[iDb];
  78650. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  78651. assert( pDb->pSchema!=0 );
  78652. sqlite3SchemaClear(pDb->pSchema);
  78653. /* If any database other than TEMP is reset, then also reset TEMP
  78654. ** since TEMP might be holding triggers that reference tables in the
  78655. ** other database.
  78656. */
  78657. if( iDb!=1 ){
  78658. pDb = &db->aDb[1];
  78659. assert( pDb->pSchema!=0 );
  78660. sqlite3SchemaClear(pDb->pSchema);
  78661. }
  78662. return;
  78663. }
  78664. /*
  78665. ** Erase all schema information from all attached databases (including
  78666. ** "main" and "temp") for a single database connection.
  78667. */
  78668. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  78669. int i;
  78670. sqlite3BtreeEnterAll(db);
  78671. for(i=0; i<db->nDb; i++){
  78672. Db *pDb = &db->aDb[i];
  78673. if( pDb->pSchema ){
  78674. sqlite3SchemaClear(pDb->pSchema);
  78675. }
  78676. }
  78677. db->flags &= ~SQLITE_InternChanges;
  78678. sqlite3VtabUnlockList(db);
  78679. sqlite3BtreeLeaveAll(db);
  78680. sqlite3CollapseDatabaseArray(db);
  78681. }
  78682. /*
  78683. ** This routine is called when a commit occurs.
  78684. */
  78685. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  78686. db->flags &= ~SQLITE_InternChanges;
  78687. }
  78688. /*
  78689. ** Delete memory allocated for the column names of a table or view (the
  78690. ** Table.aCol[] array).
  78691. */
  78692. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  78693. int i;
  78694. Column *pCol;
  78695. assert( pTable!=0 );
  78696. if( (pCol = pTable->aCol)!=0 ){
  78697. for(i=0; i<pTable->nCol; i++, pCol++){
  78698. sqlite3DbFree(db, pCol->zName);
  78699. sqlite3ExprDelete(db, pCol->pDflt);
  78700. sqlite3DbFree(db, pCol->zDflt);
  78701. sqlite3DbFree(db, pCol->zType);
  78702. sqlite3DbFree(db, pCol->zColl);
  78703. }
  78704. sqlite3DbFree(db, pTable->aCol);
  78705. }
  78706. }
  78707. /*
  78708. ** Remove the memory data structures associated with the given
  78709. ** Table. No changes are made to disk by this routine.
  78710. **
  78711. ** This routine just deletes the data structure. It does not unlink
  78712. ** the table data structure from the hash table. But it does destroy
  78713. ** memory structures of the indices and foreign keys associated with
  78714. ** the table.
  78715. **
  78716. ** The db parameter is optional. It is needed if the Table object
  78717. ** contains lookaside memory. (Table objects in the schema do not use
  78718. ** lookaside memory, but some ephemeral Table objects do.) Or the
  78719. ** db parameter can be used with db->pnBytesFreed to measure the memory
  78720. ** used by the Table object.
  78721. */
  78722. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  78723. Index *pIndex, *pNext;
  78724. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  78725. assert( !pTable || pTable->nRef>0 );
  78726. /* Do not delete the table until the reference count reaches zero. */
  78727. if( !pTable ) return;
  78728. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  78729. /* Record the number of outstanding lookaside allocations in schema Tables
  78730. ** prior to doing any free() operations. Since schema Tables do not use
  78731. ** lookaside, this number should not change. */
  78732. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  78733. db->lookaside.nOut : 0 );
  78734. /* Delete all indices associated with this table. */
  78735. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  78736. pNext = pIndex->pNext;
  78737. assert( pIndex->pSchema==pTable->pSchema );
  78738. if( !db || db->pnBytesFreed==0 ){
  78739. char *zName = pIndex->zName;
  78740. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  78741. &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
  78742. );
  78743. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  78744. assert( pOld==pIndex || pOld==0 );
  78745. }
  78746. freeIndex(db, pIndex);
  78747. }
  78748. /* Delete any foreign keys attached to this table. */
  78749. sqlite3FkDelete(db, pTable);
  78750. /* Delete the Table structure itself.
  78751. */
  78752. sqliteDeleteColumnNames(db, pTable);
  78753. sqlite3DbFree(db, pTable->zName);
  78754. sqlite3DbFree(db, pTable->zColAff);
  78755. sqlite3SelectDelete(db, pTable->pSelect);
  78756. #ifndef SQLITE_OMIT_CHECK
  78757. sqlite3ExprListDelete(db, pTable->pCheck);
  78758. #endif
  78759. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78760. sqlite3VtabClear(db, pTable);
  78761. #endif
  78762. sqlite3DbFree(db, pTable);
  78763. /* Verify that no lookaside memory was used by schema tables */
  78764. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  78765. }
  78766. /*
  78767. ** Unlink the given table from the hash tables and the delete the
  78768. ** table structure with all its indices and foreign keys.
  78769. */
  78770. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  78771. Table *p;
  78772. Db *pDb;
  78773. assert( db!=0 );
  78774. assert( iDb>=0 && iDb<db->nDb );
  78775. assert( zTabName );
  78776. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  78777. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  78778. pDb = &db->aDb[iDb];
  78779. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
  78780. sqlite3Strlen30(zTabName),0);
  78781. sqlite3DeleteTable(db, p);
  78782. db->flags |= SQLITE_InternChanges;
  78783. }
  78784. /*
  78785. ** Given a token, return a string that consists of the text of that
  78786. ** token. Space to hold the returned string
  78787. ** is obtained from sqliteMalloc() and must be freed by the calling
  78788. ** function.
  78789. **
  78790. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  78791. ** surround the body of the token are removed.
  78792. **
  78793. ** Tokens are often just pointers into the original SQL text and so
  78794. ** are not \000 terminated and are not persistent. The returned string
  78795. ** is \000 terminated and is persistent.
  78796. */
  78797. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  78798. char *zName;
  78799. if( pName ){
  78800. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  78801. sqlite3Dequote(zName);
  78802. }else{
  78803. zName = 0;
  78804. }
  78805. return zName;
  78806. }
  78807. /*
  78808. ** Open the sqlite_master table stored in database number iDb for
  78809. ** writing. The table is opened using cursor 0.
  78810. */
  78811. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  78812. Vdbe *v = sqlite3GetVdbe(p);
  78813. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  78814. sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  78815. sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
  78816. if( p->nTab==0 ){
  78817. p->nTab = 1;
  78818. }
  78819. }
  78820. /*
  78821. ** Parameter zName points to a nul-terminated buffer containing the name
  78822. ** of a database ("main", "temp" or the name of an attached db). This
  78823. ** function returns the index of the named database in db->aDb[], or
  78824. ** -1 if the named db cannot be found.
  78825. */
  78826. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  78827. int i = -1; /* Database number */
  78828. if( zName ){
  78829. Db *pDb;
  78830. int n = sqlite3Strlen30(zName);
  78831. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  78832. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  78833. 0==sqlite3StrICmp(pDb->zName, zName) ){
  78834. break;
  78835. }
  78836. }
  78837. }
  78838. return i;
  78839. }
  78840. /*
  78841. ** The token *pName contains the name of a database (either "main" or
  78842. ** "temp" or the name of an attached db). This routine returns the
  78843. ** index of the named database in db->aDb[], or -1 if the named db
  78844. ** does not exist.
  78845. */
  78846. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  78847. int i; /* Database number */
  78848. char *zName; /* Name we are searching for */
  78849. zName = sqlite3NameFromToken(db, pName);
  78850. i = sqlite3FindDbName(db, zName);
  78851. sqlite3DbFree(db, zName);
  78852. return i;
  78853. }
  78854. /* The table or view or trigger name is passed to this routine via tokens
  78855. ** pName1 and pName2. If the table name was fully qualified, for example:
  78856. **
  78857. ** CREATE TABLE xxx.yyy (...);
  78858. **
  78859. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  78860. ** the table name is not fully qualified, i.e.:
  78861. **
  78862. ** CREATE TABLE yyy(...);
  78863. **
  78864. ** Then pName1 is set to "yyy" and pName2 is "".
  78865. **
  78866. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  78867. ** pName2) that stores the unqualified table name. The index of the
  78868. ** database "xxx" is returned.
  78869. */
  78870. SQLITE_PRIVATE int sqlite3TwoPartName(
  78871. Parse *pParse, /* Parsing and code generating context */
  78872. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  78873. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  78874. Token **pUnqual /* Write the unqualified object name here */
  78875. ){
  78876. int iDb; /* Database holding the object */
  78877. sqlite3 *db = pParse->db;
  78878. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  78879. if( db->init.busy ) {
  78880. sqlite3ErrorMsg(pParse, "corrupt database");
  78881. pParse->nErr++;
  78882. return -1;
  78883. }
  78884. *pUnqual = pName2;
  78885. iDb = sqlite3FindDb(db, pName1);
  78886. if( iDb<0 ){
  78887. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  78888. pParse->nErr++;
  78889. return -1;
  78890. }
  78891. }else{
  78892. assert( db->init.iDb==0 || db->init.busy );
  78893. iDb = db->init.iDb;
  78894. *pUnqual = pName1;
  78895. }
  78896. return iDb;
  78897. }
  78898. /*
  78899. ** This routine is used to check if the UTF-8 string zName is a legal
  78900. ** unqualified name for a new schema object (table, index, view or
  78901. ** trigger). All names are legal except those that begin with the string
  78902. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  78903. ** is reserved for internal use.
  78904. */
  78905. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  78906. if( !pParse->db->init.busy && pParse->nested==0
  78907. && (pParse->db->flags & SQLITE_WriteSchema)==0
  78908. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  78909. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  78910. return SQLITE_ERROR;
  78911. }
  78912. return SQLITE_OK;
  78913. }
  78914. /*
  78915. ** Begin constructing a new table representation in memory. This is
  78916. ** the first of several action routines that get called in response
  78917. ** to a CREATE TABLE statement. In particular, this routine is called
  78918. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  78919. ** flag is true if the table should be stored in the auxiliary database
  78920. ** file instead of in the main database file. This is normally the case
  78921. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  78922. ** CREATE and TABLE.
  78923. **
  78924. ** The new table record is initialized and put in pParse->pNewTable.
  78925. ** As more of the CREATE TABLE statement is parsed, additional action
  78926. ** routines will be called to add more information to this record.
  78927. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  78928. ** is called to complete the construction of the new table record.
  78929. */
  78930. SQLITE_PRIVATE void sqlite3StartTable(
  78931. Parse *pParse, /* Parser context */
  78932. Token *pName1, /* First part of the name of the table or view */
  78933. Token *pName2, /* Second part of the name of the table or view */
  78934. int isTemp, /* True if this is a TEMP table */
  78935. int isView, /* True if this is a VIEW */
  78936. int isVirtual, /* True if this is a VIRTUAL table */
  78937. int noErr /* Do nothing if table already exists */
  78938. ){
  78939. Table *pTable;
  78940. char *zName = 0; /* The name of the new table */
  78941. sqlite3 *db = pParse->db;
  78942. Vdbe *v;
  78943. int iDb; /* Database number to create the table in */
  78944. Token *pName; /* Unqualified name of the table to create */
  78945. /* The table or view name to create is passed to this routine via tokens
  78946. ** pName1 and pName2. If the table name was fully qualified, for example:
  78947. **
  78948. ** CREATE TABLE xxx.yyy (...);
  78949. **
  78950. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  78951. ** the table name is not fully qualified, i.e.:
  78952. **
  78953. ** CREATE TABLE yyy(...);
  78954. **
  78955. ** Then pName1 is set to "yyy" and pName2 is "".
  78956. **
  78957. ** The call below sets the pName pointer to point at the token (pName1 or
  78958. ** pName2) that stores the unqualified table name. The variable iDb is
  78959. ** set to the index of the database that the table or view is to be
  78960. ** created in.
  78961. */
  78962. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  78963. if( iDb<0 ) return;
  78964. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  78965. /* If creating a temp table, the name may not be qualified. Unless
  78966. ** the database name is "temp" anyway. */
  78967. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  78968. return;
  78969. }
  78970. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  78971. pParse->sNameToken = *pName;
  78972. zName = sqlite3NameFromToken(db, pName);
  78973. if( zName==0 ) return;
  78974. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  78975. goto begin_table_error;
  78976. }
  78977. if( db->init.iDb==1 ) isTemp = 1;
  78978. #ifndef SQLITE_OMIT_AUTHORIZATION
  78979. assert( (isTemp & 1)==isTemp );
  78980. {
  78981. int code;
  78982. char *zDb = db->aDb[iDb].zName;
  78983. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  78984. goto begin_table_error;
  78985. }
  78986. if( isView ){
  78987. if( !OMIT_TEMPDB && isTemp ){
  78988. code = SQLITE_CREATE_TEMP_VIEW;
  78989. }else{
  78990. code = SQLITE_CREATE_VIEW;
  78991. }
  78992. }else{
  78993. if( !OMIT_TEMPDB && isTemp ){
  78994. code = SQLITE_CREATE_TEMP_TABLE;
  78995. }else{
  78996. code = SQLITE_CREATE_TABLE;
  78997. }
  78998. }
  78999. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  79000. goto begin_table_error;
  79001. }
  79002. }
  79003. #endif
  79004. /* Make sure the new table name does not collide with an existing
  79005. ** index or table name in the same database. Issue an error message if
  79006. ** it does. The exception is if the statement being parsed was passed
  79007. ** to an sqlite3_declare_vtab() call. In that case only the column names
  79008. ** and types will be used, so there is no need to test for namespace
  79009. ** collisions.
  79010. */
  79011. if( !IN_DECLARE_VTAB ){
  79012. char *zDb = db->aDb[iDb].zName;
  79013. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  79014. goto begin_table_error;
  79015. }
  79016. pTable = sqlite3FindTable(db, zName, zDb);
  79017. if( pTable ){
  79018. if( !noErr ){
  79019. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  79020. }else{
  79021. assert( !db->init.busy );
  79022. sqlite3CodeVerifySchema(pParse, iDb);
  79023. }
  79024. goto begin_table_error;
  79025. }
  79026. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  79027. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  79028. goto begin_table_error;
  79029. }
  79030. }
  79031. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  79032. if( pTable==0 ){
  79033. db->mallocFailed = 1;
  79034. pParse->rc = SQLITE_NOMEM;
  79035. pParse->nErr++;
  79036. goto begin_table_error;
  79037. }
  79038. pTable->zName = zName;
  79039. pTable->iPKey = -1;
  79040. pTable->pSchema = db->aDb[iDb].pSchema;
  79041. pTable->nRef = 1;
  79042. pTable->nRowEst = 1048576;
  79043. assert( pParse->pNewTable==0 );
  79044. pParse->pNewTable = pTable;
  79045. /* If this is the magic sqlite_sequence table used by autoincrement,
  79046. ** then record a pointer to this table in the main database structure
  79047. ** so that INSERT can find the table easily.
  79048. */
  79049. #ifndef SQLITE_OMIT_AUTOINCREMENT
  79050. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  79051. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  79052. pTable->pSchema->pSeqTab = pTable;
  79053. }
  79054. #endif
  79055. /* Begin generating the code that will insert the table record into
  79056. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  79057. ** and allocate the record number for the table entry now. Before any
  79058. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  79059. ** indices to be created and the table record must come before the
  79060. ** indices. Hence, the record number for the table must be allocated
  79061. ** now.
  79062. */
  79063. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  79064. int j1;
  79065. int fileFormat;
  79066. int reg1, reg2, reg3;
  79067. sqlite3BeginWriteOperation(pParse, 0, iDb);
  79068. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79069. if( isVirtual ){
  79070. sqlite3VdbeAddOp0(v, OP_VBegin);
  79071. }
  79072. #endif
  79073. /* If the file format and encoding in the database have not been set,
  79074. ** set them now.
  79075. */
  79076. reg1 = pParse->regRowid = ++pParse->nMem;
  79077. reg2 = pParse->regRoot = ++pParse->nMem;
  79078. reg3 = ++pParse->nMem;
  79079. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  79080. sqlite3VdbeUsesBtree(v, iDb);
  79081. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
  79082. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  79083. 1 : SQLITE_MAX_FILE_FORMAT;
  79084. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  79085. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  79086. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  79087. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  79088. sqlite3VdbeJumpHere(v, j1);
  79089. /* This just creates a place-holder record in the sqlite_master table.
  79090. ** The record created does not contain anything yet. It will be replaced
  79091. ** by the real entry in code generated at sqlite3EndTable().
  79092. **
  79093. ** The rowid for the new entry is left in register pParse->regRowid.
  79094. ** The root page number of the new table is left in reg pParse->regRoot.
  79095. ** The rowid and root page number values are needed by the code that
  79096. ** sqlite3EndTable will generate.
  79097. */
  79098. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  79099. if( isView || isVirtual ){
  79100. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  79101. }else
  79102. #endif
  79103. {
  79104. sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  79105. }
  79106. sqlite3OpenMasterTable(pParse, iDb);
  79107. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  79108. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  79109. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  79110. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  79111. sqlite3VdbeAddOp0(v, OP_Close);
  79112. }
  79113. /* Normal (non-error) return. */
  79114. return;
  79115. /* If an error occurs, we jump here */
  79116. begin_table_error:
  79117. sqlite3DbFree(db, zName);
  79118. return;
  79119. }
  79120. /*
  79121. ** This macro is used to compare two strings in a case-insensitive manner.
  79122. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  79123. ** produces larger code.
  79124. **
  79125. ** WARNING: This macro is not compatible with the strcmp() family. It
  79126. ** returns true if the two strings are equal, otherwise false.
  79127. */
  79128. #define STRICMP(x, y) (\
  79129. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  79130. sqlite3UpperToLower[*(unsigned char *)(y)] \
  79131. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  79132. /*
  79133. ** Add a new column to the table currently being constructed.
  79134. **
  79135. ** The parser calls this routine once for each column declaration
  79136. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  79137. ** first to get things going. Then this routine is called for each
  79138. ** column.
  79139. */
  79140. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  79141. Table *p;
  79142. int i;
  79143. char *z;
  79144. Column *pCol;
  79145. sqlite3 *db = pParse->db;
  79146. if( (p = pParse->pNewTable)==0 ) return;
  79147. #if SQLITE_MAX_COLUMN
  79148. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  79149. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  79150. return;
  79151. }
  79152. #endif
  79153. z = sqlite3NameFromToken(db, pName);
  79154. if( z==0 ) return;
  79155. for(i=0; i<p->nCol; i++){
  79156. if( STRICMP(z, p->aCol[i].zName) ){
  79157. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  79158. sqlite3DbFree(db, z);
  79159. return;
  79160. }
  79161. }
  79162. if( (p->nCol & 0x7)==0 ){
  79163. Column *aNew;
  79164. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  79165. if( aNew==0 ){
  79166. sqlite3DbFree(db, z);
  79167. return;
  79168. }
  79169. p->aCol = aNew;
  79170. }
  79171. pCol = &p->aCol[p->nCol];
  79172. memset(pCol, 0, sizeof(p->aCol[0]));
  79173. pCol->zName = z;
  79174. /* If there is no type specified, columns have the default affinity
  79175. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  79176. ** be called next to set pCol->affinity correctly.
  79177. */
  79178. pCol->affinity = SQLITE_AFF_NONE;
  79179. pCol->szEst = 1;
  79180. p->nCol++;
  79181. }
  79182. /*
  79183. ** This routine is called by the parser while in the middle of
  79184. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  79185. ** been seen on a column. This routine sets the notNull flag on
  79186. ** the column currently under construction.
  79187. */
  79188. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  79189. Table *p;
  79190. p = pParse->pNewTable;
  79191. if( p==0 || NEVER(p->nCol<1) ) return;
  79192. p->aCol[p->nCol-1].notNull = (u8)onError;
  79193. }
  79194. /*
  79195. ** Scan the column type name zType (length nType) and return the
  79196. ** associated affinity type.
  79197. **
  79198. ** This routine does a case-independent search of zType for the
  79199. ** substrings in the following table. If one of the substrings is
  79200. ** found, the corresponding affinity is returned. If zType contains
  79201. ** more than one of the substrings, entries toward the top of
  79202. ** the table take priority. For example, if zType is 'BLOBINT',
  79203. ** SQLITE_AFF_INTEGER is returned.
  79204. **
  79205. ** Substring | Affinity
  79206. ** --------------------------------
  79207. ** 'INT' | SQLITE_AFF_INTEGER
  79208. ** 'CHAR' | SQLITE_AFF_TEXT
  79209. ** 'CLOB' | SQLITE_AFF_TEXT
  79210. ** 'TEXT' | SQLITE_AFF_TEXT
  79211. ** 'BLOB' | SQLITE_AFF_NONE
  79212. ** 'REAL' | SQLITE_AFF_REAL
  79213. ** 'FLOA' | SQLITE_AFF_REAL
  79214. ** 'DOUB' | SQLITE_AFF_REAL
  79215. **
  79216. ** If none of the substrings in the above table are found,
  79217. ** SQLITE_AFF_NUMERIC is returned.
  79218. */
  79219. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  79220. u32 h = 0;
  79221. char aff = SQLITE_AFF_NUMERIC;
  79222. const char *zChar = 0;
  79223. if( zIn==0 ) return aff;
  79224. while( zIn[0] ){
  79225. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  79226. zIn++;
  79227. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  79228. aff = SQLITE_AFF_TEXT;
  79229. zChar = zIn;
  79230. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  79231. aff = SQLITE_AFF_TEXT;
  79232. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  79233. aff = SQLITE_AFF_TEXT;
  79234. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  79235. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  79236. aff = SQLITE_AFF_NONE;
  79237. if( zIn[0]=='(' ) zChar = zIn;
  79238. #ifndef SQLITE_OMIT_FLOATING_POINT
  79239. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  79240. && aff==SQLITE_AFF_NUMERIC ){
  79241. aff = SQLITE_AFF_REAL;
  79242. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  79243. && aff==SQLITE_AFF_NUMERIC ){
  79244. aff = SQLITE_AFF_REAL;
  79245. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  79246. && aff==SQLITE_AFF_NUMERIC ){
  79247. aff = SQLITE_AFF_REAL;
  79248. #endif
  79249. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  79250. aff = SQLITE_AFF_INTEGER;
  79251. break;
  79252. }
  79253. }
  79254. /* If pszEst is not NULL, store an estimate of the field size. The
  79255. ** estimate is scaled so that the size of an integer is 1. */
  79256. if( pszEst ){
  79257. *pszEst = 1; /* default size is approx 4 bytes */
  79258. if( aff<=SQLITE_AFF_NONE ){
  79259. if( zChar ){
  79260. while( zChar[0] ){
  79261. if( sqlite3Isdigit(zChar[0]) ){
  79262. int v = 0;
  79263. sqlite3GetInt32(zChar, &v);
  79264. v = v/4 + 1;
  79265. if( v>255 ) v = 255;
  79266. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  79267. break;
  79268. }
  79269. zChar++;
  79270. }
  79271. }else{
  79272. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  79273. }
  79274. }
  79275. }
  79276. return aff;
  79277. }
  79278. /*
  79279. ** This routine is called by the parser while in the middle of
  79280. ** parsing a CREATE TABLE statement. The pFirst token is the first
  79281. ** token in the sequence of tokens that describe the type of the
  79282. ** column currently under construction. pLast is the last token
  79283. ** in the sequence. Use this information to construct a string
  79284. ** that contains the typename of the column and store that string
  79285. ** in zType.
  79286. */
  79287. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  79288. Table *p;
  79289. Column *pCol;
  79290. p = pParse->pNewTable;
  79291. if( p==0 || NEVER(p->nCol<1) ) return;
  79292. pCol = &p->aCol[p->nCol-1];
  79293. assert( pCol->zType==0 );
  79294. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  79295. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  79296. }
  79297. /*
  79298. ** The expression is the default value for the most recently added column
  79299. ** of the table currently under construction.
  79300. **
  79301. ** Default value expressions must be constant. Raise an exception if this
  79302. ** is not the case.
  79303. **
  79304. ** This routine is called by the parser while in the middle of
  79305. ** parsing a CREATE TABLE statement.
  79306. */
  79307. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  79308. Table *p;
  79309. Column *pCol;
  79310. sqlite3 *db = pParse->db;
  79311. p = pParse->pNewTable;
  79312. if( p!=0 ){
  79313. pCol = &(p->aCol[p->nCol-1]);
  79314. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
  79315. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  79316. pCol->zName);
  79317. }else{
  79318. /* A copy of pExpr is used instead of the original, as pExpr contains
  79319. ** tokens that point to volatile memory. The 'span' of the expression
  79320. ** is required by pragma table_info.
  79321. */
  79322. sqlite3ExprDelete(db, pCol->pDflt);
  79323. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  79324. sqlite3DbFree(db, pCol->zDflt);
  79325. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  79326. (int)(pSpan->zEnd - pSpan->zStart));
  79327. }
  79328. }
  79329. sqlite3ExprDelete(db, pSpan->pExpr);
  79330. }
  79331. /*
  79332. ** Designate the PRIMARY KEY for the table. pList is a list of names
  79333. ** of columns that form the primary key. If pList is NULL, then the
  79334. ** most recently added column of the table is the primary key.
  79335. **
  79336. ** A table can have at most one primary key. If the table already has
  79337. ** a primary key (and this is the second primary key) then create an
  79338. ** error.
  79339. **
  79340. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  79341. ** then we will try to use that column as the rowid. Set the Table.iPKey
  79342. ** field of the table under construction to be the index of the
  79343. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  79344. ** no INTEGER PRIMARY KEY.
  79345. **
  79346. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  79347. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  79348. */
  79349. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  79350. Parse *pParse, /* Parsing context */
  79351. ExprList *pList, /* List of field names to be indexed */
  79352. int onError, /* What to do with a uniqueness conflict */
  79353. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  79354. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  79355. ){
  79356. Table *pTab = pParse->pNewTable;
  79357. char *zType = 0;
  79358. int iCol = -1, i;
  79359. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  79360. if( pTab->tabFlags & TF_HasPrimaryKey ){
  79361. sqlite3ErrorMsg(pParse,
  79362. "table \"%s\" has more than one primary key", pTab->zName);
  79363. goto primary_key_exit;
  79364. }
  79365. pTab->tabFlags |= TF_HasPrimaryKey;
  79366. if( pList==0 ){
  79367. iCol = pTab->nCol - 1;
  79368. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  79369. }else{
  79370. for(i=0; i<pList->nExpr; i++){
  79371. for(iCol=0; iCol<pTab->nCol; iCol++){
  79372. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  79373. break;
  79374. }
  79375. }
  79376. if( iCol<pTab->nCol ){
  79377. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  79378. }
  79379. }
  79380. if( pList->nExpr>1 ) iCol = -1;
  79381. }
  79382. if( iCol>=0 && iCol<pTab->nCol ){
  79383. zType = pTab->aCol[iCol].zType;
  79384. }
  79385. if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  79386. && sortOrder==SQLITE_SO_ASC ){
  79387. pTab->iPKey = iCol;
  79388. pTab->keyConf = (u8)onError;
  79389. assert( autoInc==0 || autoInc==1 );
  79390. pTab->tabFlags |= autoInc*TF_Autoincrement;
  79391. }else if( autoInc ){
  79392. #ifndef SQLITE_OMIT_AUTOINCREMENT
  79393. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  79394. "INTEGER PRIMARY KEY");
  79395. #endif
  79396. }else{
  79397. Index *p;
  79398. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  79399. 0, sortOrder, 0);
  79400. if( p ){
  79401. p->autoIndex = 2;
  79402. }
  79403. pList = 0;
  79404. }
  79405. primary_key_exit:
  79406. sqlite3ExprListDelete(pParse->db, pList);
  79407. return;
  79408. }
  79409. /*
  79410. ** Add a new CHECK constraint to the table currently under construction.
  79411. */
  79412. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  79413. Parse *pParse, /* Parsing context */
  79414. Expr *pCheckExpr /* The check expression */
  79415. ){
  79416. #ifndef SQLITE_OMIT_CHECK
  79417. Table *pTab = pParse->pNewTable;
  79418. if( pTab && !IN_DECLARE_VTAB ){
  79419. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  79420. if( pParse->constraintName.n ){
  79421. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  79422. }
  79423. }else
  79424. #endif
  79425. {
  79426. sqlite3ExprDelete(pParse->db, pCheckExpr);
  79427. }
  79428. }
  79429. /*
  79430. ** Set the collation function of the most recently parsed table column
  79431. ** to the CollSeq given.
  79432. */
  79433. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  79434. Table *p;
  79435. int i;
  79436. char *zColl; /* Dequoted name of collation sequence */
  79437. sqlite3 *db;
  79438. if( (p = pParse->pNewTable)==0 ) return;
  79439. i = p->nCol-1;
  79440. db = pParse->db;
  79441. zColl = sqlite3NameFromToken(db, pToken);
  79442. if( !zColl ) return;
  79443. if( sqlite3LocateCollSeq(pParse, zColl) ){
  79444. Index *pIdx;
  79445. sqlite3DbFree(db, p->aCol[i].zColl);
  79446. p->aCol[i].zColl = zColl;
  79447. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  79448. ** then an index may have been created on this column before the
  79449. ** collation type was added. Correct this if it is the case.
  79450. */
  79451. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  79452. assert( pIdx->nColumn==1 );
  79453. if( pIdx->aiColumn[0]==i ){
  79454. pIdx->azColl[0] = p->aCol[i].zColl;
  79455. }
  79456. }
  79457. }else{
  79458. sqlite3DbFree(db, zColl);
  79459. }
  79460. }
  79461. /*
  79462. ** This function returns the collation sequence for database native text
  79463. ** encoding identified by the string zName, length nName.
  79464. **
  79465. ** If the requested collation sequence is not available, or not available
  79466. ** in the database native encoding, the collation factory is invoked to
  79467. ** request it. If the collation factory does not supply such a sequence,
  79468. ** and the sequence is available in another text encoding, then that is
  79469. ** returned instead.
  79470. **
  79471. ** If no versions of the requested collations sequence are available, or
  79472. ** another error occurs, NULL is returned and an error message written into
  79473. ** pParse.
  79474. **
  79475. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  79476. ** invokes the collation factory if the named collation cannot be found
  79477. ** and generates an error message.
  79478. **
  79479. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  79480. */
  79481. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  79482. sqlite3 *db = pParse->db;
  79483. u8 enc = ENC(db);
  79484. u8 initbusy = db->init.busy;
  79485. CollSeq *pColl;
  79486. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  79487. if( !initbusy && (!pColl || !pColl->xCmp) ){
  79488. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  79489. }
  79490. return pColl;
  79491. }
  79492. /*
  79493. ** Generate code that will increment the schema cookie.
  79494. **
  79495. ** The schema cookie is used to determine when the schema for the
  79496. ** database changes. After each schema change, the cookie value
  79497. ** changes. When a process first reads the schema it records the
  79498. ** cookie. Thereafter, whenever it goes to access the database,
  79499. ** it checks the cookie to make sure the schema has not changed
  79500. ** since it was last read.
  79501. **
  79502. ** This plan is not completely bullet-proof. It is possible for
  79503. ** the schema to change multiple times and for the cookie to be
  79504. ** set back to prior value. But schema changes are infrequent
  79505. ** and the probability of hitting the same cookie value is only
  79506. ** 1 chance in 2^32. So we're safe enough.
  79507. */
  79508. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  79509. int r1 = sqlite3GetTempReg(pParse);
  79510. sqlite3 *db = pParse->db;
  79511. Vdbe *v = pParse->pVdbe;
  79512. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  79513. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  79514. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  79515. sqlite3ReleaseTempReg(pParse, r1);
  79516. }
  79517. /*
  79518. ** Measure the number of characters needed to output the given
  79519. ** identifier. The number returned includes any quotes used
  79520. ** but does not include the null terminator.
  79521. **
  79522. ** The estimate is conservative. It might be larger that what is
  79523. ** really needed.
  79524. */
  79525. static int identLength(const char *z){
  79526. int n;
  79527. for(n=0; *z; n++, z++){
  79528. if( *z=='"' ){ n++; }
  79529. }
  79530. return n + 2;
  79531. }
  79532. /*
  79533. ** The first parameter is a pointer to an output buffer. The second
  79534. ** parameter is a pointer to an integer that contains the offset at
  79535. ** which to write into the output buffer. This function copies the
  79536. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  79537. ** to the specified offset in the buffer and updates *pIdx to refer
  79538. ** to the first byte after the last byte written before returning.
  79539. **
  79540. ** If the string zSignedIdent consists entirely of alpha-numeric
  79541. ** characters, does not begin with a digit and is not an SQL keyword,
  79542. ** then it is copied to the output buffer exactly as it is. Otherwise,
  79543. ** it is quoted using double-quotes.
  79544. */
  79545. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  79546. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  79547. int i, j, needQuote;
  79548. i = *pIdx;
  79549. for(j=0; zIdent[j]; j++){
  79550. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  79551. }
  79552. needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  79553. if( !needQuote ){
  79554. needQuote = zIdent[j];
  79555. }
  79556. if( needQuote ) z[i++] = '"';
  79557. for(j=0; zIdent[j]; j++){
  79558. z[i++] = zIdent[j];
  79559. if( zIdent[j]=='"' ) z[i++] = '"';
  79560. }
  79561. if( needQuote ) z[i++] = '"';
  79562. z[i] = 0;
  79563. *pIdx = i;
  79564. }
  79565. /*
  79566. ** Generate a CREATE TABLE statement appropriate for the given
  79567. ** table. Memory to hold the text of the statement is obtained
  79568. ** from sqliteMalloc() and must be freed by the calling function.
  79569. */
  79570. static char *createTableStmt(sqlite3 *db, Table *p){
  79571. int i, k, n;
  79572. char *zStmt;
  79573. char *zSep, *zSep2, *zEnd;
  79574. Column *pCol;
  79575. n = 0;
  79576. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  79577. n += identLength(pCol->zName) + 5;
  79578. }
  79579. n += identLength(p->zName);
  79580. if( n<50 ){
  79581. zSep = "";
  79582. zSep2 = ",";
  79583. zEnd = ")";
  79584. }else{
  79585. zSep = "\n ";
  79586. zSep2 = ",\n ";
  79587. zEnd = "\n)";
  79588. }
  79589. n += 35 + 6*p->nCol;
  79590. zStmt = sqlite3DbMallocRaw(0, n);
  79591. if( zStmt==0 ){
  79592. db->mallocFailed = 1;
  79593. return 0;
  79594. }
  79595. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  79596. k = sqlite3Strlen30(zStmt);
  79597. identPut(zStmt, &k, p->zName);
  79598. zStmt[k++] = '(';
  79599. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  79600. static const char * const azType[] = {
  79601. /* SQLITE_AFF_TEXT */ " TEXT",
  79602. /* SQLITE_AFF_NONE */ "",
  79603. /* SQLITE_AFF_NUMERIC */ " NUM",
  79604. /* SQLITE_AFF_INTEGER */ " INT",
  79605. /* SQLITE_AFF_REAL */ " REAL"
  79606. };
  79607. int len;
  79608. const char *zType;
  79609. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  79610. k += sqlite3Strlen30(&zStmt[k]);
  79611. zSep = zSep2;
  79612. identPut(zStmt, &k, pCol->zName);
  79613. assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
  79614. assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
  79615. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  79616. testcase( pCol->affinity==SQLITE_AFF_NONE );
  79617. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  79618. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  79619. testcase( pCol->affinity==SQLITE_AFF_REAL );
  79620. zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
  79621. len = sqlite3Strlen30(zType);
  79622. assert( pCol->affinity==SQLITE_AFF_NONE
  79623. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  79624. memcpy(&zStmt[k], zType, len);
  79625. k += len;
  79626. assert( k<=n );
  79627. }
  79628. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  79629. return zStmt;
  79630. }
  79631. /*
  79632. ** Estimate the total row width for a table.
  79633. */
  79634. static void estimateTableWidth(Table *pTab){
  79635. unsigned wTable = 0;
  79636. const Column *pTabCol;
  79637. int i;
  79638. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  79639. wTable += pTabCol->szEst;
  79640. }
  79641. if( pTab->iPKey<0 ) wTable++;
  79642. pTab->szTabRow = sqlite3LogEst(wTable*4);
  79643. }
  79644. /*
  79645. ** Estimate the average size of a row for an index.
  79646. */
  79647. static void estimateIndexWidth(Index *pIdx){
  79648. unsigned wIndex = 1;
  79649. int i;
  79650. const Column *aCol = pIdx->pTable->aCol;
  79651. for(i=0; i<pIdx->nColumn; i++){
  79652. assert( pIdx->aiColumn[i]>=0 && pIdx->aiColumn[i]<pIdx->pTable->nCol );
  79653. wIndex += aCol[pIdx->aiColumn[i]].szEst;
  79654. }
  79655. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  79656. }
  79657. /*
  79658. ** This routine is called to report the final ")" that terminates
  79659. ** a CREATE TABLE statement.
  79660. **
  79661. ** The table structure that other action routines have been building
  79662. ** is added to the internal hash tables, assuming no errors have
  79663. ** occurred.
  79664. **
  79665. ** An entry for the table is made in the master table on disk, unless
  79666. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  79667. ** it means we are reading the sqlite_master table because we just
  79668. ** connected to the database or because the sqlite_master table has
  79669. ** recently changed, so the entry for this table already exists in
  79670. ** the sqlite_master table. We do not want to create it again.
  79671. **
  79672. ** If the pSelect argument is not NULL, it means that this routine
  79673. ** was called to create a table generated from a
  79674. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  79675. ** the new table will match the result set of the SELECT.
  79676. */
  79677. SQLITE_PRIVATE void sqlite3EndTable(
  79678. Parse *pParse, /* Parse context */
  79679. Token *pCons, /* The ',' token after the last column defn. */
  79680. Token *pEnd, /* The final ')' token in the CREATE TABLE */
  79681. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  79682. ){
  79683. Table *p; /* The new table */
  79684. sqlite3 *db = pParse->db; /* The database connection */
  79685. int iDb; /* Database in which the table lives */
  79686. Index *pIdx; /* An implied index of the table */
  79687. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  79688. return;
  79689. }
  79690. p = pParse->pNewTable;
  79691. if( p==0 ) return;
  79692. assert( !db->init.busy || !pSelect );
  79693. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  79694. #ifndef SQLITE_OMIT_CHECK
  79695. /* Resolve names in all CHECK constraint expressions.
  79696. */
  79697. if( p->pCheck ){
  79698. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  79699. }
  79700. #endif /* !defined(SQLITE_OMIT_CHECK) */
  79701. /* Estimate the average row size for the table and for all implied indices */
  79702. estimateTableWidth(p);
  79703. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  79704. estimateIndexWidth(pIdx);
  79705. }
  79706. /* If the db->init.busy is 1 it means we are reading the SQL off the
  79707. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  79708. ** So do not write to the disk again. Extract the root page number
  79709. ** for the table from the db->init.newTnum field. (The page number
  79710. ** should have been put there by the sqliteOpenCb routine.)
  79711. */
  79712. if( db->init.busy ){
  79713. p->tnum = db->init.newTnum;
  79714. }
  79715. /* If not initializing, then create a record for the new table
  79716. ** in the SQLITE_MASTER table of the database.
  79717. **
  79718. ** If this is a TEMPORARY table, write the entry into the auxiliary
  79719. ** file instead of into the main database file.
  79720. */
  79721. if( !db->init.busy ){
  79722. int n;
  79723. Vdbe *v;
  79724. char *zType; /* "view" or "table" */
  79725. char *zType2; /* "VIEW" or "TABLE" */
  79726. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  79727. v = sqlite3GetVdbe(pParse);
  79728. if( NEVER(v==0) ) return;
  79729. sqlite3VdbeAddOp1(v, OP_Close, 0);
  79730. /*
  79731. ** Initialize zType for the new view or table.
  79732. */
  79733. if( p->pSelect==0 ){
  79734. /* A regular table */
  79735. zType = "table";
  79736. zType2 = "TABLE";
  79737. #ifndef SQLITE_OMIT_VIEW
  79738. }else{
  79739. /* A view */
  79740. zType = "view";
  79741. zType2 = "VIEW";
  79742. #endif
  79743. }
  79744. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  79745. ** statement to populate the new table. The root-page number for the
  79746. ** new table is in register pParse->regRoot.
  79747. **
  79748. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  79749. ** suitable state to query for the column names and types to be used
  79750. ** by the new table.
  79751. **
  79752. ** A shared-cache write-lock is not required to write to the new table,
  79753. ** as a schema-lock must have already been obtained to create it. Since
  79754. ** a schema-lock excludes all other database users, the write-lock would
  79755. ** be redundant.
  79756. */
  79757. if( pSelect ){
  79758. SelectDest dest;
  79759. Table *pSelTab;
  79760. assert(pParse->nTab==1);
  79761. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  79762. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  79763. pParse->nTab = 2;
  79764. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  79765. sqlite3Select(pParse, pSelect, &dest);
  79766. sqlite3VdbeAddOp1(v, OP_Close, 1);
  79767. if( pParse->nErr==0 ){
  79768. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  79769. if( pSelTab==0 ) return;
  79770. assert( p->aCol==0 );
  79771. p->nCol = pSelTab->nCol;
  79772. p->aCol = pSelTab->aCol;
  79773. pSelTab->nCol = 0;
  79774. pSelTab->aCol = 0;
  79775. sqlite3DeleteTable(db, pSelTab);
  79776. }
  79777. }
  79778. /* Compute the complete text of the CREATE statement */
  79779. if( pSelect ){
  79780. zStmt = createTableStmt(db, p);
  79781. }else{
  79782. n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
  79783. zStmt = sqlite3MPrintf(db,
  79784. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  79785. );
  79786. }
  79787. /* A slot for the record has already been allocated in the
  79788. ** SQLITE_MASTER table. We just need to update that slot with all
  79789. ** the information we've collected.
  79790. */
  79791. sqlite3NestedParse(pParse,
  79792. "UPDATE %Q.%s "
  79793. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  79794. "WHERE rowid=#%d",
  79795. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  79796. zType,
  79797. p->zName,
  79798. p->zName,
  79799. pParse->regRoot,
  79800. zStmt,
  79801. pParse->regRowid
  79802. );
  79803. sqlite3DbFree(db, zStmt);
  79804. sqlite3ChangeCookie(pParse, iDb);
  79805. #ifndef SQLITE_OMIT_AUTOINCREMENT
  79806. /* Check to see if we need to create an sqlite_sequence table for
  79807. ** keeping track of autoincrement keys.
  79808. */
  79809. if( p->tabFlags & TF_Autoincrement ){
  79810. Db *pDb = &db->aDb[iDb];
  79811. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  79812. if( pDb->pSchema->pSeqTab==0 ){
  79813. sqlite3NestedParse(pParse,
  79814. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  79815. pDb->zName
  79816. );
  79817. }
  79818. }
  79819. #endif
  79820. /* Reparse everything to update our internal data structures */
  79821. sqlite3VdbeAddParseSchemaOp(v, iDb,
  79822. sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
  79823. }
  79824. /* Add the table to the in-memory representation of the database.
  79825. */
  79826. if( db->init.busy ){
  79827. Table *pOld;
  79828. Schema *pSchema = p->pSchema;
  79829. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  79830. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
  79831. sqlite3Strlen30(p->zName),p);
  79832. if( pOld ){
  79833. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  79834. db->mallocFailed = 1;
  79835. return;
  79836. }
  79837. pParse->pNewTable = 0;
  79838. db->flags |= SQLITE_InternChanges;
  79839. #ifndef SQLITE_OMIT_ALTERTABLE
  79840. if( !p->pSelect ){
  79841. const char *zName = (const char *)pParse->sNameToken.z;
  79842. int nName;
  79843. assert( !pSelect && pCons && pEnd );
  79844. if( pCons->z==0 ){
  79845. pCons = pEnd;
  79846. }
  79847. nName = (int)((const char *)pCons->z - zName);
  79848. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  79849. }
  79850. #endif
  79851. }
  79852. }
  79853. #ifndef SQLITE_OMIT_VIEW
  79854. /*
  79855. ** The parser calls this routine in order to create a new VIEW
  79856. */
  79857. SQLITE_PRIVATE void sqlite3CreateView(
  79858. Parse *pParse, /* The parsing context */
  79859. Token *pBegin, /* The CREATE token that begins the statement */
  79860. Token *pName1, /* The token that holds the name of the view */
  79861. Token *pName2, /* The token that holds the name of the view */
  79862. Select *pSelect, /* A SELECT statement that will become the new view */
  79863. int isTemp, /* TRUE for a TEMPORARY view */
  79864. int noErr /* Suppress error messages if VIEW already exists */
  79865. ){
  79866. Table *p;
  79867. int n;
  79868. const char *z;
  79869. Token sEnd;
  79870. DbFixer sFix;
  79871. Token *pName = 0;
  79872. int iDb;
  79873. sqlite3 *db = pParse->db;
  79874. if( pParse->nVar>0 ){
  79875. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  79876. sqlite3SelectDelete(db, pSelect);
  79877. return;
  79878. }
  79879. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  79880. p = pParse->pNewTable;
  79881. if( p==0 || pParse->nErr ){
  79882. sqlite3SelectDelete(db, pSelect);
  79883. return;
  79884. }
  79885. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  79886. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  79887. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  79888. if( sqlite3FixSelect(&sFix, pSelect) ){
  79889. sqlite3SelectDelete(db, pSelect);
  79890. return;
  79891. }
  79892. /* Make a copy of the entire SELECT statement that defines the view.
  79893. ** This will force all the Expr.token.z values to be dynamically
  79894. ** allocated rather than point to the input string - which means that
  79895. ** they will persist after the current sqlite3_exec() call returns.
  79896. */
  79897. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  79898. sqlite3SelectDelete(db, pSelect);
  79899. if( db->mallocFailed ){
  79900. return;
  79901. }
  79902. if( !db->init.busy ){
  79903. sqlite3ViewGetColumnNames(pParse, p);
  79904. }
  79905. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  79906. ** the end.
  79907. */
  79908. sEnd = pParse->sLastToken;
  79909. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  79910. sEnd.z += sEnd.n;
  79911. }
  79912. sEnd.n = 0;
  79913. n = (int)(sEnd.z - pBegin->z);
  79914. z = pBegin->z;
  79915. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  79916. sEnd.z = &z[n-1];
  79917. sEnd.n = 1;
  79918. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  79919. sqlite3EndTable(pParse, 0, &sEnd, 0);
  79920. return;
  79921. }
  79922. #endif /* SQLITE_OMIT_VIEW */
  79923. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  79924. /*
  79925. ** The Table structure pTable is really a VIEW. Fill in the names of
  79926. ** the columns of the view in the pTable structure. Return the number
  79927. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  79928. */
  79929. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  79930. Table *pSelTab; /* A fake table from which we get the result set */
  79931. Select *pSel; /* Copy of the SELECT that implements the view */
  79932. int nErr = 0; /* Number of errors encountered */
  79933. int n; /* Temporarily holds the number of cursors assigned */
  79934. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  79935. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  79936. assert( pTable );
  79937. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79938. if( sqlite3VtabCallConnect(pParse, pTable) ){
  79939. return SQLITE_ERROR;
  79940. }
  79941. if( IsVirtual(pTable) ) return 0;
  79942. #endif
  79943. #ifndef SQLITE_OMIT_VIEW
  79944. /* A positive nCol means the columns names for this view are
  79945. ** already known.
  79946. */
  79947. if( pTable->nCol>0 ) return 0;
  79948. /* A negative nCol is a special marker meaning that we are currently
  79949. ** trying to compute the column names. If we enter this routine with
  79950. ** a negative nCol, it means two or more views form a loop, like this:
  79951. **
  79952. ** CREATE VIEW one AS SELECT * FROM two;
  79953. ** CREATE VIEW two AS SELECT * FROM one;
  79954. **
  79955. ** Actually, the error above is now caught prior to reaching this point.
  79956. ** But the following test is still important as it does come up
  79957. ** in the following:
  79958. **
  79959. ** CREATE TABLE main.ex1(a);
  79960. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  79961. ** SELECT * FROM temp.ex1;
  79962. */
  79963. if( pTable->nCol<0 ){
  79964. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  79965. return 1;
  79966. }
  79967. assert( pTable->nCol>=0 );
  79968. /* If we get this far, it means we need to compute the table names.
  79969. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  79970. ** "*" elements in the results set of the view and will assign cursors
  79971. ** to the elements of the FROM clause. But we do not want these changes
  79972. ** to be permanent. So the computation is done on a copy of the SELECT
  79973. ** statement that defines the view.
  79974. */
  79975. assert( pTable->pSelect );
  79976. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  79977. if( pSel ){
  79978. u8 enableLookaside = db->lookaside.bEnabled;
  79979. n = pParse->nTab;
  79980. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  79981. pTable->nCol = -1;
  79982. db->lookaside.bEnabled = 0;
  79983. #ifndef SQLITE_OMIT_AUTHORIZATION
  79984. xAuth = db->xAuth;
  79985. db->xAuth = 0;
  79986. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  79987. db->xAuth = xAuth;
  79988. #else
  79989. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  79990. #endif
  79991. db->lookaside.bEnabled = enableLookaside;
  79992. pParse->nTab = n;
  79993. if( pSelTab ){
  79994. assert( pTable->aCol==0 );
  79995. pTable->nCol = pSelTab->nCol;
  79996. pTable->aCol = pSelTab->aCol;
  79997. pSelTab->nCol = 0;
  79998. pSelTab->aCol = 0;
  79999. sqlite3DeleteTable(db, pSelTab);
  80000. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  80001. pTable->pSchema->flags |= DB_UnresetViews;
  80002. }else{
  80003. pTable->nCol = 0;
  80004. nErr++;
  80005. }
  80006. sqlite3SelectDelete(db, pSel);
  80007. } else {
  80008. nErr++;
  80009. }
  80010. #endif /* SQLITE_OMIT_VIEW */
  80011. return nErr;
  80012. }
  80013. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  80014. #ifndef SQLITE_OMIT_VIEW
  80015. /*
  80016. ** Clear the column names from every VIEW in database idx.
  80017. */
  80018. static void sqliteViewResetAll(sqlite3 *db, int idx){
  80019. HashElem *i;
  80020. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  80021. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  80022. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  80023. Table *pTab = sqliteHashData(i);
  80024. if( pTab->pSelect ){
  80025. sqliteDeleteColumnNames(db, pTab);
  80026. pTab->aCol = 0;
  80027. pTab->nCol = 0;
  80028. }
  80029. }
  80030. DbClearProperty(db, idx, DB_UnresetViews);
  80031. }
  80032. #else
  80033. # define sqliteViewResetAll(A,B)
  80034. #endif /* SQLITE_OMIT_VIEW */
  80035. /*
  80036. ** This function is called by the VDBE to adjust the internal schema
  80037. ** used by SQLite when the btree layer moves a table root page. The
  80038. ** root-page of a table or index in database iDb has changed from iFrom
  80039. ** to iTo.
  80040. **
  80041. ** Ticket #1728: The symbol table might still contain information
  80042. ** on tables and/or indices that are the process of being deleted.
  80043. ** If you are unlucky, one of those deleted indices or tables might
  80044. ** have the same rootpage number as the real table or index that is
  80045. ** being moved. So we cannot stop searching after the first match
  80046. ** because the first match might be for one of the deleted indices
  80047. ** or tables and not the table/index that is actually being moved.
  80048. ** We must continue looping until all tables and indices with
  80049. ** rootpage==iFrom have been converted to have a rootpage of iTo
  80050. ** in order to be certain that we got the right one.
  80051. */
  80052. #ifndef SQLITE_OMIT_AUTOVACUUM
  80053. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  80054. HashElem *pElem;
  80055. Hash *pHash;
  80056. Db *pDb;
  80057. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80058. pDb = &db->aDb[iDb];
  80059. pHash = &pDb->pSchema->tblHash;
  80060. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  80061. Table *pTab = sqliteHashData(pElem);
  80062. if( pTab->tnum==iFrom ){
  80063. pTab->tnum = iTo;
  80064. }
  80065. }
  80066. pHash = &pDb->pSchema->idxHash;
  80067. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  80068. Index *pIdx = sqliteHashData(pElem);
  80069. if( pIdx->tnum==iFrom ){
  80070. pIdx->tnum = iTo;
  80071. }
  80072. }
  80073. }
  80074. #endif
  80075. /*
  80076. ** Write code to erase the table with root-page iTable from database iDb.
  80077. ** Also write code to modify the sqlite_master table and internal schema
  80078. ** if a root-page of another table is moved by the btree-layer whilst
  80079. ** erasing iTable (this can happen with an auto-vacuum database).
  80080. */
  80081. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  80082. Vdbe *v = sqlite3GetVdbe(pParse);
  80083. int r1 = sqlite3GetTempReg(pParse);
  80084. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  80085. sqlite3MayAbort(pParse);
  80086. #ifndef SQLITE_OMIT_AUTOVACUUM
  80087. /* OP_Destroy stores an in integer r1. If this integer
  80088. ** is non-zero, then it is the root page number of a table moved to
  80089. ** location iTable. The following code modifies the sqlite_master table to
  80090. ** reflect this.
  80091. **
  80092. ** The "#NNN" in the SQL is a special constant that means whatever value
  80093. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  80094. ** token for additional information.
  80095. */
  80096. sqlite3NestedParse(pParse,
  80097. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  80098. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  80099. #endif
  80100. sqlite3ReleaseTempReg(pParse, r1);
  80101. }
  80102. /*
  80103. ** Write VDBE code to erase table pTab and all associated indices on disk.
  80104. ** Code to update the sqlite_master tables and internal schema definitions
  80105. ** in case a root-page belonging to another table is moved by the btree layer
  80106. ** is also added (this can happen with an auto-vacuum database).
  80107. */
  80108. static void destroyTable(Parse *pParse, Table *pTab){
  80109. #ifdef SQLITE_OMIT_AUTOVACUUM
  80110. Index *pIdx;
  80111. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  80112. destroyRootPage(pParse, pTab->tnum, iDb);
  80113. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  80114. destroyRootPage(pParse, pIdx->tnum, iDb);
  80115. }
  80116. #else
  80117. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  80118. ** is not defined), then it is important to call OP_Destroy on the
  80119. ** table and index root-pages in order, starting with the numerically
  80120. ** largest root-page number. This guarantees that none of the root-pages
  80121. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  80122. ** following were coded:
  80123. **
  80124. ** OP_Destroy 4 0
  80125. ** ...
  80126. ** OP_Destroy 5 0
  80127. **
  80128. ** and root page 5 happened to be the largest root-page number in the
  80129. ** database, then root page 5 would be moved to page 4 by the
  80130. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  80131. ** a free-list page.
  80132. */
  80133. int iTab = pTab->tnum;
  80134. int iDestroyed = 0;
  80135. while( 1 ){
  80136. Index *pIdx;
  80137. int iLargest = 0;
  80138. if( iDestroyed==0 || iTab<iDestroyed ){
  80139. iLargest = iTab;
  80140. }
  80141. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  80142. int iIdx = pIdx->tnum;
  80143. assert( pIdx->pSchema==pTab->pSchema );
  80144. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  80145. iLargest = iIdx;
  80146. }
  80147. }
  80148. if( iLargest==0 ){
  80149. return;
  80150. }else{
  80151. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  80152. assert( iDb>=0 && iDb<pParse->db->nDb );
  80153. destroyRootPage(pParse, iLargest, iDb);
  80154. iDestroyed = iLargest;
  80155. }
  80156. }
  80157. #endif
  80158. }
  80159. /*
  80160. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  80161. ** after a DROP INDEX or DROP TABLE command.
  80162. */
  80163. static void sqlite3ClearStatTables(
  80164. Parse *pParse, /* The parsing context */
  80165. int iDb, /* The database number */
  80166. const char *zType, /* "idx" or "tbl" */
  80167. const char *zName /* Name of index or table */
  80168. ){
  80169. int i;
  80170. const char *zDbName = pParse->db->aDb[iDb].zName;
  80171. for(i=1; i<=4; i++){
  80172. char zTab[24];
  80173. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  80174. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  80175. sqlite3NestedParse(pParse,
  80176. "DELETE FROM %Q.%s WHERE %s=%Q",
  80177. zDbName, zTab, zType, zName
  80178. );
  80179. }
  80180. }
  80181. }
  80182. /*
  80183. ** Generate code to drop a table.
  80184. */
  80185. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  80186. Vdbe *v;
  80187. sqlite3 *db = pParse->db;
  80188. Trigger *pTrigger;
  80189. Db *pDb = &db->aDb[iDb];
  80190. v = sqlite3GetVdbe(pParse);
  80191. assert( v!=0 );
  80192. sqlite3BeginWriteOperation(pParse, 1, iDb);
  80193. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80194. if( IsVirtual(pTab) ){
  80195. sqlite3VdbeAddOp0(v, OP_VBegin);
  80196. }
  80197. #endif
  80198. /* Drop all triggers associated with the table being dropped. Code
  80199. ** is generated to remove entries from sqlite_master and/or
  80200. ** sqlite_temp_master if required.
  80201. */
  80202. pTrigger = sqlite3TriggerList(pParse, pTab);
  80203. while( pTrigger ){
  80204. assert( pTrigger->pSchema==pTab->pSchema ||
  80205. pTrigger->pSchema==db->aDb[1].pSchema );
  80206. sqlite3DropTriggerPtr(pParse, pTrigger);
  80207. pTrigger = pTrigger->pNext;
  80208. }
  80209. #ifndef SQLITE_OMIT_AUTOINCREMENT
  80210. /* Remove any entries of the sqlite_sequence table associated with
  80211. ** the table being dropped. This is done before the table is dropped
  80212. ** at the btree level, in case the sqlite_sequence table needs to
  80213. ** move as a result of the drop (can happen in auto-vacuum mode).
  80214. */
  80215. if( pTab->tabFlags & TF_Autoincrement ){
  80216. sqlite3NestedParse(pParse,
  80217. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  80218. pDb->zName, pTab->zName
  80219. );
  80220. }
  80221. #endif
  80222. /* Drop all SQLITE_MASTER table and index entries that refer to the
  80223. ** table. The program name loops through the master table and deletes
  80224. ** every row that refers to a table of the same name as the one being
  80225. ** dropped. Triggers are handled separately because a trigger can be
  80226. ** created in the temp database that refers to a table in another
  80227. ** database.
  80228. */
  80229. sqlite3NestedParse(pParse,
  80230. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  80231. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  80232. if( !isView && !IsVirtual(pTab) ){
  80233. destroyTable(pParse, pTab);
  80234. }
  80235. /* Remove the table entry from SQLite's internal schema and modify
  80236. ** the schema cookie.
  80237. */
  80238. if( IsVirtual(pTab) ){
  80239. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  80240. }
  80241. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  80242. sqlite3ChangeCookie(pParse, iDb);
  80243. sqliteViewResetAll(db, iDb);
  80244. }
  80245. /*
  80246. ** This routine is called to do the work of a DROP TABLE statement.
  80247. ** pName is the name of the table to be dropped.
  80248. */
  80249. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  80250. Table *pTab;
  80251. Vdbe *v;
  80252. sqlite3 *db = pParse->db;
  80253. int iDb;
  80254. if( db->mallocFailed ){
  80255. goto exit_drop_table;
  80256. }
  80257. assert( pParse->nErr==0 );
  80258. assert( pName->nSrc==1 );
  80259. if( noErr ) db->suppressErr++;
  80260. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  80261. if( noErr ) db->suppressErr--;
  80262. if( pTab==0 ){
  80263. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  80264. goto exit_drop_table;
  80265. }
  80266. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  80267. assert( iDb>=0 && iDb<db->nDb );
  80268. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  80269. ** it is initialized.
  80270. */
  80271. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  80272. goto exit_drop_table;
  80273. }
  80274. #ifndef SQLITE_OMIT_AUTHORIZATION
  80275. {
  80276. int code;
  80277. const char *zTab = SCHEMA_TABLE(iDb);
  80278. const char *zDb = db->aDb[iDb].zName;
  80279. const char *zArg2 = 0;
  80280. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  80281. goto exit_drop_table;
  80282. }
  80283. if( isView ){
  80284. if( !OMIT_TEMPDB && iDb==1 ){
  80285. code = SQLITE_DROP_TEMP_VIEW;
  80286. }else{
  80287. code = SQLITE_DROP_VIEW;
  80288. }
  80289. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80290. }else if( IsVirtual(pTab) ){
  80291. code = SQLITE_DROP_VTABLE;
  80292. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  80293. #endif
  80294. }else{
  80295. if( !OMIT_TEMPDB && iDb==1 ){
  80296. code = SQLITE_DROP_TEMP_TABLE;
  80297. }else{
  80298. code = SQLITE_DROP_TABLE;
  80299. }
  80300. }
  80301. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  80302. goto exit_drop_table;
  80303. }
  80304. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  80305. goto exit_drop_table;
  80306. }
  80307. }
  80308. #endif
  80309. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  80310. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  80311. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  80312. goto exit_drop_table;
  80313. }
  80314. #ifndef SQLITE_OMIT_VIEW
  80315. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  80316. ** on a table.
  80317. */
  80318. if( isView && pTab->pSelect==0 ){
  80319. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  80320. goto exit_drop_table;
  80321. }
  80322. if( !isView && pTab->pSelect ){
  80323. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  80324. goto exit_drop_table;
  80325. }
  80326. #endif
  80327. /* Generate code to remove the table from the master table
  80328. ** on disk.
  80329. */
  80330. v = sqlite3GetVdbe(pParse);
  80331. if( v ){
  80332. sqlite3BeginWriteOperation(pParse, 1, iDb);
  80333. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  80334. sqlite3FkDropTable(pParse, pName, pTab);
  80335. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  80336. }
  80337. exit_drop_table:
  80338. sqlite3SrcListDelete(db, pName);
  80339. }
  80340. /*
  80341. ** This routine is called to create a new foreign key on the table
  80342. ** currently under construction. pFromCol determines which columns
  80343. ** in the current table point to the foreign key. If pFromCol==0 then
  80344. ** connect the key to the last column inserted. pTo is the name of
  80345. ** the table referred to. pToCol is a list of tables in the other
  80346. ** pTo table that the foreign key points to. flags contains all
  80347. ** information about the conflict resolution algorithms specified
  80348. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  80349. **
  80350. ** An FKey structure is created and added to the table currently
  80351. ** under construction in the pParse->pNewTable field.
  80352. **
  80353. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  80354. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  80355. */
  80356. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  80357. Parse *pParse, /* Parsing context */
  80358. ExprList *pFromCol, /* Columns in this table that point to other table */
  80359. Token *pTo, /* Name of the other table */
  80360. ExprList *pToCol, /* Columns in the other table */
  80361. int flags /* Conflict resolution algorithms. */
  80362. ){
  80363. sqlite3 *db = pParse->db;
  80364. #ifndef SQLITE_OMIT_FOREIGN_KEY
  80365. FKey *pFKey = 0;
  80366. FKey *pNextTo;
  80367. Table *p = pParse->pNewTable;
  80368. int nByte;
  80369. int i;
  80370. int nCol;
  80371. char *z;
  80372. assert( pTo!=0 );
  80373. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  80374. if( pFromCol==0 ){
  80375. int iCol = p->nCol-1;
  80376. if( NEVER(iCol<0) ) goto fk_end;
  80377. if( pToCol && pToCol->nExpr!=1 ){
  80378. sqlite3ErrorMsg(pParse, "foreign key on %s"
  80379. " should reference only one column of table %T",
  80380. p->aCol[iCol].zName, pTo);
  80381. goto fk_end;
  80382. }
  80383. nCol = 1;
  80384. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  80385. sqlite3ErrorMsg(pParse,
  80386. "number of columns in foreign key does not match the number of "
  80387. "columns in the referenced table");
  80388. goto fk_end;
  80389. }else{
  80390. nCol = pFromCol->nExpr;
  80391. }
  80392. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  80393. if( pToCol ){
  80394. for(i=0; i<pToCol->nExpr; i++){
  80395. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  80396. }
  80397. }
  80398. pFKey = sqlite3DbMallocZero(db, nByte );
  80399. if( pFKey==0 ){
  80400. goto fk_end;
  80401. }
  80402. pFKey->pFrom = p;
  80403. pFKey->pNextFrom = p->pFKey;
  80404. z = (char*)&pFKey->aCol[nCol];
  80405. pFKey->zTo = z;
  80406. memcpy(z, pTo->z, pTo->n);
  80407. z[pTo->n] = 0;
  80408. sqlite3Dequote(z);
  80409. z += pTo->n+1;
  80410. pFKey->nCol = nCol;
  80411. if( pFromCol==0 ){
  80412. pFKey->aCol[0].iFrom = p->nCol-1;
  80413. }else{
  80414. for(i=0; i<nCol; i++){
  80415. int j;
  80416. for(j=0; j<p->nCol; j++){
  80417. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  80418. pFKey->aCol[i].iFrom = j;
  80419. break;
  80420. }
  80421. }
  80422. if( j>=p->nCol ){
  80423. sqlite3ErrorMsg(pParse,
  80424. "unknown column \"%s\" in foreign key definition",
  80425. pFromCol->a[i].zName);
  80426. goto fk_end;
  80427. }
  80428. }
  80429. }
  80430. if( pToCol ){
  80431. for(i=0; i<nCol; i++){
  80432. int n = sqlite3Strlen30(pToCol->a[i].zName);
  80433. pFKey->aCol[i].zCol = z;
  80434. memcpy(z, pToCol->a[i].zName, n);
  80435. z[n] = 0;
  80436. z += n+1;
  80437. }
  80438. }
  80439. pFKey->isDeferred = 0;
  80440. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  80441. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  80442. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  80443. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  80444. pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
  80445. );
  80446. if( pNextTo==pFKey ){
  80447. db->mallocFailed = 1;
  80448. goto fk_end;
  80449. }
  80450. if( pNextTo ){
  80451. assert( pNextTo->pPrevTo==0 );
  80452. pFKey->pNextTo = pNextTo;
  80453. pNextTo->pPrevTo = pFKey;
  80454. }
  80455. /* Link the foreign key to the table as the last step.
  80456. */
  80457. p->pFKey = pFKey;
  80458. pFKey = 0;
  80459. fk_end:
  80460. sqlite3DbFree(db, pFKey);
  80461. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  80462. sqlite3ExprListDelete(db, pFromCol);
  80463. sqlite3ExprListDelete(db, pToCol);
  80464. }
  80465. /*
  80466. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  80467. ** clause is seen as part of a foreign key definition. The isDeferred
  80468. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  80469. ** The behavior of the most recently created foreign key is adjusted
  80470. ** accordingly.
  80471. */
  80472. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  80473. #ifndef SQLITE_OMIT_FOREIGN_KEY
  80474. Table *pTab;
  80475. FKey *pFKey;
  80476. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  80477. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  80478. pFKey->isDeferred = (u8)isDeferred;
  80479. #endif
  80480. }
  80481. /*
  80482. ** Generate code that will erase and refill index *pIdx. This is
  80483. ** used to initialize a newly created index or to recompute the
  80484. ** content of an index in response to a REINDEX command.
  80485. **
  80486. ** if memRootPage is not negative, it means that the index is newly
  80487. ** created. The register specified by memRootPage contains the
  80488. ** root page number of the index. If memRootPage is negative, then
  80489. ** the index already exists and must be cleared before being refilled and
  80490. ** the root page number of the index is taken from pIndex->tnum.
  80491. */
  80492. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  80493. Table *pTab = pIndex->pTable; /* The table that is indexed */
  80494. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  80495. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  80496. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  80497. int addr1; /* Address of top of loop */
  80498. int addr2; /* Address to jump to for next iteration */
  80499. int tnum; /* Root page of index */
  80500. int iPartIdxLabel; /* Jump to this label to skip a row */
  80501. Vdbe *v; /* Generate code into this virtual machine */
  80502. KeyInfo *pKey; /* KeyInfo for index */
  80503. int regRecord; /* Register holding assemblied index record */
  80504. sqlite3 *db = pParse->db; /* The database connection */
  80505. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  80506. #ifndef SQLITE_OMIT_AUTHORIZATION
  80507. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  80508. db->aDb[iDb].zName ) ){
  80509. return;
  80510. }
  80511. #endif
  80512. /* Require a write-lock on the table to perform this operation */
  80513. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  80514. v = sqlite3GetVdbe(pParse);
  80515. if( v==0 ) return;
  80516. if( memRootPage>=0 ){
  80517. tnum = memRootPage;
  80518. }else{
  80519. tnum = pIndex->tnum;
  80520. sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  80521. }
  80522. pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  80523. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  80524. (char *)pKey, P4_KEYINFO_HANDOFF);
  80525. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  80526. /* Open the sorter cursor if we are to use one. */
  80527. iSorter = pParse->nTab++;
  80528. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
  80529. /* Open the table. Loop through all rows of the table, inserting index
  80530. ** records into the sorter. */
  80531. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  80532. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  80533. regRecord = sqlite3GetTempReg(pParse);
  80534. sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel);
  80535. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  80536. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  80537. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  80538. sqlite3VdbeJumpHere(v, addr1);
  80539. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
  80540. if( pIndex->onError!=OE_None ){
  80541. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  80542. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  80543. addr2 = sqlite3VdbeCurrentAddr(v);
  80544. sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
  80545. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  80546. OE_Abort, "indexed columns are not unique", P4_STATIC
  80547. );
  80548. }else{
  80549. addr2 = sqlite3VdbeCurrentAddr(v);
  80550. }
  80551. sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
  80552. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  80553. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  80554. sqlite3ReleaseTempReg(pParse, regRecord);
  80555. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
  80556. sqlite3VdbeJumpHere(v, addr1);
  80557. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  80558. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  80559. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  80560. }
  80561. /*
  80562. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  80563. ** and pTblList is the name of the table that is to be indexed. Both will
  80564. ** be NULL for a primary key or an index that is created to satisfy a
  80565. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  80566. ** as the table to be indexed. pParse->pNewTable is a table that is
  80567. ** currently being constructed by a CREATE TABLE statement.
  80568. **
  80569. ** pList is a list of columns to be indexed. pList will be NULL if this
  80570. ** is a primary key or unique-constraint on the most recent column added
  80571. ** to the table currently under construction.
  80572. **
  80573. ** If the index is created successfully, return a pointer to the new Index
  80574. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  80575. ** as the tables primary key (Index.autoIndex==2).
  80576. */
  80577. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  80578. Parse *pParse, /* All information about this parse */
  80579. Token *pName1, /* First part of index name. May be NULL */
  80580. Token *pName2, /* Second part of index name. May be NULL */
  80581. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  80582. ExprList *pList, /* A list of columns to be indexed */
  80583. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  80584. Token *pStart, /* The CREATE token that begins this statement */
  80585. Expr *pPIWhere, /* WHERE clause for partial indices */
  80586. int sortOrder, /* Sort order of primary key when pList==NULL */
  80587. int ifNotExist /* Omit error if index already exists */
  80588. ){
  80589. Index *pRet = 0; /* Pointer to return */
  80590. Table *pTab = 0; /* Table to be indexed */
  80591. Index *pIndex = 0; /* The index to be created */
  80592. char *zName = 0; /* Name of the index */
  80593. int nName; /* Number of characters in zName */
  80594. int i, j;
  80595. Token nullId; /* Fake token for an empty ID list */
  80596. DbFixer sFix; /* For assigning database names to pTable */
  80597. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  80598. sqlite3 *db = pParse->db;
  80599. Db *pDb; /* The specific table containing the indexed database */
  80600. int iDb; /* Index of the database that is being written */
  80601. Token *pName = 0; /* Unqualified name of the index to create */
  80602. struct ExprList_item *pListItem; /* For looping over pList */
  80603. const Column *pTabCol; /* A column in the table */
  80604. int nCol; /* Number of columns */
  80605. int nExtra = 0; /* Space allocated for zExtra[] */
  80606. char *zExtra; /* Extra space after the Index object */
  80607. assert( pParse->nErr==0 ); /* Never called with prior errors */
  80608. if( db->mallocFailed || IN_DECLARE_VTAB ){
  80609. goto exit_create_index;
  80610. }
  80611. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  80612. goto exit_create_index;
  80613. }
  80614. /*
  80615. ** Find the table that is to be indexed. Return early if not found.
  80616. */
  80617. if( pTblName!=0 ){
  80618. /* Use the two-part index name to determine the database
  80619. ** to search for the table. 'Fix' the table name to this db
  80620. ** before looking up the table.
  80621. */
  80622. assert( pName1 && pName2 );
  80623. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  80624. if( iDb<0 ) goto exit_create_index;
  80625. assert( pName && pName->z );
  80626. #ifndef SQLITE_OMIT_TEMPDB
  80627. /* If the index name was unqualified, check if the table
  80628. ** is a temp table. If so, set the database to 1. Do not do this
  80629. ** if initialising a database schema.
  80630. */
  80631. if( !db->init.busy ){
  80632. pTab = sqlite3SrcListLookup(pParse, pTblName);
  80633. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  80634. iDb = 1;
  80635. }
  80636. }
  80637. #endif
  80638. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  80639. if( sqlite3FixSrcList(&sFix, pTblName) ){
  80640. /* Because the parser constructs pTblName from a single identifier,
  80641. ** sqlite3FixSrcList can never fail. */
  80642. assert(0);
  80643. }
  80644. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  80645. assert( db->mallocFailed==0 || pTab==0 );
  80646. if( pTab==0 ) goto exit_create_index;
  80647. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  80648. sqlite3ErrorMsg(pParse,
  80649. "cannot create a TEMP index on non-TEMP table \"%s\"",
  80650. pTab->zName);
  80651. goto exit_create_index;
  80652. }
  80653. }else{
  80654. assert( pName==0 );
  80655. assert( pStart==0 );
  80656. pTab = pParse->pNewTable;
  80657. if( !pTab ) goto exit_create_index;
  80658. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  80659. }
  80660. pDb = &db->aDb[iDb];
  80661. assert( pTab!=0 );
  80662. assert( pParse->nErr==0 );
  80663. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  80664. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  80665. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  80666. goto exit_create_index;
  80667. }
  80668. #ifndef SQLITE_OMIT_VIEW
  80669. if( pTab->pSelect ){
  80670. sqlite3ErrorMsg(pParse, "views may not be indexed");
  80671. goto exit_create_index;
  80672. }
  80673. #endif
  80674. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80675. if( IsVirtual(pTab) ){
  80676. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  80677. goto exit_create_index;
  80678. }
  80679. #endif
  80680. /*
  80681. ** Find the name of the index. Make sure there is not already another
  80682. ** index or table with the same name.
  80683. **
  80684. ** Exception: If we are reading the names of permanent indices from the
  80685. ** sqlite_master table (because some other process changed the schema) and
  80686. ** one of the index names collides with the name of a temporary table or
  80687. ** index, then we will continue to process this index.
  80688. **
  80689. ** If pName==0 it means that we are
  80690. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  80691. ** own name.
  80692. */
  80693. if( pName ){
  80694. zName = sqlite3NameFromToken(db, pName);
  80695. if( zName==0 ) goto exit_create_index;
  80696. assert( pName->z!=0 );
  80697. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  80698. goto exit_create_index;
  80699. }
  80700. if( !db->init.busy ){
  80701. if( sqlite3FindTable(db, zName, 0)!=0 ){
  80702. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  80703. goto exit_create_index;
  80704. }
  80705. }
  80706. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  80707. if( !ifNotExist ){
  80708. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  80709. }else{
  80710. assert( !db->init.busy );
  80711. sqlite3CodeVerifySchema(pParse, iDb);
  80712. }
  80713. goto exit_create_index;
  80714. }
  80715. }else{
  80716. int n;
  80717. Index *pLoop;
  80718. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  80719. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  80720. if( zName==0 ){
  80721. goto exit_create_index;
  80722. }
  80723. }
  80724. /* Check for authorization to create an index.
  80725. */
  80726. #ifndef SQLITE_OMIT_AUTHORIZATION
  80727. {
  80728. const char *zDb = pDb->zName;
  80729. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  80730. goto exit_create_index;
  80731. }
  80732. i = SQLITE_CREATE_INDEX;
  80733. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  80734. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  80735. goto exit_create_index;
  80736. }
  80737. }
  80738. #endif
  80739. /* If pList==0, it means this routine was called to make a primary
  80740. ** key out of the last column added to the table under construction.
  80741. ** So create a fake list to simulate this.
  80742. */
  80743. if( pList==0 ){
  80744. nullId.z = pTab->aCol[pTab->nCol-1].zName;
  80745. nullId.n = sqlite3Strlen30((char*)nullId.z);
  80746. pList = sqlite3ExprListAppend(pParse, 0, 0);
  80747. if( pList==0 ) goto exit_create_index;
  80748. sqlite3ExprListSetName(pParse, pList, &nullId, 0);
  80749. pList->a[0].sortOrder = (u8)sortOrder;
  80750. }
  80751. /* Figure out how many bytes of space are required to store explicitly
  80752. ** specified collation sequence names.
  80753. */
  80754. for(i=0; i<pList->nExpr; i++){
  80755. Expr *pExpr = pList->a[i].pExpr;
  80756. if( pExpr ){
  80757. assert( pExpr->op==TK_COLLATE );
  80758. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  80759. }
  80760. }
  80761. /*
  80762. ** Allocate the index structure.
  80763. */
  80764. nName = sqlite3Strlen30(zName);
  80765. nCol = pList->nExpr;
  80766. pIndex = sqlite3DbMallocZero(db,
  80767. ROUND8(sizeof(Index)) + /* Index structure */
  80768. ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
  80769. sizeof(char *)*nCol + /* Index.azColl */
  80770. sizeof(int)*nCol + /* Index.aiColumn */
  80771. sizeof(u8)*nCol + /* Index.aSortOrder */
  80772. nName + 1 + /* Index.zName */
  80773. nExtra /* Collation sequence names */
  80774. );
  80775. if( db->mallocFailed ){
  80776. goto exit_create_index;
  80777. }
  80778. zExtra = (char*)pIndex;
  80779. pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
  80780. pIndex->azColl = (char**)
  80781. ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
  80782. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
  80783. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  80784. pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  80785. pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
  80786. pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  80787. zExtra = (char *)(&pIndex->zName[nName+1]);
  80788. memcpy(pIndex->zName, zName, nName+1);
  80789. pIndex->pTable = pTab;
  80790. pIndex->nColumn = pList->nExpr;
  80791. pIndex->onError = (u8)onError;
  80792. pIndex->uniqNotNull = onError==OE_Abort;
  80793. pIndex->autoIndex = (u8)(pName==0);
  80794. pIndex->pSchema = db->aDb[iDb].pSchema;
  80795. if( pPIWhere ){
  80796. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  80797. pIndex->pPartIdxWhere = pPIWhere;
  80798. pPIWhere = 0;
  80799. }
  80800. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80801. /* Check to see if we should honor DESC requests on index columns
  80802. */
  80803. if( pDb->pSchema->file_format>=4 ){
  80804. sortOrderMask = -1; /* Honor DESC */
  80805. }else{
  80806. sortOrderMask = 0; /* Ignore DESC */
  80807. }
  80808. /* Scan the names of the columns of the table to be indexed and
  80809. ** load the column indices into the Index structure. Report an error
  80810. ** if any column is not found.
  80811. **
  80812. ** TODO: Add a test to make sure that the same column is not named
  80813. ** more than once within the same index. Only the first instance of
  80814. ** the column will ever be used by the optimizer. Note that using the
  80815. ** same column more than once cannot be an error because that would
  80816. ** break backwards compatibility - it needs to be a warning.
  80817. */
  80818. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  80819. const char *zColName = pListItem->zName;
  80820. int requestedSortOrder;
  80821. char *zColl; /* Collation sequence name */
  80822. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  80823. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  80824. }
  80825. if( j>=pTab->nCol ){
  80826. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  80827. pTab->zName, zColName);
  80828. pParse->checkSchema = 1;
  80829. goto exit_create_index;
  80830. }
  80831. pIndex->aiColumn[i] = j;
  80832. if( pListItem->pExpr ){
  80833. int nColl;
  80834. assert( pListItem->pExpr->op==TK_COLLATE );
  80835. zColl = pListItem->pExpr->u.zToken;
  80836. nColl = sqlite3Strlen30(zColl) + 1;
  80837. assert( nExtra>=nColl );
  80838. memcpy(zExtra, zColl, nColl);
  80839. zColl = zExtra;
  80840. zExtra += nColl;
  80841. nExtra -= nColl;
  80842. }else{
  80843. zColl = pTab->aCol[j].zColl;
  80844. if( !zColl ) zColl = "BINARY";
  80845. }
  80846. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  80847. goto exit_create_index;
  80848. }
  80849. pIndex->azColl[i] = zColl;
  80850. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  80851. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  80852. if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
  80853. }
  80854. sqlite3DefaultRowEst(pIndex);
  80855. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  80856. if( pTab==pParse->pNewTable ){
  80857. /* This routine has been called to create an automatic index as a
  80858. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  80859. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  80860. ** i.e. one of:
  80861. **
  80862. ** CREATE TABLE t(x PRIMARY KEY, y);
  80863. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  80864. **
  80865. ** Either way, check to see if the table already has such an index. If
  80866. ** so, don't bother creating this one. This only applies to
  80867. ** automatically created indices. Users can do as they wish with
  80868. ** explicit indices.
  80869. **
  80870. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  80871. ** (and thus suppressing the second one) even if they have different
  80872. ** sort orders.
  80873. **
  80874. ** If there are different collating sequences or if the columns of
  80875. ** the constraint occur in different orders, then the constraints are
  80876. ** considered distinct and both result in separate indices.
  80877. */
  80878. Index *pIdx;
  80879. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  80880. int k;
  80881. assert( pIdx->onError!=OE_None );
  80882. assert( pIdx->autoIndex );
  80883. assert( pIndex->onError!=OE_None );
  80884. if( pIdx->nColumn!=pIndex->nColumn ) continue;
  80885. for(k=0; k<pIdx->nColumn; k++){
  80886. const char *z1;
  80887. const char *z2;
  80888. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  80889. z1 = pIdx->azColl[k];
  80890. z2 = pIndex->azColl[k];
  80891. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  80892. }
  80893. if( k==pIdx->nColumn ){
  80894. if( pIdx->onError!=pIndex->onError ){
  80895. /* This constraint creates the same index as a previous
  80896. ** constraint specified somewhere in the CREATE TABLE statement.
  80897. ** However the ON CONFLICT clauses are different. If both this
  80898. ** constraint and the previous equivalent constraint have explicit
  80899. ** ON CONFLICT clauses this is an error. Otherwise, use the
  80900. ** explicitly specified behavior for the index.
  80901. */
  80902. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  80903. sqlite3ErrorMsg(pParse,
  80904. "conflicting ON CONFLICT clauses specified", 0);
  80905. }
  80906. if( pIdx->onError==OE_Default ){
  80907. pIdx->onError = pIndex->onError;
  80908. }
  80909. }
  80910. goto exit_create_index;
  80911. }
  80912. }
  80913. }
  80914. /* Link the new Index structure to its table and to the other
  80915. ** in-memory database structures.
  80916. */
  80917. if( db->init.busy ){
  80918. Index *p;
  80919. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  80920. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  80921. pIndex->zName, sqlite3Strlen30(pIndex->zName),
  80922. pIndex);
  80923. if( p ){
  80924. assert( p==pIndex ); /* Malloc must have failed */
  80925. db->mallocFailed = 1;
  80926. goto exit_create_index;
  80927. }
  80928. db->flags |= SQLITE_InternChanges;
  80929. if( pTblName!=0 ){
  80930. pIndex->tnum = db->init.newTnum;
  80931. }
  80932. }
  80933. /* If the db->init.busy is 0 then create the index on disk. This
  80934. ** involves writing the index into the master table and filling in the
  80935. ** index with the current table contents.
  80936. **
  80937. ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  80938. ** command. db->init.busy is 1 when a database is opened and
  80939. ** CREATE INDEX statements are read out of the master table. In
  80940. ** the latter case the index already exists on disk, which is why
  80941. ** we don't want to recreate it.
  80942. **
  80943. ** If pTblName==0 it means this index is generated as a primary key
  80944. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  80945. ** has just been created, it contains no data and the index initialization
  80946. ** step can be skipped.
  80947. */
  80948. else if( pParse->nErr==0 ){
  80949. Vdbe *v;
  80950. char *zStmt;
  80951. int iMem = ++pParse->nMem;
  80952. v = sqlite3GetVdbe(pParse);
  80953. if( v==0 ) goto exit_create_index;
  80954. /* Create the rootpage for the index
  80955. */
  80956. sqlite3BeginWriteOperation(pParse, 1, iDb);
  80957. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  80958. /* Gather the complete text of the CREATE INDEX statement into
  80959. ** the zStmt variable
  80960. */
  80961. if( pStart ){
  80962. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  80963. if( pName->z[n-1]==';' ) n--;
  80964. /* A named index with an explicit CREATE INDEX statement */
  80965. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  80966. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  80967. }else{
  80968. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  80969. /* zStmt = sqlite3MPrintf(""); */
  80970. zStmt = 0;
  80971. }
  80972. /* Add an entry in sqlite_master for this index
  80973. */
  80974. sqlite3NestedParse(pParse,
  80975. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  80976. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  80977. pIndex->zName,
  80978. pTab->zName,
  80979. iMem,
  80980. zStmt
  80981. );
  80982. sqlite3DbFree(db, zStmt);
  80983. /* Fill the index with data and reparse the schema. Code an OP_Expire
  80984. ** to invalidate all pre-compiled statements.
  80985. */
  80986. if( pTblName ){
  80987. sqlite3RefillIndex(pParse, pIndex, iMem);
  80988. sqlite3ChangeCookie(pParse, iDb);
  80989. sqlite3VdbeAddParseSchemaOp(v, iDb,
  80990. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  80991. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  80992. }
  80993. }
  80994. /* When adding an index to the list of indices for a table, make
  80995. ** sure all indices labeled OE_Replace come after all those labeled
  80996. ** OE_Ignore. This is necessary for the correct constraint check
  80997. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  80998. ** UPDATE and INSERT statements.
  80999. */
  81000. if( db->init.busy || pTblName==0 ){
  81001. if( onError!=OE_Replace || pTab->pIndex==0
  81002. || pTab->pIndex->onError==OE_Replace){
  81003. pIndex->pNext = pTab->pIndex;
  81004. pTab->pIndex = pIndex;
  81005. }else{
  81006. Index *pOther = pTab->pIndex;
  81007. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  81008. pOther = pOther->pNext;
  81009. }
  81010. pIndex->pNext = pOther->pNext;
  81011. pOther->pNext = pIndex;
  81012. }
  81013. pRet = pIndex;
  81014. pIndex = 0;
  81015. }
  81016. /* Clean up before exiting */
  81017. exit_create_index:
  81018. if( pIndex ) freeIndex(db, pIndex);
  81019. sqlite3ExprDelete(db, pPIWhere);
  81020. sqlite3ExprListDelete(db, pList);
  81021. sqlite3SrcListDelete(db, pTblName);
  81022. sqlite3DbFree(db, zName);
  81023. return pRet;
  81024. }
  81025. /*
  81026. ** Fill the Index.aiRowEst[] array with default information - information
  81027. ** to be used when we have not run the ANALYZE command.
  81028. **
  81029. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  81030. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  81031. ** number of rows in the table that match any particular value of the
  81032. ** first column of the index. aiRowEst[2] is an estimate of the number
  81033. ** of rows that match any particular combiniation of the first 2 columns
  81034. ** of the index. And so forth. It must always be the case that
  81035. *
  81036. ** aiRowEst[N]<=aiRowEst[N-1]
  81037. ** aiRowEst[N]>=1
  81038. **
  81039. ** Apart from that, we have little to go on besides intuition as to
  81040. ** how aiRowEst[] should be initialized. The numbers generated here
  81041. ** are based on typical values found in actual indices.
  81042. */
  81043. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  81044. tRowcnt *a = pIdx->aiRowEst;
  81045. int i;
  81046. tRowcnt n;
  81047. assert( a!=0 );
  81048. a[0] = pIdx->pTable->nRowEst;
  81049. if( a[0]<10 ) a[0] = 10;
  81050. n = 10;
  81051. for(i=1; i<=pIdx->nColumn; i++){
  81052. a[i] = n;
  81053. if( n>5 ) n--;
  81054. }
  81055. if( pIdx->onError!=OE_None ){
  81056. a[pIdx->nColumn] = 1;
  81057. }
  81058. }
  81059. /*
  81060. ** This routine will drop an existing named index. This routine
  81061. ** implements the DROP INDEX statement.
  81062. */
  81063. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  81064. Index *pIndex;
  81065. Vdbe *v;
  81066. sqlite3 *db = pParse->db;
  81067. int iDb;
  81068. assert( pParse->nErr==0 ); /* Never called with prior errors */
  81069. if( db->mallocFailed ){
  81070. goto exit_drop_index;
  81071. }
  81072. assert( pName->nSrc==1 );
  81073. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  81074. goto exit_drop_index;
  81075. }
  81076. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  81077. if( pIndex==0 ){
  81078. if( !ifExists ){
  81079. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  81080. }else{
  81081. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  81082. }
  81083. pParse->checkSchema = 1;
  81084. goto exit_drop_index;
  81085. }
  81086. if( pIndex->autoIndex ){
  81087. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  81088. "or PRIMARY KEY constraint cannot be dropped", 0);
  81089. goto exit_drop_index;
  81090. }
  81091. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  81092. #ifndef SQLITE_OMIT_AUTHORIZATION
  81093. {
  81094. int code = SQLITE_DROP_INDEX;
  81095. Table *pTab = pIndex->pTable;
  81096. const char *zDb = db->aDb[iDb].zName;
  81097. const char *zTab = SCHEMA_TABLE(iDb);
  81098. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  81099. goto exit_drop_index;
  81100. }
  81101. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  81102. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  81103. goto exit_drop_index;
  81104. }
  81105. }
  81106. #endif
  81107. /* Generate code to remove the index and from the master table */
  81108. v = sqlite3GetVdbe(pParse);
  81109. if( v ){
  81110. sqlite3BeginWriteOperation(pParse, 1, iDb);
  81111. sqlite3NestedParse(pParse,
  81112. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  81113. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  81114. );
  81115. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  81116. sqlite3ChangeCookie(pParse, iDb);
  81117. destroyRootPage(pParse, pIndex->tnum, iDb);
  81118. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  81119. }
  81120. exit_drop_index:
  81121. sqlite3SrcListDelete(db, pName);
  81122. }
  81123. /*
  81124. ** pArray is a pointer to an array of objects. Each object in the
  81125. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  81126. ** to extend the array so that there is space for a new object at the end.
  81127. **
  81128. ** When this function is called, *pnEntry contains the current size of
  81129. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  81130. ** in total).
  81131. **
  81132. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  81133. ** space allocated for the new object is zeroed, *pnEntry updated to
  81134. ** reflect the new size of the array and a pointer to the new allocation
  81135. ** returned. *pIdx is set to the index of the new array entry in this case.
  81136. **
  81137. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  81138. ** unchanged and a copy of pArray returned.
  81139. */
  81140. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  81141. sqlite3 *db, /* Connection to notify of malloc failures */
  81142. void *pArray, /* Array of objects. Might be reallocated */
  81143. int szEntry, /* Size of each object in the array */
  81144. int *pnEntry, /* Number of objects currently in use */
  81145. int *pIdx /* Write the index of a new slot here */
  81146. ){
  81147. char *z;
  81148. int n = *pnEntry;
  81149. if( (n & (n-1))==0 ){
  81150. int sz = (n==0) ? 1 : 2*n;
  81151. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  81152. if( pNew==0 ){
  81153. *pIdx = -1;
  81154. return pArray;
  81155. }
  81156. pArray = pNew;
  81157. }
  81158. z = (char*)pArray;
  81159. memset(&z[n * szEntry], 0, szEntry);
  81160. *pIdx = n;
  81161. ++*pnEntry;
  81162. return pArray;
  81163. }
  81164. /*
  81165. ** Append a new element to the given IdList. Create a new IdList if
  81166. ** need be.
  81167. **
  81168. ** A new IdList is returned, or NULL if malloc() fails.
  81169. */
  81170. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  81171. int i;
  81172. if( pList==0 ){
  81173. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  81174. if( pList==0 ) return 0;
  81175. }
  81176. pList->a = sqlite3ArrayAllocate(
  81177. db,
  81178. pList->a,
  81179. sizeof(pList->a[0]),
  81180. &pList->nId,
  81181. &i
  81182. );
  81183. if( i<0 ){
  81184. sqlite3IdListDelete(db, pList);
  81185. return 0;
  81186. }
  81187. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  81188. return pList;
  81189. }
  81190. /*
  81191. ** Delete an IdList.
  81192. */
  81193. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  81194. int i;
  81195. if( pList==0 ) return;
  81196. for(i=0; i<pList->nId; i++){
  81197. sqlite3DbFree(db, pList->a[i].zName);
  81198. }
  81199. sqlite3DbFree(db, pList->a);
  81200. sqlite3DbFree(db, pList);
  81201. }
  81202. /*
  81203. ** Return the index in pList of the identifier named zId. Return -1
  81204. ** if not found.
  81205. */
  81206. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  81207. int i;
  81208. if( pList==0 ) return -1;
  81209. for(i=0; i<pList->nId; i++){
  81210. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  81211. }
  81212. return -1;
  81213. }
  81214. /*
  81215. ** Expand the space allocated for the given SrcList object by
  81216. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  81217. ** New slots are zeroed.
  81218. **
  81219. ** For example, suppose a SrcList initially contains two entries: A,B.
  81220. ** To append 3 new entries onto the end, do this:
  81221. **
  81222. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  81223. **
  81224. ** After the call above it would contain: A, B, nil, nil, nil.
  81225. ** If the iStart argument had been 1 instead of 2, then the result
  81226. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  81227. ** the iStart value would be 0. The result then would
  81228. ** be: nil, nil, nil, A, B.
  81229. **
  81230. ** If a memory allocation fails the SrcList is unchanged. The
  81231. ** db->mallocFailed flag will be set to true.
  81232. */
  81233. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  81234. sqlite3 *db, /* Database connection to notify of OOM errors */
  81235. SrcList *pSrc, /* The SrcList to be enlarged */
  81236. int nExtra, /* Number of new slots to add to pSrc->a[] */
  81237. int iStart /* Index in pSrc->a[] of first new slot */
  81238. ){
  81239. int i;
  81240. /* Sanity checking on calling parameters */
  81241. assert( iStart>=0 );
  81242. assert( nExtra>=1 );
  81243. assert( pSrc!=0 );
  81244. assert( iStart<=pSrc->nSrc );
  81245. /* Allocate additional space if needed */
  81246. if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
  81247. SrcList *pNew;
  81248. int nAlloc = pSrc->nSrc+nExtra;
  81249. int nGot;
  81250. pNew = sqlite3DbRealloc(db, pSrc,
  81251. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  81252. if( pNew==0 ){
  81253. assert( db->mallocFailed );
  81254. return pSrc;
  81255. }
  81256. pSrc = pNew;
  81257. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  81258. pSrc->nAlloc = (u8)nGot;
  81259. }
  81260. /* Move existing slots that come after the newly inserted slots
  81261. ** out of the way */
  81262. for(i=pSrc->nSrc-1; i>=iStart; i--){
  81263. pSrc->a[i+nExtra] = pSrc->a[i];
  81264. }
  81265. pSrc->nSrc += (i8)nExtra;
  81266. /* Zero the newly allocated slots */
  81267. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  81268. for(i=iStart; i<iStart+nExtra; i++){
  81269. pSrc->a[i].iCursor = -1;
  81270. }
  81271. /* Return a pointer to the enlarged SrcList */
  81272. return pSrc;
  81273. }
  81274. /*
  81275. ** Append a new table name to the given SrcList. Create a new SrcList if
  81276. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  81277. **
  81278. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  81279. ** SrcList might be the same as the SrcList that was input or it might be
  81280. ** a new one. If an OOM error does occurs, then the prior value of pList
  81281. ** that is input to this routine is automatically freed.
  81282. **
  81283. ** If pDatabase is not null, it means that the table has an optional
  81284. ** database name prefix. Like this: "database.table". The pDatabase
  81285. ** points to the table name and the pTable points to the database name.
  81286. ** The SrcList.a[].zName field is filled with the table name which might
  81287. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  81288. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  81289. ** or with NULL if no database is specified.
  81290. **
  81291. ** In other words, if call like this:
  81292. **
  81293. ** sqlite3SrcListAppend(D,A,B,0);
  81294. **
  81295. ** Then B is a table name and the database name is unspecified. If called
  81296. ** like this:
  81297. **
  81298. ** sqlite3SrcListAppend(D,A,B,C);
  81299. **
  81300. ** Then C is the table name and B is the database name. If C is defined
  81301. ** then so is B. In other words, we never have a case where:
  81302. **
  81303. ** sqlite3SrcListAppend(D,A,0,C);
  81304. **
  81305. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  81306. ** before being added to the SrcList.
  81307. */
  81308. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  81309. sqlite3 *db, /* Connection to notify of malloc failures */
  81310. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  81311. Token *pTable, /* Table to append */
  81312. Token *pDatabase /* Database of the table */
  81313. ){
  81314. struct SrcList_item *pItem;
  81315. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  81316. if( pList==0 ){
  81317. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  81318. if( pList==0 ) return 0;
  81319. pList->nAlloc = 1;
  81320. }
  81321. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  81322. if( db->mallocFailed ){
  81323. sqlite3SrcListDelete(db, pList);
  81324. return 0;
  81325. }
  81326. pItem = &pList->a[pList->nSrc-1];
  81327. if( pDatabase && pDatabase->z==0 ){
  81328. pDatabase = 0;
  81329. }
  81330. if( pDatabase ){
  81331. Token *pTemp = pDatabase;
  81332. pDatabase = pTable;
  81333. pTable = pTemp;
  81334. }
  81335. pItem->zName = sqlite3NameFromToken(db, pTable);
  81336. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  81337. return pList;
  81338. }
  81339. /*
  81340. ** Assign VdbeCursor index numbers to all tables in a SrcList
  81341. */
  81342. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  81343. int i;
  81344. struct SrcList_item *pItem;
  81345. assert(pList || pParse->db->mallocFailed );
  81346. if( pList ){
  81347. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  81348. if( pItem->iCursor>=0 ) break;
  81349. pItem->iCursor = pParse->nTab++;
  81350. if( pItem->pSelect ){
  81351. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  81352. }
  81353. }
  81354. }
  81355. }
  81356. /*
  81357. ** Delete an entire SrcList including all its substructure.
  81358. */
  81359. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  81360. int i;
  81361. struct SrcList_item *pItem;
  81362. if( pList==0 ) return;
  81363. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  81364. sqlite3DbFree(db, pItem->zDatabase);
  81365. sqlite3DbFree(db, pItem->zName);
  81366. sqlite3DbFree(db, pItem->zAlias);
  81367. sqlite3DbFree(db, pItem->zIndex);
  81368. sqlite3DeleteTable(db, pItem->pTab);
  81369. sqlite3SelectDelete(db, pItem->pSelect);
  81370. sqlite3ExprDelete(db, pItem->pOn);
  81371. sqlite3IdListDelete(db, pItem->pUsing);
  81372. }
  81373. sqlite3DbFree(db, pList);
  81374. }
  81375. /*
  81376. ** This routine is called by the parser to add a new term to the
  81377. ** end of a growing FROM clause. The "p" parameter is the part of
  81378. ** the FROM clause that has already been constructed. "p" is NULL
  81379. ** if this is the first term of the FROM clause. pTable and pDatabase
  81380. ** are the name of the table and database named in the FROM clause term.
  81381. ** pDatabase is NULL if the database name qualifier is missing - the
  81382. ** usual case. If the term has a alias, then pAlias points to the
  81383. ** alias token. If the term is a subquery, then pSubquery is the
  81384. ** SELECT statement that the subquery encodes. The pTable and
  81385. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  81386. ** parameters are the content of the ON and USING clauses.
  81387. **
  81388. ** Return a new SrcList which encodes is the FROM with the new
  81389. ** term added.
  81390. */
  81391. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  81392. Parse *pParse, /* Parsing context */
  81393. SrcList *p, /* The left part of the FROM clause already seen */
  81394. Token *pTable, /* Name of the table to add to the FROM clause */
  81395. Token *pDatabase, /* Name of the database containing pTable */
  81396. Token *pAlias, /* The right-hand side of the AS subexpression */
  81397. Select *pSubquery, /* A subquery used in place of a table name */
  81398. Expr *pOn, /* The ON clause of a join */
  81399. IdList *pUsing /* The USING clause of a join */
  81400. ){
  81401. struct SrcList_item *pItem;
  81402. sqlite3 *db = pParse->db;
  81403. if( !p && (pOn || pUsing) ){
  81404. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  81405. (pOn ? "ON" : "USING")
  81406. );
  81407. goto append_from_error;
  81408. }
  81409. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  81410. if( p==0 || NEVER(p->nSrc==0) ){
  81411. goto append_from_error;
  81412. }
  81413. pItem = &p->a[p->nSrc-1];
  81414. assert( pAlias!=0 );
  81415. if( pAlias->n ){
  81416. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  81417. }
  81418. pItem->pSelect = pSubquery;
  81419. pItem->pOn = pOn;
  81420. pItem->pUsing = pUsing;
  81421. return p;
  81422. append_from_error:
  81423. assert( p==0 );
  81424. sqlite3ExprDelete(db, pOn);
  81425. sqlite3IdListDelete(db, pUsing);
  81426. sqlite3SelectDelete(db, pSubquery);
  81427. return 0;
  81428. }
  81429. /*
  81430. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  81431. ** element of the source-list passed as the second argument.
  81432. */
  81433. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  81434. assert( pIndexedBy!=0 );
  81435. if( p && ALWAYS(p->nSrc>0) ){
  81436. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  81437. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  81438. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  81439. /* A "NOT INDEXED" clause was supplied. See parse.y
  81440. ** construct "indexed_opt" for details. */
  81441. pItem->notIndexed = 1;
  81442. }else{
  81443. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  81444. }
  81445. }
  81446. }
  81447. /*
  81448. ** When building up a FROM clause in the parser, the join operator
  81449. ** is initially attached to the left operand. But the code generator
  81450. ** expects the join operator to be on the right operand. This routine
  81451. ** Shifts all join operators from left to right for an entire FROM
  81452. ** clause.
  81453. **
  81454. ** Example: Suppose the join is like this:
  81455. **
  81456. ** A natural cross join B
  81457. **
  81458. ** The operator is "natural cross join". The A and B operands are stored
  81459. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  81460. ** operator with A. This routine shifts that operator over to B.
  81461. */
  81462. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  81463. if( p ){
  81464. int i;
  81465. assert( p->a || p->nSrc==0 );
  81466. for(i=p->nSrc-1; i>0; i--){
  81467. p->a[i].jointype = p->a[i-1].jointype;
  81468. }
  81469. p->a[0].jointype = 0;
  81470. }
  81471. }
  81472. /*
  81473. ** Begin a transaction
  81474. */
  81475. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  81476. sqlite3 *db;
  81477. Vdbe *v;
  81478. int i;
  81479. assert( pParse!=0 );
  81480. db = pParse->db;
  81481. assert( db!=0 );
  81482. /* if( db->aDb[0].pBt==0 ) return; */
  81483. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  81484. return;
  81485. }
  81486. v = sqlite3GetVdbe(pParse);
  81487. if( !v ) return;
  81488. if( type!=TK_DEFERRED ){
  81489. for(i=0; i<db->nDb; i++){
  81490. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  81491. sqlite3VdbeUsesBtree(v, i);
  81492. }
  81493. }
  81494. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  81495. }
  81496. /*
  81497. ** Commit a transaction
  81498. */
  81499. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  81500. Vdbe *v;
  81501. assert( pParse!=0 );
  81502. assert( pParse->db!=0 );
  81503. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  81504. return;
  81505. }
  81506. v = sqlite3GetVdbe(pParse);
  81507. if( v ){
  81508. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  81509. }
  81510. }
  81511. /*
  81512. ** Rollback a transaction
  81513. */
  81514. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  81515. Vdbe *v;
  81516. assert( pParse!=0 );
  81517. assert( pParse->db!=0 );
  81518. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  81519. return;
  81520. }
  81521. v = sqlite3GetVdbe(pParse);
  81522. if( v ){
  81523. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  81524. }
  81525. }
  81526. /*
  81527. ** This function is called by the parser when it parses a command to create,
  81528. ** release or rollback an SQL savepoint.
  81529. */
  81530. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  81531. char *zName = sqlite3NameFromToken(pParse->db, pName);
  81532. if( zName ){
  81533. Vdbe *v = sqlite3GetVdbe(pParse);
  81534. #ifndef SQLITE_OMIT_AUTHORIZATION
  81535. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  81536. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  81537. #endif
  81538. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  81539. sqlite3DbFree(pParse->db, zName);
  81540. return;
  81541. }
  81542. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  81543. }
  81544. }
  81545. /*
  81546. ** Make sure the TEMP database is open and available for use. Return
  81547. ** the number of errors. Leave any error messages in the pParse structure.
  81548. */
  81549. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  81550. sqlite3 *db = pParse->db;
  81551. if( db->aDb[1].pBt==0 && !pParse->explain ){
  81552. int rc;
  81553. Btree *pBt;
  81554. static const int flags =
  81555. SQLITE_OPEN_READWRITE |
  81556. SQLITE_OPEN_CREATE |
  81557. SQLITE_OPEN_EXCLUSIVE |
  81558. SQLITE_OPEN_DELETEONCLOSE |
  81559. SQLITE_OPEN_TEMP_DB;
  81560. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  81561. if( rc!=SQLITE_OK ){
  81562. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  81563. "file for storing temporary tables");
  81564. pParse->rc = rc;
  81565. return 1;
  81566. }
  81567. db->aDb[1].pBt = pBt;
  81568. assert( db->aDb[1].pSchema );
  81569. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  81570. db->mallocFailed = 1;
  81571. return 1;
  81572. }
  81573. }
  81574. return 0;
  81575. }
  81576. /*
  81577. ** Generate VDBE code that will verify the schema cookie and start
  81578. ** a read-transaction for all named database files.
  81579. **
  81580. ** It is important that all schema cookies be verified and all
  81581. ** read transactions be started before anything else happens in
  81582. ** the VDBE program. But this routine can be called after much other
  81583. ** code has been generated. So here is what we do:
  81584. **
  81585. ** The first time this routine is called, we code an OP_Goto that
  81586. ** will jump to a subroutine at the end of the program. Then we
  81587. ** record every database that needs its schema verified in the
  81588. ** pParse->cookieMask field. Later, after all other code has been
  81589. ** generated, the subroutine that does the cookie verifications and
  81590. ** starts the transactions will be coded and the OP_Goto P2 value
  81591. ** will be made to point to that subroutine. The generation of the
  81592. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  81593. **
  81594. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  81595. ** schema on any databases. This can be used to position the OP_Goto
  81596. ** early in the code, before we know if any database tables will be used.
  81597. */
  81598. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  81599. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  81600. #ifndef SQLITE_OMIT_TRIGGER
  81601. if( pToplevel!=pParse ){
  81602. /* This branch is taken if a trigger is currently being coded. In this
  81603. ** case, set cookieGoto to a non-zero value to show that this function
  81604. ** has been called. This is used by the sqlite3ExprCodeConstants()
  81605. ** function. */
  81606. pParse->cookieGoto = -1;
  81607. }
  81608. #endif
  81609. if( pToplevel->cookieGoto==0 ){
  81610. Vdbe *v = sqlite3GetVdbe(pToplevel);
  81611. if( v==0 ) return; /* This only happens if there was a prior error */
  81612. pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  81613. }
  81614. if( iDb>=0 ){
  81615. sqlite3 *db = pToplevel->db;
  81616. yDbMask mask;
  81617. assert( iDb<db->nDb );
  81618. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  81619. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  81620. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81621. mask = ((yDbMask)1)<<iDb;
  81622. if( (pToplevel->cookieMask & mask)==0 ){
  81623. pToplevel->cookieMask |= mask;
  81624. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  81625. if( !OMIT_TEMPDB && iDb==1 ){
  81626. sqlite3OpenTempDatabase(pToplevel);
  81627. }
  81628. }
  81629. }
  81630. }
  81631. /*
  81632. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  81633. ** attached database. Otherwise, invoke it for the database named zDb only.
  81634. */
  81635. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  81636. sqlite3 *db = pParse->db;
  81637. int i;
  81638. for(i=0; i<db->nDb; i++){
  81639. Db *pDb = &db->aDb[i];
  81640. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  81641. sqlite3CodeVerifySchema(pParse, i);
  81642. }
  81643. }
  81644. }
  81645. /*
  81646. ** Generate VDBE code that prepares for doing an operation that
  81647. ** might change the database.
  81648. **
  81649. ** This routine starts a new transaction if we are not already within
  81650. ** a transaction. If we are already within a transaction, then a checkpoint
  81651. ** is set if the setStatement parameter is true. A checkpoint should
  81652. ** be set for operations that might fail (due to a constraint) part of
  81653. ** the way through and which will need to undo some writes without having to
  81654. ** rollback the whole transaction. For operations where all constraints
  81655. ** can be checked before any changes are made to the database, it is never
  81656. ** necessary to undo a write and the checkpoint should not be set.
  81657. */
  81658. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  81659. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  81660. sqlite3CodeVerifySchema(pParse, iDb);
  81661. pToplevel->writeMask |= ((yDbMask)1)<<iDb;
  81662. pToplevel->isMultiWrite |= setStatement;
  81663. }
  81664. /*
  81665. ** Indicate that the statement currently under construction might write
  81666. ** more than one entry (example: deleting one row then inserting another,
  81667. ** inserting multiple rows in a table, or inserting a row and index entries.)
  81668. ** If an abort occurs after some of these writes have completed, then it will
  81669. ** be necessary to undo the completed writes.
  81670. */
  81671. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  81672. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  81673. pToplevel->isMultiWrite = 1;
  81674. }
  81675. /*
  81676. ** The code generator calls this routine if is discovers that it is
  81677. ** possible to abort a statement prior to completion. In order to
  81678. ** perform this abort without corrupting the database, we need to make
  81679. ** sure that the statement is protected by a statement transaction.
  81680. **
  81681. ** Technically, we only need to set the mayAbort flag if the
  81682. ** isMultiWrite flag was previously set. There is a time dependency
  81683. ** such that the abort must occur after the multiwrite. This makes
  81684. ** some statements involving the REPLACE conflict resolution algorithm
  81685. ** go a little faster. But taking advantage of this time dependency
  81686. ** makes it more difficult to prove that the code is correct (in
  81687. ** particular, it prevents us from writing an effective
  81688. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  81689. ** to take the safe route and skip the optimization.
  81690. */
  81691. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  81692. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  81693. pToplevel->mayAbort = 1;
  81694. }
  81695. /*
  81696. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  81697. ** error. The onError parameter determines which (if any) of the statement
  81698. ** and/or current transaction is rolled back.
  81699. */
  81700. SQLITE_PRIVATE void sqlite3HaltConstraint(
  81701. Parse *pParse, /* Parsing context */
  81702. int errCode, /* extended error code */
  81703. int onError, /* Constraint type */
  81704. char *p4, /* Error message */
  81705. int p4type /* P4_STATIC or P4_TRANSIENT */
  81706. ){
  81707. Vdbe *v = sqlite3GetVdbe(pParse);
  81708. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  81709. if( onError==OE_Abort ){
  81710. sqlite3MayAbort(pParse);
  81711. }
  81712. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  81713. }
  81714. /*
  81715. ** Check to see if pIndex uses the collating sequence pColl. Return
  81716. ** true if it does and false if it does not.
  81717. */
  81718. #ifndef SQLITE_OMIT_REINDEX
  81719. static int collationMatch(const char *zColl, Index *pIndex){
  81720. int i;
  81721. assert( zColl!=0 );
  81722. for(i=0; i<pIndex->nColumn; i++){
  81723. const char *z = pIndex->azColl[i];
  81724. assert( z!=0 );
  81725. if( 0==sqlite3StrICmp(z, zColl) ){
  81726. return 1;
  81727. }
  81728. }
  81729. return 0;
  81730. }
  81731. #endif
  81732. /*
  81733. ** Recompute all indices of pTab that use the collating sequence pColl.
  81734. ** If pColl==0 then recompute all indices of pTab.
  81735. */
  81736. #ifndef SQLITE_OMIT_REINDEX
  81737. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  81738. Index *pIndex; /* An index associated with pTab */
  81739. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  81740. if( zColl==0 || collationMatch(zColl, pIndex) ){
  81741. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  81742. sqlite3BeginWriteOperation(pParse, 0, iDb);
  81743. sqlite3RefillIndex(pParse, pIndex, -1);
  81744. }
  81745. }
  81746. }
  81747. #endif
  81748. /*
  81749. ** Recompute all indices of all tables in all databases where the
  81750. ** indices use the collating sequence pColl. If pColl==0 then recompute
  81751. ** all indices everywhere.
  81752. */
  81753. #ifndef SQLITE_OMIT_REINDEX
  81754. static void reindexDatabases(Parse *pParse, char const *zColl){
  81755. Db *pDb; /* A single database */
  81756. int iDb; /* The database index number */
  81757. sqlite3 *db = pParse->db; /* The database connection */
  81758. HashElem *k; /* For looping over tables in pDb */
  81759. Table *pTab; /* A table in the database */
  81760. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  81761. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  81762. assert( pDb!=0 );
  81763. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  81764. pTab = (Table*)sqliteHashData(k);
  81765. reindexTable(pParse, pTab, zColl);
  81766. }
  81767. }
  81768. }
  81769. #endif
  81770. /*
  81771. ** Generate code for the REINDEX command.
  81772. **
  81773. ** REINDEX -- 1
  81774. ** REINDEX <collation> -- 2
  81775. ** REINDEX ?<database>.?<tablename> -- 3
  81776. ** REINDEX ?<database>.?<indexname> -- 4
  81777. **
  81778. ** Form 1 causes all indices in all attached databases to be rebuilt.
  81779. ** Form 2 rebuilds all indices in all databases that use the named
  81780. ** collating function. Forms 3 and 4 rebuild the named index or all
  81781. ** indices associated with the named table.
  81782. */
  81783. #ifndef SQLITE_OMIT_REINDEX
  81784. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  81785. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  81786. char *z; /* Name of a table or index */
  81787. const char *zDb; /* Name of the database */
  81788. Table *pTab; /* A table in the database */
  81789. Index *pIndex; /* An index associated with pTab */
  81790. int iDb; /* The database index number */
  81791. sqlite3 *db = pParse->db; /* The database connection */
  81792. Token *pObjName; /* Name of the table or index to be reindexed */
  81793. /* Read the database schema. If an error occurs, leave an error message
  81794. ** and code in pParse and return NULL. */
  81795. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  81796. return;
  81797. }
  81798. if( pName1==0 ){
  81799. reindexDatabases(pParse, 0);
  81800. return;
  81801. }else if( NEVER(pName2==0) || pName2->z==0 ){
  81802. char *zColl;
  81803. assert( pName1->z );
  81804. zColl = sqlite3NameFromToken(pParse->db, pName1);
  81805. if( !zColl ) return;
  81806. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  81807. if( pColl ){
  81808. reindexDatabases(pParse, zColl);
  81809. sqlite3DbFree(db, zColl);
  81810. return;
  81811. }
  81812. sqlite3DbFree(db, zColl);
  81813. }
  81814. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  81815. if( iDb<0 ) return;
  81816. z = sqlite3NameFromToken(db, pObjName);
  81817. if( z==0 ) return;
  81818. zDb = db->aDb[iDb].zName;
  81819. pTab = sqlite3FindTable(db, z, zDb);
  81820. if( pTab ){
  81821. reindexTable(pParse, pTab, 0);
  81822. sqlite3DbFree(db, z);
  81823. return;
  81824. }
  81825. pIndex = sqlite3FindIndex(db, z, zDb);
  81826. sqlite3DbFree(db, z);
  81827. if( pIndex ){
  81828. sqlite3BeginWriteOperation(pParse, 0, iDb);
  81829. sqlite3RefillIndex(pParse, pIndex, -1);
  81830. return;
  81831. }
  81832. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  81833. }
  81834. #endif
  81835. /*
  81836. ** Return a dynamicly allocated KeyInfo structure that can be used
  81837. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  81838. **
  81839. ** If successful, a pointer to the new structure is returned. In this case
  81840. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  81841. ** pointer. If an error occurs (out of memory or missing collation
  81842. ** sequence), NULL is returned and the state of pParse updated to reflect
  81843. ** the error.
  81844. */
  81845. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  81846. int i;
  81847. int nCol = pIdx->nColumn;
  81848. KeyInfo *pKey;
  81849. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol);
  81850. if( pKey ){
  81851. for(i=0; i<nCol; i++){
  81852. char *zColl = pIdx->azColl[i];
  81853. assert( zColl );
  81854. pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
  81855. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  81856. }
  81857. }
  81858. if( pParse->nErr ){
  81859. sqlite3DbFree(pParse->db, pKey);
  81860. pKey = 0;
  81861. }
  81862. return pKey;
  81863. }
  81864. /************** End of build.c ***********************************************/
  81865. /************** Begin file callback.c ****************************************/
  81866. /*
  81867. ** 2005 May 23
  81868. **
  81869. ** The author disclaims copyright to this source code. In place of
  81870. ** a legal notice, here is a blessing:
  81871. **
  81872. ** May you do good and not evil.
  81873. ** May you find forgiveness for yourself and forgive others.
  81874. ** May you share freely, never taking more than you give.
  81875. **
  81876. *************************************************************************
  81877. **
  81878. ** This file contains functions used to access the internal hash tables
  81879. ** of user defined functions and collation sequences.
  81880. */
  81881. /*
  81882. ** Invoke the 'collation needed' callback to request a collation sequence
  81883. ** in the encoding enc of name zName, length nName.
  81884. */
  81885. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  81886. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  81887. if( db->xCollNeeded ){
  81888. char *zExternal = sqlite3DbStrDup(db, zName);
  81889. if( !zExternal ) return;
  81890. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  81891. sqlite3DbFree(db, zExternal);
  81892. }
  81893. #ifndef SQLITE_OMIT_UTF16
  81894. if( db->xCollNeeded16 ){
  81895. char const *zExternal;
  81896. sqlite3_value *pTmp = sqlite3ValueNew(db);
  81897. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  81898. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  81899. if( zExternal ){
  81900. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  81901. }
  81902. sqlite3ValueFree(pTmp);
  81903. }
  81904. #endif
  81905. }
  81906. /*
  81907. ** This routine is called if the collation factory fails to deliver a
  81908. ** collation function in the best encoding but there may be other versions
  81909. ** of this collation function (for other text encodings) available. Use one
  81910. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  81911. ** possible.
  81912. */
  81913. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  81914. CollSeq *pColl2;
  81915. char *z = pColl->zName;
  81916. int i;
  81917. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  81918. for(i=0; i<3; i++){
  81919. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  81920. if( pColl2->xCmp!=0 ){
  81921. memcpy(pColl, pColl2, sizeof(CollSeq));
  81922. pColl->xDel = 0; /* Do not copy the destructor */
  81923. return SQLITE_OK;
  81924. }
  81925. }
  81926. return SQLITE_ERROR;
  81927. }
  81928. /*
  81929. ** This function is responsible for invoking the collation factory callback
  81930. ** or substituting a collation sequence of a different encoding when the
  81931. ** requested collation sequence is not available in the desired encoding.
  81932. **
  81933. ** If it is not NULL, then pColl must point to the database native encoding
  81934. ** collation sequence with name zName, length nName.
  81935. **
  81936. ** The return value is either the collation sequence to be used in database
  81937. ** db for collation type name zName, length nName, or NULL, if no collation
  81938. ** sequence can be found. If no collation is found, leave an error message.
  81939. **
  81940. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  81941. */
  81942. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  81943. Parse *pParse, /* Parsing context */
  81944. u8 enc, /* The desired encoding for the collating sequence */
  81945. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  81946. const char *zName /* Collating sequence name */
  81947. ){
  81948. CollSeq *p;
  81949. sqlite3 *db = pParse->db;
  81950. p = pColl;
  81951. if( !p ){
  81952. p = sqlite3FindCollSeq(db, enc, zName, 0);
  81953. }
  81954. if( !p || !p->xCmp ){
  81955. /* No collation sequence of this type for this encoding is registered.
  81956. ** Call the collation factory to see if it can supply us with one.
  81957. */
  81958. callCollNeeded(db, enc, zName);
  81959. p = sqlite3FindCollSeq(db, enc, zName, 0);
  81960. }
  81961. if( p && !p->xCmp && synthCollSeq(db, p) ){
  81962. p = 0;
  81963. }
  81964. assert( !p || p->xCmp );
  81965. if( p==0 ){
  81966. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  81967. }
  81968. return p;
  81969. }
  81970. /*
  81971. ** This routine is called on a collation sequence before it is used to
  81972. ** check that it is defined. An undefined collation sequence exists when
  81973. ** a database is loaded that contains references to collation sequences
  81974. ** that have not been defined by sqlite3_create_collation() etc.
  81975. **
  81976. ** If required, this routine calls the 'collation needed' callback to
  81977. ** request a definition of the collating sequence. If this doesn't work,
  81978. ** an equivalent collating sequence that uses a text encoding different
  81979. ** from the main database is substituted, if one is available.
  81980. */
  81981. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  81982. if( pColl ){
  81983. const char *zName = pColl->zName;
  81984. sqlite3 *db = pParse->db;
  81985. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  81986. if( !p ){
  81987. return SQLITE_ERROR;
  81988. }
  81989. assert( p==pColl );
  81990. }
  81991. return SQLITE_OK;
  81992. }
  81993. /*
  81994. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  81995. ** specified by zName and nName is not found and parameter 'create' is
  81996. ** true, then create a new entry. Otherwise return NULL.
  81997. **
  81998. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  81999. ** array of three CollSeq structures. The first is the collation sequence
  82000. ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  82001. **
  82002. ** Stored immediately after the three collation sequences is a copy of
  82003. ** the collation sequence name. A pointer to this string is stored in
  82004. ** each collation sequence structure.
  82005. */
  82006. static CollSeq *findCollSeqEntry(
  82007. sqlite3 *db, /* Database connection */
  82008. const char *zName, /* Name of the collating sequence */
  82009. int create /* Create a new entry if true */
  82010. ){
  82011. CollSeq *pColl;
  82012. int nName = sqlite3Strlen30(zName);
  82013. pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  82014. if( 0==pColl && create ){
  82015. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
  82016. if( pColl ){
  82017. CollSeq *pDel = 0;
  82018. pColl[0].zName = (char*)&pColl[3];
  82019. pColl[0].enc = SQLITE_UTF8;
  82020. pColl[1].zName = (char*)&pColl[3];
  82021. pColl[1].enc = SQLITE_UTF16LE;
  82022. pColl[2].zName = (char*)&pColl[3];
  82023. pColl[2].enc = SQLITE_UTF16BE;
  82024. memcpy(pColl[0].zName, zName, nName);
  82025. pColl[0].zName[nName] = 0;
  82026. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
  82027. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  82028. ** return the pColl pointer to be deleted (because it wasn't added
  82029. ** to the hash table).
  82030. */
  82031. assert( pDel==0 || pDel==pColl );
  82032. if( pDel!=0 ){
  82033. db->mallocFailed = 1;
  82034. sqlite3DbFree(db, pDel);
  82035. pColl = 0;
  82036. }
  82037. }
  82038. }
  82039. return pColl;
  82040. }
  82041. /*
  82042. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  82043. ** Return the CollSeq* pointer for the collation sequence named zName
  82044. ** for the encoding 'enc' from the database 'db'.
  82045. **
  82046. ** If the entry specified is not found and 'create' is true, then create a
  82047. ** new entry. Otherwise return NULL.
  82048. **
  82049. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  82050. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  82051. ** if necessary and generates an error message if the collating sequence
  82052. ** cannot be found.
  82053. **
  82054. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  82055. */
  82056. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  82057. sqlite3 *db,
  82058. u8 enc,
  82059. const char *zName,
  82060. int create
  82061. ){
  82062. CollSeq *pColl;
  82063. if( zName ){
  82064. pColl = findCollSeqEntry(db, zName, create);
  82065. }else{
  82066. pColl = db->pDfltColl;
  82067. }
  82068. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  82069. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  82070. if( pColl ) pColl += enc-1;
  82071. return pColl;
  82072. }
  82073. /* During the search for the best function definition, this procedure
  82074. ** is called to test how well the function passed as the first argument
  82075. ** matches the request for a function with nArg arguments in a system
  82076. ** that uses encoding enc. The value returned indicates how well the
  82077. ** request is matched. A higher value indicates a better match.
  82078. **
  82079. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  82080. ** is also -1. In other words, we are searching for a function that
  82081. ** takes a variable number of arguments.
  82082. **
  82083. ** If nArg is -2 that means that we are searching for any function
  82084. ** regardless of the number of arguments it uses, so return a positive
  82085. ** match score for any
  82086. **
  82087. ** The returned value is always between 0 and 6, as follows:
  82088. **
  82089. ** 0: Not a match.
  82090. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  82091. ** 2: UTF16 byte order change required and function takes any number of args.
  82092. ** 3: encoding matches and function takes any number of arguments
  82093. ** 4: UTF8/16 conversion required - argument count matches exactly
  82094. ** 5: UTF16 byte order conversion required - argument count matches exactly
  82095. ** 6: Perfect match: encoding and argument count match exactly.
  82096. **
  82097. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  82098. ** a perfect match and any function with both xStep and xFunc NULL is
  82099. ** a non-match.
  82100. */
  82101. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  82102. static int matchQuality(
  82103. FuncDef *p, /* The function we are evaluating for match quality */
  82104. int nArg, /* Desired number of arguments. (-1)==any */
  82105. u8 enc /* Desired text encoding */
  82106. ){
  82107. int match;
  82108. /* nArg of -2 is a special case */
  82109. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  82110. /* Wrong number of arguments means "no match" */
  82111. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  82112. /* Give a better score to a function with a specific number of arguments
  82113. ** than to function that accepts any number of arguments. */
  82114. if( p->nArg==nArg ){
  82115. match = 4;
  82116. }else{
  82117. match = 1;
  82118. }
  82119. /* Bonus points if the text encoding matches */
  82120. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  82121. match += 2; /* Exact encoding match */
  82122. }else if( (enc & p->funcFlags & 2)!=0 ){
  82123. match += 1; /* Both are UTF16, but with different byte orders */
  82124. }
  82125. return match;
  82126. }
  82127. /*
  82128. ** Search a FuncDefHash for a function with the given name. Return
  82129. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  82130. */
  82131. static FuncDef *functionSearch(
  82132. FuncDefHash *pHash, /* Hash table to search */
  82133. int h, /* Hash of the name */
  82134. const char *zFunc, /* Name of function */
  82135. int nFunc /* Number of bytes in zFunc */
  82136. ){
  82137. FuncDef *p;
  82138. for(p=pHash->a[h]; p; p=p->pHash){
  82139. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  82140. return p;
  82141. }
  82142. }
  82143. return 0;
  82144. }
  82145. /*
  82146. ** Insert a new FuncDef into a FuncDefHash hash table.
  82147. */
  82148. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  82149. FuncDefHash *pHash, /* The hash table into which to insert */
  82150. FuncDef *pDef /* The function definition to insert */
  82151. ){
  82152. FuncDef *pOther;
  82153. int nName = sqlite3Strlen30(pDef->zName);
  82154. u8 c1 = (u8)pDef->zName[0];
  82155. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  82156. pOther = functionSearch(pHash, h, pDef->zName, nName);
  82157. if( pOther ){
  82158. assert( pOther!=pDef && pOther->pNext!=pDef );
  82159. pDef->pNext = pOther->pNext;
  82160. pOther->pNext = pDef;
  82161. }else{
  82162. pDef->pNext = 0;
  82163. pDef->pHash = pHash->a[h];
  82164. pHash->a[h] = pDef;
  82165. }
  82166. }
  82167. /*
  82168. ** Locate a user function given a name, a number of arguments and a flag
  82169. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  82170. ** pointer to the FuncDef structure that defines that function, or return
  82171. ** NULL if the function does not exist.
  82172. **
  82173. ** If the createFlag argument is true, then a new (blank) FuncDef
  82174. ** structure is created and liked into the "db" structure if a
  82175. ** no matching function previously existed.
  82176. **
  82177. ** If nArg is -2, then the first valid function found is returned. A
  82178. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  82179. ** case is used to see if zName is a valid function name for some number
  82180. ** of arguments. If nArg is -2, then createFlag must be 0.
  82181. **
  82182. ** If createFlag is false, then a function with the required name and
  82183. ** number of arguments may be returned even if the eTextRep flag does not
  82184. ** match that requested.
  82185. */
  82186. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  82187. sqlite3 *db, /* An open database */
  82188. const char *zName, /* Name of the function. Not null-terminated */
  82189. int nName, /* Number of characters in the name */
  82190. int nArg, /* Number of arguments. -1 means any number */
  82191. u8 enc, /* Preferred text encoding */
  82192. u8 createFlag /* Create new entry if true and does not otherwise exist */
  82193. ){
  82194. FuncDef *p; /* Iterator variable */
  82195. FuncDef *pBest = 0; /* Best match found so far */
  82196. int bestScore = 0; /* Score of best match */
  82197. int h; /* Hash value */
  82198. assert( nArg>=(-2) );
  82199. assert( nArg>=(-1) || createFlag==0 );
  82200. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  82201. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  82202. /* First search for a match amongst the application-defined functions.
  82203. */
  82204. p = functionSearch(&db->aFunc, h, zName, nName);
  82205. while( p ){
  82206. int score = matchQuality(p, nArg, enc);
  82207. if( score>bestScore ){
  82208. pBest = p;
  82209. bestScore = score;
  82210. }
  82211. p = p->pNext;
  82212. }
  82213. /* If no match is found, search the built-in functions.
  82214. **
  82215. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  82216. ** functions even if a prior app-defined function was found. And give
  82217. ** priority to built-in functions.
  82218. **
  82219. ** Except, if createFlag is true, that means that we are trying to
  82220. ** install a new function. Whatever FuncDef structure is returned it will
  82221. ** have fields overwritten with new information appropriate for the
  82222. ** new function. But the FuncDefs for built-in functions are read-only.
  82223. ** So we must not search for built-ins when creating a new function.
  82224. */
  82225. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  82226. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  82227. bestScore = 0;
  82228. p = functionSearch(pHash, h, zName, nName);
  82229. while( p ){
  82230. int score = matchQuality(p, nArg, enc);
  82231. if( score>bestScore ){
  82232. pBest = p;
  82233. bestScore = score;
  82234. }
  82235. p = p->pNext;
  82236. }
  82237. }
  82238. /* If the createFlag parameter is true and the search did not reveal an
  82239. ** exact match for the name, number of arguments and encoding, then add a
  82240. ** new entry to the hash table and return it.
  82241. */
  82242. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  82243. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  82244. pBest->zName = (char *)&pBest[1];
  82245. pBest->nArg = (u16)nArg;
  82246. pBest->funcFlags = enc;
  82247. memcpy(pBest->zName, zName, nName);
  82248. pBest->zName[nName] = 0;
  82249. sqlite3FuncDefInsert(&db->aFunc, pBest);
  82250. }
  82251. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  82252. return pBest;
  82253. }
  82254. return 0;
  82255. }
  82256. /*
  82257. ** Free all resources held by the schema structure. The void* argument points
  82258. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  82259. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  82260. ** of the schema hash tables).
  82261. **
  82262. ** The Schema.cache_size variable is not cleared.
  82263. */
  82264. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  82265. Hash temp1;
  82266. Hash temp2;
  82267. HashElem *pElem;
  82268. Schema *pSchema = (Schema *)p;
  82269. temp1 = pSchema->tblHash;
  82270. temp2 = pSchema->trigHash;
  82271. sqlite3HashInit(&pSchema->trigHash);
  82272. sqlite3HashClear(&pSchema->idxHash);
  82273. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  82274. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  82275. }
  82276. sqlite3HashClear(&temp2);
  82277. sqlite3HashInit(&pSchema->tblHash);
  82278. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  82279. Table *pTab = sqliteHashData(pElem);
  82280. sqlite3DeleteTable(0, pTab);
  82281. }
  82282. sqlite3HashClear(&temp1);
  82283. sqlite3HashClear(&pSchema->fkeyHash);
  82284. pSchema->pSeqTab = 0;
  82285. if( pSchema->flags & DB_SchemaLoaded ){
  82286. pSchema->iGeneration++;
  82287. pSchema->flags &= ~DB_SchemaLoaded;
  82288. }
  82289. }
  82290. /*
  82291. ** Find and return the schema associated with a BTree. Create
  82292. ** a new one if necessary.
  82293. */
  82294. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  82295. Schema * p;
  82296. if( pBt ){
  82297. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  82298. }else{
  82299. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  82300. }
  82301. if( !p ){
  82302. db->mallocFailed = 1;
  82303. }else if ( 0==p->file_format ){
  82304. sqlite3HashInit(&p->tblHash);
  82305. sqlite3HashInit(&p->idxHash);
  82306. sqlite3HashInit(&p->trigHash);
  82307. sqlite3HashInit(&p->fkeyHash);
  82308. p->enc = SQLITE_UTF8;
  82309. }
  82310. return p;
  82311. }
  82312. /************** End of callback.c ********************************************/
  82313. /************** Begin file delete.c ******************************************/
  82314. /*
  82315. ** 2001 September 15
  82316. **
  82317. ** The author disclaims copyright to this source code. In place of
  82318. ** a legal notice, here is a blessing:
  82319. **
  82320. ** May you do good and not evil.
  82321. ** May you find forgiveness for yourself and forgive others.
  82322. ** May you share freely, never taking more than you give.
  82323. **
  82324. *************************************************************************
  82325. ** This file contains C code routines that are called by the parser
  82326. ** in order to generate code for DELETE FROM statements.
  82327. */
  82328. /*
  82329. ** While a SrcList can in general represent multiple tables and subqueries
  82330. ** (as in the FROM clause of a SELECT statement) in this case it contains
  82331. ** the name of a single table, as one might find in an INSERT, DELETE,
  82332. ** or UPDATE statement. Look up that table in the symbol table and
  82333. ** return a pointer. Set an error message and return NULL if the table
  82334. ** name is not found or if any other error occurs.
  82335. **
  82336. ** The following fields are initialized appropriate in pSrc:
  82337. **
  82338. ** pSrc->a[0].pTab Pointer to the Table object
  82339. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  82340. **
  82341. */
  82342. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  82343. struct SrcList_item *pItem = pSrc->a;
  82344. Table *pTab;
  82345. assert( pItem && pSrc->nSrc==1 );
  82346. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  82347. sqlite3DeleteTable(pParse->db, pItem->pTab);
  82348. pItem->pTab = pTab;
  82349. if( pTab ){
  82350. pTab->nRef++;
  82351. }
  82352. if( sqlite3IndexedByLookup(pParse, pItem) ){
  82353. pTab = 0;
  82354. }
  82355. return pTab;
  82356. }
  82357. /*
  82358. ** Check to make sure the given table is writable. If it is not
  82359. ** writable, generate an error message and return 1. If it is
  82360. ** writable return 0;
  82361. */
  82362. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  82363. /* A table is not writable under the following circumstances:
  82364. **
  82365. ** 1) It is a virtual table and no implementation of the xUpdate method
  82366. ** has been provided, or
  82367. ** 2) It is a system table (i.e. sqlite_master), this call is not
  82368. ** part of a nested parse and writable_schema pragma has not
  82369. ** been specified.
  82370. **
  82371. ** In either case leave an error message in pParse and return non-zero.
  82372. */
  82373. if( ( IsVirtual(pTab)
  82374. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  82375. || ( (pTab->tabFlags & TF_Readonly)!=0
  82376. && (pParse->db->flags & SQLITE_WriteSchema)==0
  82377. && pParse->nested==0 )
  82378. ){
  82379. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  82380. return 1;
  82381. }
  82382. #ifndef SQLITE_OMIT_VIEW
  82383. if( !viewOk && pTab->pSelect ){
  82384. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  82385. return 1;
  82386. }
  82387. #endif
  82388. return 0;
  82389. }
  82390. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  82391. /*
  82392. ** Evaluate a view and store its result in an ephemeral table. The
  82393. ** pWhere argument is an optional WHERE clause that restricts the
  82394. ** set of rows in the view that are to be added to the ephemeral table.
  82395. */
  82396. SQLITE_PRIVATE void sqlite3MaterializeView(
  82397. Parse *pParse, /* Parsing context */
  82398. Table *pView, /* View definition */
  82399. Expr *pWhere, /* Optional WHERE clause to be added */
  82400. int iCur /* Cursor number for ephemerial table */
  82401. ){
  82402. SelectDest dest;
  82403. Select *pSel;
  82404. SrcList *pFrom;
  82405. sqlite3 *db = pParse->db;
  82406. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  82407. pWhere = sqlite3ExprDup(db, pWhere, 0);
  82408. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  82409. if( pFrom ){
  82410. assert( pFrom->nSrc==1 );
  82411. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  82412. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  82413. assert( pFrom->a[0].pOn==0 );
  82414. assert( pFrom->a[0].pUsing==0 );
  82415. }
  82416. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  82417. if( pSel ) pSel->selFlags |= SF_Materialize;
  82418. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  82419. sqlite3Select(pParse, pSel, &dest);
  82420. sqlite3SelectDelete(db, pSel);
  82421. }
  82422. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  82423. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  82424. /*
  82425. ** Generate an expression tree to implement the WHERE, ORDER BY,
  82426. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  82427. **
  82428. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  82429. ** \__________________________/
  82430. ** pLimitWhere (pInClause)
  82431. */
  82432. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  82433. Parse *pParse, /* The parser context */
  82434. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  82435. Expr *pWhere, /* The WHERE clause. May be null */
  82436. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  82437. Expr *pLimit, /* The LIMIT clause. May be null */
  82438. Expr *pOffset, /* The OFFSET clause. May be null */
  82439. char *zStmtType /* Either DELETE or UPDATE. For error messages. */
  82440. ){
  82441. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  82442. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  82443. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  82444. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  82445. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  82446. Select *pSelect = NULL; /* Complete SELECT tree */
  82447. /* Check that there isn't an ORDER BY without a LIMIT clause.
  82448. */
  82449. if( pOrderBy && (pLimit == 0) ) {
  82450. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  82451. goto limit_where_cleanup_2;
  82452. }
  82453. /* We only need to generate a select expression if there
  82454. ** is a limit/offset term to enforce.
  82455. */
  82456. if( pLimit == 0 ) {
  82457. /* if pLimit is null, pOffset will always be null as well. */
  82458. assert( pOffset == 0 );
  82459. return pWhere;
  82460. }
  82461. /* Generate a select expression tree to enforce the limit/offset
  82462. ** term for the DELETE or UPDATE statement. For example:
  82463. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  82464. ** becomes:
  82465. ** DELETE FROM table_a WHERE rowid IN (
  82466. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  82467. ** );
  82468. */
  82469. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  82470. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  82471. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  82472. if( pEList == 0 ) goto limit_where_cleanup_2;
  82473. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  82474. ** and the SELECT subtree. */
  82475. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  82476. if( pSelectSrc == 0 ) {
  82477. sqlite3ExprListDelete(pParse->db, pEList);
  82478. goto limit_where_cleanup_2;
  82479. }
  82480. /* generate the SELECT expression tree. */
  82481. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  82482. pOrderBy,0,pLimit,pOffset);
  82483. if( pSelect == 0 ) return 0;
  82484. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  82485. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  82486. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  82487. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  82488. if( pInClause == 0 ) goto limit_where_cleanup_1;
  82489. pInClause->x.pSelect = pSelect;
  82490. pInClause->flags |= EP_xIsSelect;
  82491. sqlite3ExprSetHeight(pParse, pInClause);
  82492. return pInClause;
  82493. /* something went wrong. clean up anything allocated. */
  82494. limit_where_cleanup_1:
  82495. sqlite3SelectDelete(pParse->db, pSelect);
  82496. return 0;
  82497. limit_where_cleanup_2:
  82498. sqlite3ExprDelete(pParse->db, pWhere);
  82499. sqlite3ExprListDelete(pParse->db, pOrderBy);
  82500. sqlite3ExprDelete(pParse->db, pLimit);
  82501. sqlite3ExprDelete(pParse->db, pOffset);
  82502. return 0;
  82503. }
  82504. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  82505. /*
  82506. ** Generate code for a DELETE FROM statement.
  82507. **
  82508. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  82509. ** \________/ \________________/
  82510. ** pTabList pWhere
  82511. */
  82512. SQLITE_PRIVATE void sqlite3DeleteFrom(
  82513. Parse *pParse, /* The parser context */
  82514. SrcList *pTabList, /* The table from which we should delete things */
  82515. Expr *pWhere /* The WHERE clause. May be null */
  82516. ){
  82517. Vdbe *v; /* The virtual database engine */
  82518. Table *pTab; /* The table from which records will be deleted */
  82519. const char *zDb; /* Name of database holding pTab */
  82520. int end, addr = 0; /* A couple addresses of generated code */
  82521. int i; /* Loop counter */
  82522. WhereInfo *pWInfo; /* Information about the WHERE clause */
  82523. Index *pIdx; /* For looping over indices of the table */
  82524. int iCur; /* VDBE Cursor number for pTab */
  82525. sqlite3 *db; /* Main database structure */
  82526. AuthContext sContext; /* Authorization context */
  82527. NameContext sNC; /* Name context to resolve expressions in */
  82528. int iDb; /* Database number */
  82529. int memCnt = -1; /* Memory cell used for change counting */
  82530. int rcauth; /* Value returned by authorization callback */
  82531. #ifndef SQLITE_OMIT_TRIGGER
  82532. int isView; /* True if attempting to delete from a view */
  82533. Trigger *pTrigger; /* List of table triggers, if required */
  82534. #endif
  82535. memset(&sContext, 0, sizeof(sContext));
  82536. db = pParse->db;
  82537. if( pParse->nErr || db->mallocFailed ){
  82538. goto delete_from_cleanup;
  82539. }
  82540. assert( pTabList->nSrc==1 );
  82541. /* Locate the table which we want to delete. This table has to be
  82542. ** put in an SrcList structure because some of the subroutines we
  82543. ** will be calling are designed to work with multiple tables and expect
  82544. ** an SrcList* parameter instead of just a Table* parameter.
  82545. */
  82546. pTab = sqlite3SrcListLookup(pParse, pTabList);
  82547. if( pTab==0 ) goto delete_from_cleanup;
  82548. /* Figure out if we have any triggers and if the table being
  82549. ** deleted from is a view
  82550. */
  82551. #ifndef SQLITE_OMIT_TRIGGER
  82552. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  82553. isView = pTab->pSelect!=0;
  82554. #else
  82555. # define pTrigger 0
  82556. # define isView 0
  82557. #endif
  82558. #ifdef SQLITE_OMIT_VIEW
  82559. # undef isView
  82560. # define isView 0
  82561. #endif
  82562. /* If pTab is really a view, make sure it has been initialized.
  82563. */
  82564. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  82565. goto delete_from_cleanup;
  82566. }
  82567. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  82568. goto delete_from_cleanup;
  82569. }
  82570. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  82571. assert( iDb<db->nDb );
  82572. zDb = db->aDb[iDb].zName;
  82573. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  82574. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  82575. if( rcauth==SQLITE_DENY ){
  82576. goto delete_from_cleanup;
  82577. }
  82578. assert(!isView || pTrigger);
  82579. /* Assign cursor number to the table and all its indices.
  82580. */
  82581. assert( pTabList->nSrc==1 );
  82582. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  82583. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  82584. pParse->nTab++;
  82585. }
  82586. /* Start the view context
  82587. */
  82588. if( isView ){
  82589. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  82590. }
  82591. /* Begin generating code.
  82592. */
  82593. v = sqlite3GetVdbe(pParse);
  82594. if( v==0 ){
  82595. goto delete_from_cleanup;
  82596. }
  82597. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  82598. sqlite3BeginWriteOperation(pParse, 1, iDb);
  82599. /* If we are trying to delete from a view, realize that view into
  82600. ** a ephemeral table.
  82601. */
  82602. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  82603. if( isView ){
  82604. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  82605. }
  82606. #endif
  82607. /* Resolve the column names in the WHERE clause.
  82608. */
  82609. memset(&sNC, 0, sizeof(sNC));
  82610. sNC.pParse = pParse;
  82611. sNC.pSrcList = pTabList;
  82612. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  82613. goto delete_from_cleanup;
  82614. }
  82615. /* Initialize the counter of the number of rows deleted, if
  82616. ** we are counting rows.
  82617. */
  82618. if( db->flags & SQLITE_CountRows ){
  82619. memCnt = ++pParse->nMem;
  82620. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  82621. }
  82622. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  82623. /* Special case: A DELETE without a WHERE clause deletes everything.
  82624. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  82625. ** this optimization caused the row change count (the value returned by
  82626. ** API function sqlite3_count_changes) to be set incorrectly. */
  82627. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  82628. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  82629. ){
  82630. assert( !isView );
  82631. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  82632. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  82633. pTab->zName, P4_STATIC);
  82634. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  82635. assert( pIdx->pSchema==pTab->pSchema );
  82636. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  82637. }
  82638. }else
  82639. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  82640. /* The usual case: There is a WHERE clause so we have to scan through
  82641. ** the table and pick which records to delete.
  82642. */
  82643. {
  82644. int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
  82645. int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
  82646. int regRowid; /* Actual register containing rowids */
  82647. /* Collect rowids of every row to be deleted.
  82648. */
  82649. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  82650. pWInfo = sqlite3WhereBegin(
  82651. pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
  82652. );
  82653. if( pWInfo==0 ) goto delete_from_cleanup;
  82654. regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
  82655. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
  82656. if( db->flags & SQLITE_CountRows ){
  82657. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  82658. }
  82659. sqlite3WhereEnd(pWInfo);
  82660. /* Delete every item whose key was written to the list during the
  82661. ** database scan. We have to delete items after the scan is complete
  82662. ** because deleting an item can change the scan order. */
  82663. end = sqlite3VdbeMakeLabel(v);
  82664. /* Unless this is a view, open cursors for the table we are
  82665. ** deleting from and all its indices. If this is a view, then the
  82666. ** only effect this statement has is to fire the INSTEAD OF
  82667. ** triggers. */
  82668. if( !isView ){
  82669. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  82670. }
  82671. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
  82672. /* Delete the row */
  82673. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82674. if( IsVirtual(pTab) ){
  82675. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  82676. sqlite3VtabMakeWritable(pParse, pTab);
  82677. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
  82678. sqlite3VdbeChangeP5(v, OE_Abort);
  82679. sqlite3MayAbort(pParse);
  82680. }else
  82681. #endif
  82682. {
  82683. int count = (pParse->nested==0); /* True to count changes */
  82684. sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
  82685. }
  82686. /* End of the delete loop */
  82687. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  82688. sqlite3VdbeResolveLabel(v, end);
  82689. /* Close the cursors open on the table and its indexes. */
  82690. if( !isView && !IsVirtual(pTab) ){
  82691. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  82692. sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
  82693. }
  82694. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  82695. }
  82696. }
  82697. /* Update the sqlite_sequence table by storing the content of the
  82698. ** maximum rowid counter values recorded while inserting into
  82699. ** autoincrement tables.
  82700. */
  82701. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  82702. sqlite3AutoincrementEnd(pParse);
  82703. }
  82704. /* Return the number of rows that were deleted. If this routine is
  82705. ** generating code because of a call to sqlite3NestedParse(), do not
  82706. ** invoke the callback function.
  82707. */
  82708. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  82709. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  82710. sqlite3VdbeSetNumCols(v, 1);
  82711. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  82712. }
  82713. delete_from_cleanup:
  82714. sqlite3AuthContextPop(&sContext);
  82715. sqlite3SrcListDelete(db, pTabList);
  82716. sqlite3ExprDelete(db, pWhere);
  82717. return;
  82718. }
  82719. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  82720. ** thely may interfere with compilation of other functions in this file
  82721. ** (or in another file, if this file becomes part of the amalgamation). */
  82722. #ifdef isView
  82723. #undef isView
  82724. #endif
  82725. #ifdef pTrigger
  82726. #undef pTrigger
  82727. #endif
  82728. /*
  82729. ** This routine generates VDBE code that causes a single row of a
  82730. ** single table to be deleted.
  82731. **
  82732. ** The VDBE must be in a particular state when this routine is called.
  82733. ** These are the requirements:
  82734. **
  82735. ** 1. A read/write cursor pointing to pTab, the table containing the row
  82736. ** to be deleted, must be opened as cursor number $iCur.
  82737. **
  82738. ** 2. Read/write cursors for all indices of pTab must be open as
  82739. ** cursor number base+i for the i-th index.
  82740. **
  82741. ** 3. The record number of the row to be deleted must be stored in
  82742. ** memory cell iRowid.
  82743. **
  82744. ** This routine generates code to remove both the table record and all
  82745. ** index entries that point to that record.
  82746. */
  82747. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  82748. Parse *pParse, /* Parsing context */
  82749. Table *pTab, /* Table containing the row to be deleted */
  82750. int iCur, /* Cursor number for the table */
  82751. int iRowid, /* Memory cell that contains the rowid to delete */
  82752. int count, /* If non-zero, increment the row change counter */
  82753. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  82754. int onconf /* Default ON CONFLICT policy for triggers */
  82755. ){
  82756. Vdbe *v = pParse->pVdbe; /* Vdbe */
  82757. int iOld = 0; /* First register in OLD.* array */
  82758. int iLabel; /* Label resolved to end of generated code */
  82759. /* Vdbe is guaranteed to have been allocated by this stage. */
  82760. assert( v );
  82761. /* Seek cursor iCur to the row to delete. If this row no longer exists
  82762. ** (this can happen if a trigger program has already deleted it), do
  82763. ** not attempt to delete it or fire any DELETE triggers. */
  82764. iLabel = sqlite3VdbeMakeLabel(v);
  82765. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  82766. /* If there are any triggers to fire, allocate a range of registers to
  82767. ** use for the old.* references in the triggers. */
  82768. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  82769. u32 mask; /* Mask of OLD.* columns in use */
  82770. int iCol; /* Iterator used while populating OLD.* */
  82771. /* TODO: Could use temporary registers here. Also could attempt to
  82772. ** avoid copying the contents of the rowid register. */
  82773. mask = sqlite3TriggerColmask(
  82774. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  82775. );
  82776. mask |= sqlite3FkOldmask(pParse, pTab);
  82777. iOld = pParse->nMem+1;
  82778. pParse->nMem += (1 + pTab->nCol);
  82779. /* Populate the OLD.* pseudo-table register array. These values will be
  82780. ** used by any BEFORE and AFTER triggers that exist. */
  82781. sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
  82782. for(iCol=0; iCol<pTab->nCol; iCol++){
  82783. if( mask==0xffffffff || mask&(1<<iCol) ){
  82784. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
  82785. }
  82786. }
  82787. /* Invoke BEFORE DELETE trigger programs. */
  82788. sqlite3CodeRowTrigger(pParse, pTrigger,
  82789. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  82790. );
  82791. /* Seek the cursor to the row to be deleted again. It may be that
  82792. ** the BEFORE triggers coded above have already removed the row
  82793. ** being deleted. Do not attempt to delete the row a second time, and
  82794. ** do not fire AFTER triggers. */
  82795. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  82796. /* Do FK processing. This call checks that any FK constraints that
  82797. ** refer to this table (i.e. constraints attached to other tables)
  82798. ** are not violated by deleting this row. */
  82799. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  82800. }
  82801. /* Delete the index and table entries. Skip this step if pTab is really
  82802. ** a view (in which case the only effect of the DELETE statement is to
  82803. ** fire the INSTEAD OF triggers). */
  82804. if( pTab->pSelect==0 ){
  82805. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
  82806. sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  82807. if( count ){
  82808. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  82809. }
  82810. }
  82811. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  82812. ** handle rows (possibly in other tables) that refer via a foreign key
  82813. ** to the row just deleted. */
  82814. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  82815. /* Invoke AFTER DELETE trigger programs. */
  82816. sqlite3CodeRowTrigger(pParse, pTrigger,
  82817. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  82818. );
  82819. /* Jump here if the row had already been deleted before any BEFORE
  82820. ** trigger programs were invoked. Or if a trigger program throws a
  82821. ** RAISE(IGNORE) exception. */
  82822. sqlite3VdbeResolveLabel(v, iLabel);
  82823. }
  82824. /*
  82825. ** This routine generates VDBE code that causes the deletion of all
  82826. ** index entries associated with a single row of a single table.
  82827. **
  82828. ** The VDBE must be in a particular state when this routine is called.
  82829. ** These are the requirements:
  82830. **
  82831. ** 1. A read/write cursor pointing to pTab, the table containing the row
  82832. ** to be deleted, must be opened as cursor number "iCur".
  82833. **
  82834. ** 2. Read/write cursors for all indices of pTab must be open as
  82835. ** cursor number iCur+i for the i-th index.
  82836. **
  82837. ** 3. The "iCur" cursor must be pointing to the row that is to be
  82838. ** deleted.
  82839. */
  82840. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  82841. Parse *pParse, /* Parsing and code generating context */
  82842. Table *pTab, /* Table containing the row to be deleted */
  82843. int iCur, /* Cursor number for the table */
  82844. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  82845. ){
  82846. int i;
  82847. Index *pIdx;
  82848. int r1;
  82849. int iPartIdxLabel;
  82850. Vdbe *v = pParse->pVdbe;
  82851. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  82852. if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
  82853. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0, &iPartIdxLabel);
  82854. sqlite3VdbeAddOp3(v, OP_IdxDelete, iCur+i, r1, pIdx->nColumn+1);
  82855. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  82856. }
  82857. }
  82858. /*
  82859. ** Generate code that will assemble an index key and put it in register
  82860. ** regOut. The key with be for index pIdx which is an index on pTab.
  82861. ** iCur is the index of a cursor open on the pTab table and pointing to
  82862. ** the entry that needs indexing.
  82863. **
  82864. ** Return a register number which is the first in a block of
  82865. ** registers that holds the elements of the index key. The
  82866. ** block of registers has already been deallocated by the time
  82867. ** this routine returns.
  82868. **
  82869. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  82870. ** to that label if pIdx is a partial index that should be skipped.
  82871. ** A partial index should be skipped if its WHERE clause evaluates
  82872. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  82873. ** will be set to zero which is an empty label that is ignored by
  82874. ** sqlite3VdbeResolveLabel().
  82875. */
  82876. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  82877. Parse *pParse, /* Parsing context */
  82878. Index *pIdx, /* The index for which to generate a key */
  82879. int iCur, /* Cursor number for the pIdx->pTable table */
  82880. int regOut, /* Write the new index key to this register */
  82881. int doMakeRec, /* Run the OP_MakeRecord instruction if true */
  82882. int *piPartIdxLabel /* OUT: Jump to this label to skip partial index */
  82883. ){
  82884. Vdbe *v = pParse->pVdbe;
  82885. int j;
  82886. Table *pTab = pIdx->pTable;
  82887. int regBase;
  82888. int nCol;
  82889. if( piPartIdxLabel ){
  82890. if( pIdx->pPartIdxWhere ){
  82891. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  82892. pParse->iPartIdxTab = iCur;
  82893. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  82894. SQLITE_JUMPIFNULL);
  82895. }else{
  82896. *piPartIdxLabel = 0;
  82897. }
  82898. }
  82899. nCol = pIdx->nColumn;
  82900. regBase = sqlite3GetTempRange(pParse, nCol+1);
  82901. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  82902. for(j=0; j<nCol; j++){
  82903. int idx = pIdx->aiColumn[j];
  82904. if( idx==pTab->iPKey ){
  82905. sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
  82906. }else{
  82907. sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
  82908. sqlite3ColumnDefault(v, pTab, idx, -1);
  82909. }
  82910. }
  82911. if( doMakeRec ){
  82912. const char *zAff;
  82913. if( pTab->pSelect
  82914. || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
  82915. ){
  82916. zAff = 0;
  82917. }else{
  82918. zAff = sqlite3IndexAffinityStr(v, pIdx);
  82919. }
  82920. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
  82921. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  82922. }
  82923. sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  82924. return regBase;
  82925. }
  82926. /************** End of delete.c **********************************************/
  82927. /************** Begin file func.c ********************************************/
  82928. /*
  82929. ** 2002 February 23
  82930. **
  82931. ** The author disclaims copyright to this source code. In place of
  82932. ** a legal notice, here is a blessing:
  82933. **
  82934. ** May you do good and not evil.
  82935. ** May you find forgiveness for yourself and forgive others.
  82936. ** May you share freely, never taking more than you give.
  82937. **
  82938. *************************************************************************
  82939. ** This file contains the C functions that implement various SQL
  82940. ** functions of SQLite.
  82941. **
  82942. ** There is only one exported symbol in this file - the function
  82943. ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
  82944. ** All other code has file scope.
  82945. */
  82946. /* #include <stdlib.h> */
  82947. /* #include <assert.h> */
  82948. /*
  82949. ** Return the collating function associated with a function.
  82950. */
  82951. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  82952. return context->pColl;
  82953. }
  82954. /*
  82955. ** Indicate that the accumulator load should be skipped on this
  82956. ** iteration of the aggregate loop.
  82957. */
  82958. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  82959. context->skipFlag = 1;
  82960. }
  82961. /*
  82962. ** Implementation of the non-aggregate min() and max() functions
  82963. */
  82964. static void minmaxFunc(
  82965. sqlite3_context *context,
  82966. int argc,
  82967. sqlite3_value **argv
  82968. ){
  82969. int i;
  82970. int mask; /* 0 for min() or 0xffffffff for max() */
  82971. int iBest;
  82972. CollSeq *pColl;
  82973. assert( argc>1 );
  82974. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  82975. pColl = sqlite3GetFuncCollSeq(context);
  82976. assert( pColl );
  82977. assert( mask==-1 || mask==0 );
  82978. iBest = 0;
  82979. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  82980. for(i=1; i<argc; i++){
  82981. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  82982. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  82983. testcase( mask==0 );
  82984. iBest = i;
  82985. }
  82986. }
  82987. sqlite3_result_value(context, argv[iBest]);
  82988. }
  82989. /*
  82990. ** Return the type of the argument.
  82991. */
  82992. static void typeofFunc(
  82993. sqlite3_context *context,
  82994. int NotUsed,
  82995. sqlite3_value **argv
  82996. ){
  82997. const char *z = 0;
  82998. UNUSED_PARAMETER(NotUsed);
  82999. switch( sqlite3_value_type(argv[0]) ){
  83000. case SQLITE_INTEGER: z = "integer"; break;
  83001. case SQLITE_TEXT: z = "text"; break;
  83002. case SQLITE_FLOAT: z = "real"; break;
  83003. case SQLITE_BLOB: z = "blob"; break;
  83004. default: z = "null"; break;
  83005. }
  83006. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  83007. }
  83008. /*
  83009. ** Implementation of the length() function
  83010. */
  83011. static void lengthFunc(
  83012. sqlite3_context *context,
  83013. int argc,
  83014. sqlite3_value **argv
  83015. ){
  83016. int len;
  83017. assert( argc==1 );
  83018. UNUSED_PARAMETER(argc);
  83019. switch( sqlite3_value_type(argv[0]) ){
  83020. case SQLITE_BLOB:
  83021. case SQLITE_INTEGER:
  83022. case SQLITE_FLOAT: {
  83023. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  83024. break;
  83025. }
  83026. case SQLITE_TEXT: {
  83027. const unsigned char *z = sqlite3_value_text(argv[0]);
  83028. if( z==0 ) return;
  83029. len = 0;
  83030. while( *z ){
  83031. len++;
  83032. SQLITE_SKIP_UTF8(z);
  83033. }
  83034. sqlite3_result_int(context, len);
  83035. break;
  83036. }
  83037. default: {
  83038. sqlite3_result_null(context);
  83039. break;
  83040. }
  83041. }
  83042. }
  83043. /*
  83044. ** Implementation of the abs() function.
  83045. **
  83046. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  83047. ** the numeric argument X.
  83048. */
  83049. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  83050. assert( argc==1 );
  83051. UNUSED_PARAMETER(argc);
  83052. switch( sqlite3_value_type(argv[0]) ){
  83053. case SQLITE_INTEGER: {
  83054. i64 iVal = sqlite3_value_int64(argv[0]);
  83055. if( iVal<0 ){
  83056. if( (iVal<<1)==0 ){
  83057. /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
  83058. ** abs(X) throws an integer overflow error since there is no
  83059. ** equivalent positive 64-bit two complement value. */
  83060. sqlite3_result_error(context, "integer overflow", -1);
  83061. return;
  83062. }
  83063. iVal = -iVal;
  83064. }
  83065. sqlite3_result_int64(context, iVal);
  83066. break;
  83067. }
  83068. case SQLITE_NULL: {
  83069. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  83070. sqlite3_result_null(context);
  83071. break;
  83072. }
  83073. default: {
  83074. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  83075. ** something that can be converted into a number, we have:
  83076. ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
  83077. ** cannot be converted to a numeric value.
  83078. */
  83079. double rVal = sqlite3_value_double(argv[0]);
  83080. if( rVal<0 ) rVal = -rVal;
  83081. sqlite3_result_double(context, rVal);
  83082. break;
  83083. }
  83084. }
  83085. }
  83086. /*
  83087. ** Implementation of the instr() function.
  83088. **
  83089. ** instr(haystack,needle) finds the first occurrence of needle
  83090. ** in haystack and returns the number of previous characters plus 1,
  83091. ** or 0 if needle does not occur within haystack.
  83092. **
  83093. ** If both haystack and needle are BLOBs, then the result is one more than
  83094. ** the number of bytes in haystack prior to the first occurrence of needle,
  83095. ** or 0 if needle never occurs in haystack.
  83096. */
  83097. static void instrFunc(
  83098. sqlite3_context *context,
  83099. int argc,
  83100. sqlite3_value **argv
  83101. ){
  83102. const unsigned char *zHaystack;
  83103. const unsigned char *zNeedle;
  83104. int nHaystack;
  83105. int nNeedle;
  83106. int typeHaystack, typeNeedle;
  83107. int N = 1;
  83108. int isText;
  83109. UNUSED_PARAMETER(argc);
  83110. typeHaystack = sqlite3_value_type(argv[0]);
  83111. typeNeedle = sqlite3_value_type(argv[1]);
  83112. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  83113. nHaystack = sqlite3_value_bytes(argv[0]);
  83114. nNeedle = sqlite3_value_bytes(argv[1]);
  83115. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  83116. zHaystack = sqlite3_value_blob(argv[0]);
  83117. zNeedle = sqlite3_value_blob(argv[1]);
  83118. isText = 0;
  83119. }else{
  83120. zHaystack = sqlite3_value_text(argv[0]);
  83121. zNeedle = sqlite3_value_text(argv[1]);
  83122. isText = 1;
  83123. }
  83124. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  83125. N++;
  83126. do{
  83127. nHaystack--;
  83128. zHaystack++;
  83129. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  83130. }
  83131. if( nNeedle>nHaystack ) N = 0;
  83132. sqlite3_result_int(context, N);
  83133. }
  83134. /*
  83135. ** Implementation of the substr() function.
  83136. **
  83137. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  83138. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  83139. ** of x. If x is text, then we actually count UTF-8 characters.
  83140. ** If x is a blob, then we count bytes.
  83141. **
  83142. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  83143. **
  83144. ** If p2 is negative, return the p2 characters preceding p1.
  83145. */
  83146. static void substrFunc(
  83147. sqlite3_context *context,
  83148. int argc,
  83149. sqlite3_value **argv
  83150. ){
  83151. const unsigned char *z;
  83152. const unsigned char *z2;
  83153. int len;
  83154. int p0type;
  83155. i64 p1, p2;
  83156. int negP2 = 0;
  83157. assert( argc==3 || argc==2 );
  83158. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  83159. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  83160. ){
  83161. return;
  83162. }
  83163. p0type = sqlite3_value_type(argv[0]);
  83164. p1 = sqlite3_value_int(argv[1]);
  83165. if( p0type==SQLITE_BLOB ){
  83166. len = sqlite3_value_bytes(argv[0]);
  83167. z = sqlite3_value_blob(argv[0]);
  83168. if( z==0 ) return;
  83169. assert( len==sqlite3_value_bytes(argv[0]) );
  83170. }else{
  83171. z = sqlite3_value_text(argv[0]);
  83172. if( z==0 ) return;
  83173. len = 0;
  83174. if( p1<0 ){
  83175. for(z2=z; *z2; len++){
  83176. SQLITE_SKIP_UTF8(z2);
  83177. }
  83178. }
  83179. }
  83180. if( argc==3 ){
  83181. p2 = sqlite3_value_int(argv[2]);
  83182. if( p2<0 ){
  83183. p2 = -p2;
  83184. negP2 = 1;
  83185. }
  83186. }else{
  83187. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  83188. }
  83189. if( p1<0 ){
  83190. p1 += len;
  83191. if( p1<0 ){
  83192. p2 += p1;
  83193. if( p2<0 ) p2 = 0;
  83194. p1 = 0;
  83195. }
  83196. }else if( p1>0 ){
  83197. p1--;
  83198. }else if( p2>0 ){
  83199. p2--;
  83200. }
  83201. if( negP2 ){
  83202. p1 -= p2;
  83203. if( p1<0 ){
  83204. p2 += p1;
  83205. p1 = 0;
  83206. }
  83207. }
  83208. assert( p1>=0 && p2>=0 );
  83209. if( p0type!=SQLITE_BLOB ){
  83210. while( *z && p1 ){
  83211. SQLITE_SKIP_UTF8(z);
  83212. p1--;
  83213. }
  83214. for(z2=z; *z2 && p2; p2--){
  83215. SQLITE_SKIP_UTF8(z2);
  83216. }
  83217. sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  83218. }else{
  83219. if( p1+p2>len ){
  83220. p2 = len-p1;
  83221. if( p2<0 ) p2 = 0;
  83222. }
  83223. sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  83224. }
  83225. }
  83226. /*
  83227. ** Implementation of the round() function
  83228. */
  83229. #ifndef SQLITE_OMIT_FLOATING_POINT
  83230. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  83231. int n = 0;
  83232. double r;
  83233. char *zBuf;
  83234. assert( argc==1 || argc==2 );
  83235. if( argc==2 ){
  83236. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  83237. n = sqlite3_value_int(argv[1]);
  83238. if( n>30 ) n = 30;
  83239. if( n<0 ) n = 0;
  83240. }
  83241. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  83242. r = sqlite3_value_double(argv[0]);
  83243. /* If Y==0 and X will fit in a 64-bit int,
  83244. ** handle the rounding directly,
  83245. ** otherwise use printf.
  83246. */
  83247. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  83248. r = (double)((sqlite_int64)(r+0.5));
  83249. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  83250. r = -(double)((sqlite_int64)((-r)+0.5));
  83251. }else{
  83252. zBuf = sqlite3_mprintf("%.*f",n,r);
  83253. if( zBuf==0 ){
  83254. sqlite3_result_error_nomem(context);
  83255. return;
  83256. }
  83257. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  83258. sqlite3_free(zBuf);
  83259. }
  83260. sqlite3_result_double(context, r);
  83261. }
  83262. #endif
  83263. /*
  83264. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  83265. ** allocation fails, call sqlite3_result_error_nomem() to notify
  83266. ** the database handle that malloc() has failed and return NULL.
  83267. ** If nByte is larger than the maximum string or blob length, then
  83268. ** raise an SQLITE_TOOBIG exception and return NULL.
  83269. */
  83270. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  83271. char *z;
  83272. sqlite3 *db = sqlite3_context_db_handle(context);
  83273. assert( nByte>0 );
  83274. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  83275. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  83276. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  83277. sqlite3_result_error_toobig(context);
  83278. z = 0;
  83279. }else{
  83280. z = sqlite3Malloc((int)nByte);
  83281. if( !z ){
  83282. sqlite3_result_error_nomem(context);
  83283. }
  83284. }
  83285. return z;
  83286. }
  83287. /*
  83288. ** Implementation of the upper() and lower() SQL functions.
  83289. */
  83290. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  83291. char *z1;
  83292. const char *z2;
  83293. int i, n;
  83294. UNUSED_PARAMETER(argc);
  83295. z2 = (char*)sqlite3_value_text(argv[0]);
  83296. n = sqlite3_value_bytes(argv[0]);
  83297. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  83298. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  83299. if( z2 ){
  83300. z1 = contextMalloc(context, ((i64)n)+1);
  83301. if( z1 ){
  83302. for(i=0; i<n; i++){
  83303. z1[i] = (char)sqlite3Toupper(z2[i]);
  83304. }
  83305. sqlite3_result_text(context, z1, n, sqlite3_free);
  83306. }
  83307. }
  83308. }
  83309. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  83310. char *z1;
  83311. const char *z2;
  83312. int i, n;
  83313. UNUSED_PARAMETER(argc);
  83314. z2 = (char*)sqlite3_value_text(argv[0]);
  83315. n = sqlite3_value_bytes(argv[0]);
  83316. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  83317. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  83318. if( z2 ){
  83319. z1 = contextMalloc(context, ((i64)n)+1);
  83320. if( z1 ){
  83321. for(i=0; i<n; i++){
  83322. z1[i] = sqlite3Tolower(z2[i]);
  83323. }
  83324. sqlite3_result_text(context, z1, n, sqlite3_free);
  83325. }
  83326. }
  83327. }
  83328. /*
  83329. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  83330. ** as VDBE code so that unused argument values do not have to be computed.
  83331. ** However, we still need some kind of function implementation for this
  83332. ** routines in the function table. The noopFunc macro provides this.
  83333. ** noopFunc will never be called so it doesn't matter what the implementation
  83334. ** is. We might as well use the "version()" function as a substitute.
  83335. */
  83336. #define noopFunc versionFunc /* Substitute function - never called */
  83337. /*
  83338. ** Implementation of random(). Return a random integer.
  83339. */
  83340. static void randomFunc(
  83341. sqlite3_context *context,
  83342. int NotUsed,
  83343. sqlite3_value **NotUsed2
  83344. ){
  83345. sqlite_int64 r;
  83346. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  83347. sqlite3_randomness(sizeof(r), &r);
  83348. if( r<0 ){
  83349. /* We need to prevent a random number of 0x8000000000000000
  83350. ** (or -9223372036854775808) since when you do abs() of that
  83351. ** number of you get the same value back again. To do this
  83352. ** in a way that is testable, mask the sign bit off of negative
  83353. ** values, resulting in a positive value. Then take the
  83354. ** 2s complement of that positive value. The end result can
  83355. ** therefore be no less than -9223372036854775807.
  83356. */
  83357. r = -(r & LARGEST_INT64);
  83358. }
  83359. sqlite3_result_int64(context, r);
  83360. }
  83361. /*
  83362. ** Implementation of randomblob(N). Return a random blob
  83363. ** that is N bytes long.
  83364. */
  83365. static void randomBlob(
  83366. sqlite3_context *context,
  83367. int argc,
  83368. sqlite3_value **argv
  83369. ){
  83370. int n;
  83371. unsigned char *p;
  83372. assert( argc==1 );
  83373. UNUSED_PARAMETER(argc);
  83374. n = sqlite3_value_int(argv[0]);
  83375. if( n<1 ){
  83376. n = 1;
  83377. }
  83378. p = contextMalloc(context, n);
  83379. if( p ){
  83380. sqlite3_randomness(n, p);
  83381. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  83382. }
  83383. }
  83384. /*
  83385. ** Implementation of the last_insert_rowid() SQL function. The return
  83386. ** value is the same as the sqlite3_last_insert_rowid() API function.
  83387. */
  83388. static void last_insert_rowid(
  83389. sqlite3_context *context,
  83390. int NotUsed,
  83391. sqlite3_value **NotUsed2
  83392. ){
  83393. sqlite3 *db = sqlite3_context_db_handle(context);
  83394. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  83395. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  83396. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  83397. ** function. */
  83398. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  83399. }
  83400. /*
  83401. ** Implementation of the changes() SQL function.
  83402. **
  83403. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  83404. ** around the sqlite3_changes() C/C++ function and hence follows the same
  83405. ** rules for counting changes.
  83406. */
  83407. static void changes(
  83408. sqlite3_context *context,
  83409. int NotUsed,
  83410. sqlite3_value **NotUsed2
  83411. ){
  83412. sqlite3 *db = sqlite3_context_db_handle(context);
  83413. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  83414. sqlite3_result_int(context, sqlite3_changes(db));
  83415. }
  83416. /*
  83417. ** Implementation of the total_changes() SQL function. The return value is
  83418. ** the same as the sqlite3_total_changes() API function.
  83419. */
  83420. static void total_changes(
  83421. sqlite3_context *context,
  83422. int NotUsed,
  83423. sqlite3_value **NotUsed2
  83424. ){
  83425. sqlite3 *db = sqlite3_context_db_handle(context);
  83426. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  83427. /* IMP: R-52756-41993 This function is a wrapper around the
  83428. ** sqlite3_total_changes() C/C++ interface. */
  83429. sqlite3_result_int(context, sqlite3_total_changes(db));
  83430. }
  83431. /*
  83432. ** A structure defining how to do GLOB-style comparisons.
  83433. */
  83434. struct compareInfo {
  83435. u8 matchAll;
  83436. u8 matchOne;
  83437. u8 matchSet;
  83438. u8 noCase;
  83439. };
  83440. /*
  83441. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  83442. ** character is exactly one byte in size. Also, all characters are
  83443. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  83444. ** whereas only characters less than 0x80 do in ASCII.
  83445. */
  83446. #if defined(SQLITE_EBCDIC)
  83447. # define sqlite3Utf8Read(A) (*((*A)++))
  83448. # define GlobUpperToLower(A) A = sqlite3UpperToLower[A]
  83449. #else
  83450. # define GlobUpperToLower(A) if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
  83451. #endif
  83452. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  83453. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  83454. ** case. Thus 'a' LIKE 'A' would be true. */
  83455. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  83456. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  83457. ** is case sensitive causing 'a' LIKE 'A' to be false */
  83458. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  83459. /*
  83460. ** Compare two UTF-8 strings for equality where the first string can
  83461. ** potentially be a "glob" expression. Return true (1) if they
  83462. ** are the same and false (0) if they are different.
  83463. **
  83464. ** Globbing rules:
  83465. **
  83466. ** '*' Matches any sequence of zero or more characters.
  83467. **
  83468. ** '?' Matches exactly one character.
  83469. **
  83470. ** [...] Matches one character from the enclosed list of
  83471. ** characters.
  83472. **
  83473. ** [^...] Matches one character not in the enclosed list.
  83474. **
  83475. ** With the [...] and [^...] matching, a ']' character can be included
  83476. ** in the list by making it the first character after '[' or '^'. A
  83477. ** range of characters can be specified using '-'. Example:
  83478. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  83479. ** it the last character in the list.
  83480. **
  83481. ** This routine is usually quick, but can be N**2 in the worst case.
  83482. **
  83483. ** Hints: to match '*' or '?', put them in "[]". Like this:
  83484. **
  83485. ** abc[*]xyz Matches "abc*xyz" only
  83486. */
  83487. static int patternCompare(
  83488. const u8 *zPattern, /* The glob pattern */
  83489. const u8 *zString, /* The string to compare against the glob */
  83490. const struct compareInfo *pInfo, /* Information about how to do the compare */
  83491. u32 esc /* The escape character */
  83492. ){
  83493. u32 c, c2;
  83494. int invert;
  83495. int seen;
  83496. u8 matchOne = pInfo->matchOne;
  83497. u8 matchAll = pInfo->matchAll;
  83498. u8 matchSet = pInfo->matchSet;
  83499. u8 noCase = pInfo->noCase;
  83500. int prevEscape = 0; /* True if the previous character was 'escape' */
  83501. while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
  83502. if( c==matchAll && !prevEscape ){
  83503. while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
  83504. || c == matchOne ){
  83505. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  83506. return 0;
  83507. }
  83508. }
  83509. if( c==0 ){
  83510. return 1;
  83511. }else if( c==esc ){
  83512. c = sqlite3Utf8Read(&zPattern);
  83513. if( c==0 ){
  83514. return 0;
  83515. }
  83516. }else if( c==matchSet ){
  83517. assert( esc==0 ); /* This is GLOB, not LIKE */
  83518. assert( matchSet<0x80 ); /* '[' is a single-byte character */
  83519. while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  83520. SQLITE_SKIP_UTF8(zString);
  83521. }
  83522. return *zString!=0;
  83523. }
  83524. while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
  83525. if( noCase ){
  83526. GlobUpperToLower(c2);
  83527. GlobUpperToLower(c);
  83528. while( c2 != 0 && c2 != c ){
  83529. c2 = sqlite3Utf8Read(&zString);
  83530. GlobUpperToLower(c2);
  83531. }
  83532. }else{
  83533. while( c2 != 0 && c2 != c ){
  83534. c2 = sqlite3Utf8Read(&zString);
  83535. }
  83536. }
  83537. if( c2==0 ) return 0;
  83538. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  83539. }
  83540. return 0;
  83541. }else if( c==matchOne && !prevEscape ){
  83542. if( sqlite3Utf8Read(&zString)==0 ){
  83543. return 0;
  83544. }
  83545. }else if( c==matchSet ){
  83546. u32 prior_c = 0;
  83547. assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
  83548. seen = 0;
  83549. invert = 0;
  83550. c = sqlite3Utf8Read(&zString);
  83551. if( c==0 ) return 0;
  83552. c2 = sqlite3Utf8Read(&zPattern);
  83553. if( c2=='^' ){
  83554. invert = 1;
  83555. c2 = sqlite3Utf8Read(&zPattern);
  83556. }
  83557. if( c2==']' ){
  83558. if( c==']' ) seen = 1;
  83559. c2 = sqlite3Utf8Read(&zPattern);
  83560. }
  83561. while( c2 && c2!=']' ){
  83562. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  83563. c2 = sqlite3Utf8Read(&zPattern);
  83564. if( c>=prior_c && c<=c2 ) seen = 1;
  83565. prior_c = 0;
  83566. }else{
  83567. if( c==c2 ){
  83568. seen = 1;
  83569. }
  83570. prior_c = c2;
  83571. }
  83572. c2 = sqlite3Utf8Read(&zPattern);
  83573. }
  83574. if( c2==0 || (seen ^ invert)==0 ){
  83575. return 0;
  83576. }
  83577. }else if( esc==c && !prevEscape ){
  83578. prevEscape = 1;
  83579. }else{
  83580. c2 = sqlite3Utf8Read(&zString);
  83581. if( noCase ){
  83582. GlobUpperToLower(c);
  83583. GlobUpperToLower(c2);
  83584. }
  83585. if( c!=c2 ){
  83586. return 0;
  83587. }
  83588. prevEscape = 0;
  83589. }
  83590. }
  83591. return *zString==0;
  83592. }
  83593. /*
  83594. ** The sqlite3_strglob() interface.
  83595. */
  83596. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  83597. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  83598. }
  83599. /*
  83600. ** Count the number of times that the LIKE operator (or GLOB which is
  83601. ** just a variation of LIKE) gets called. This is used for testing
  83602. ** only.
  83603. */
  83604. #ifdef SQLITE_TEST
  83605. SQLITE_API int sqlite3_like_count = 0;
  83606. #endif
  83607. /*
  83608. ** Implementation of the like() SQL function. This function implements
  83609. ** the build-in LIKE operator. The first argument to the function is the
  83610. ** pattern and the second argument is the string. So, the SQL statements:
  83611. **
  83612. ** A LIKE B
  83613. **
  83614. ** is implemented as like(B,A).
  83615. **
  83616. ** This same function (with a different compareInfo structure) computes
  83617. ** the GLOB operator.
  83618. */
  83619. static void likeFunc(
  83620. sqlite3_context *context,
  83621. int argc,
  83622. sqlite3_value **argv
  83623. ){
  83624. const unsigned char *zA, *zB;
  83625. u32 escape = 0;
  83626. int nPat;
  83627. sqlite3 *db = sqlite3_context_db_handle(context);
  83628. zB = sqlite3_value_text(argv[0]);
  83629. zA = sqlite3_value_text(argv[1]);
  83630. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  83631. ** of deep recursion and N*N behavior in patternCompare().
  83632. */
  83633. nPat = sqlite3_value_bytes(argv[0]);
  83634. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  83635. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  83636. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  83637. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  83638. return;
  83639. }
  83640. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  83641. if( argc==3 ){
  83642. /* The escape character string must consist of a single UTF-8 character.
  83643. ** Otherwise, return an error.
  83644. */
  83645. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  83646. if( zEsc==0 ) return;
  83647. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  83648. sqlite3_result_error(context,
  83649. "ESCAPE expression must be a single character", -1);
  83650. return;
  83651. }
  83652. escape = sqlite3Utf8Read(&zEsc);
  83653. }
  83654. if( zA && zB ){
  83655. struct compareInfo *pInfo = sqlite3_user_data(context);
  83656. #ifdef SQLITE_TEST
  83657. sqlite3_like_count++;
  83658. #endif
  83659. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  83660. }
  83661. }
  83662. /*
  83663. ** Implementation of the NULLIF(x,y) function. The result is the first
  83664. ** argument if the arguments are different. The result is NULL if the
  83665. ** arguments are equal to each other.
  83666. */
  83667. static void nullifFunc(
  83668. sqlite3_context *context,
  83669. int NotUsed,
  83670. sqlite3_value **argv
  83671. ){
  83672. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  83673. UNUSED_PARAMETER(NotUsed);
  83674. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  83675. sqlite3_result_value(context, argv[0]);
  83676. }
  83677. }
  83678. /*
  83679. ** Implementation of the sqlite_version() function. The result is the version
  83680. ** of the SQLite library that is running.
  83681. */
  83682. static void versionFunc(
  83683. sqlite3_context *context,
  83684. int NotUsed,
  83685. sqlite3_value **NotUsed2
  83686. ){
  83687. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  83688. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  83689. ** sqlite3_libversion() C-interface. */
  83690. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  83691. }
  83692. /*
  83693. ** Implementation of the sqlite_source_id() function. The result is a string
  83694. ** that identifies the particular version of the source code used to build
  83695. ** SQLite.
  83696. */
  83697. static void sourceidFunc(
  83698. sqlite3_context *context,
  83699. int NotUsed,
  83700. sqlite3_value **NotUsed2
  83701. ){
  83702. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  83703. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  83704. ** sqlite3_sourceid() C interface. */
  83705. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  83706. }
  83707. /*
  83708. ** Implementation of the sqlite_log() function. This is a wrapper around
  83709. ** sqlite3_log(). The return value is NULL. The function exists purely for
  83710. ** its side-effects.
  83711. */
  83712. static void errlogFunc(
  83713. sqlite3_context *context,
  83714. int argc,
  83715. sqlite3_value **argv
  83716. ){
  83717. UNUSED_PARAMETER(argc);
  83718. UNUSED_PARAMETER(context);
  83719. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  83720. }
  83721. /*
  83722. ** Implementation of the sqlite_compileoption_used() function.
  83723. ** The result is an integer that identifies if the compiler option
  83724. ** was used to build SQLite.
  83725. */
  83726. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  83727. static void compileoptionusedFunc(
  83728. sqlite3_context *context,
  83729. int argc,
  83730. sqlite3_value **argv
  83731. ){
  83732. const char *zOptName;
  83733. assert( argc==1 );
  83734. UNUSED_PARAMETER(argc);
  83735. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  83736. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  83737. ** function.
  83738. */
  83739. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  83740. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  83741. }
  83742. }
  83743. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  83744. /*
  83745. ** Implementation of the sqlite_compileoption_get() function.
  83746. ** The result is a string that identifies the compiler options
  83747. ** used to build SQLite.
  83748. */
  83749. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  83750. static void compileoptiongetFunc(
  83751. sqlite3_context *context,
  83752. int argc,
  83753. sqlite3_value **argv
  83754. ){
  83755. int n;
  83756. assert( argc==1 );
  83757. UNUSED_PARAMETER(argc);
  83758. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  83759. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  83760. */
  83761. n = sqlite3_value_int(argv[0]);
  83762. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  83763. }
  83764. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  83765. /* Array for converting from half-bytes (nybbles) into ASCII hex
  83766. ** digits. */
  83767. static const char hexdigits[] = {
  83768. '0', '1', '2', '3', '4', '5', '6', '7',
  83769. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  83770. };
  83771. /*
  83772. ** Implementation of the QUOTE() function. This function takes a single
  83773. ** argument. If the argument is numeric, the return value is the same as
  83774. ** the argument. If the argument is NULL, the return value is the string
  83775. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  83776. ** single-quote escapes.
  83777. */
  83778. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  83779. assert( argc==1 );
  83780. UNUSED_PARAMETER(argc);
  83781. switch( sqlite3_value_type(argv[0]) ){
  83782. case SQLITE_FLOAT: {
  83783. double r1, r2;
  83784. char zBuf[50];
  83785. r1 = sqlite3_value_double(argv[0]);
  83786. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  83787. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  83788. if( r1!=r2 ){
  83789. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  83790. }
  83791. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  83792. break;
  83793. }
  83794. case SQLITE_INTEGER: {
  83795. sqlite3_result_value(context, argv[0]);
  83796. break;
  83797. }
  83798. case SQLITE_BLOB: {
  83799. char *zText = 0;
  83800. char const *zBlob = sqlite3_value_blob(argv[0]);
  83801. int nBlob = sqlite3_value_bytes(argv[0]);
  83802. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  83803. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  83804. if( zText ){
  83805. int i;
  83806. for(i=0; i<nBlob; i++){
  83807. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  83808. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  83809. }
  83810. zText[(nBlob*2)+2] = '\'';
  83811. zText[(nBlob*2)+3] = '\0';
  83812. zText[0] = 'X';
  83813. zText[1] = '\'';
  83814. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  83815. sqlite3_free(zText);
  83816. }
  83817. break;
  83818. }
  83819. case SQLITE_TEXT: {
  83820. int i,j;
  83821. u64 n;
  83822. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  83823. char *z;
  83824. if( zArg==0 ) return;
  83825. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  83826. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  83827. if( z ){
  83828. z[0] = '\'';
  83829. for(i=0, j=1; zArg[i]; i++){
  83830. z[j++] = zArg[i];
  83831. if( zArg[i]=='\'' ){
  83832. z[j++] = '\'';
  83833. }
  83834. }
  83835. z[j++] = '\'';
  83836. z[j] = 0;
  83837. sqlite3_result_text(context, z, j, sqlite3_free);
  83838. }
  83839. break;
  83840. }
  83841. default: {
  83842. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  83843. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  83844. break;
  83845. }
  83846. }
  83847. }
  83848. /*
  83849. ** The unicode() function. Return the integer unicode code-point value
  83850. ** for the first character of the input string.
  83851. */
  83852. static void unicodeFunc(
  83853. sqlite3_context *context,
  83854. int argc,
  83855. sqlite3_value **argv
  83856. ){
  83857. const unsigned char *z = sqlite3_value_text(argv[0]);
  83858. (void)argc;
  83859. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  83860. }
  83861. /*
  83862. ** The char() function takes zero or more arguments, each of which is
  83863. ** an integer. It constructs a string where each character of the string
  83864. ** is the unicode character for the corresponding integer argument.
  83865. */
  83866. static void charFunc(
  83867. sqlite3_context *context,
  83868. int argc,
  83869. sqlite3_value **argv
  83870. ){
  83871. unsigned char *z, *zOut;
  83872. int i;
  83873. zOut = z = sqlite3_malloc( argc*4 );
  83874. if( z==0 ){
  83875. sqlite3_result_error_nomem(context);
  83876. return;
  83877. }
  83878. for(i=0; i<argc; i++){
  83879. sqlite3_int64 x;
  83880. unsigned c;
  83881. x = sqlite3_value_int64(argv[i]);
  83882. if( x<0 || x>0x10ffff ) x = 0xfffd;
  83883. c = (unsigned)(x & 0x1fffff);
  83884. if( c<0x00080 ){
  83885. *zOut++ = (u8)(c&0xFF);
  83886. }else if( c<0x00800 ){
  83887. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  83888. *zOut++ = 0x80 + (u8)(c & 0x3F);
  83889. }else if( c<0x10000 ){
  83890. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  83891. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  83892. *zOut++ = 0x80 + (u8)(c & 0x3F);
  83893. }else{
  83894. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  83895. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  83896. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  83897. *zOut++ = 0x80 + (u8)(c & 0x3F);
  83898. } \
  83899. }
  83900. sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
  83901. }
  83902. /*
  83903. ** The hex() function. Interpret the argument as a blob. Return
  83904. ** a hexadecimal rendering as text.
  83905. */
  83906. static void hexFunc(
  83907. sqlite3_context *context,
  83908. int argc,
  83909. sqlite3_value **argv
  83910. ){
  83911. int i, n;
  83912. const unsigned char *pBlob;
  83913. char *zHex, *z;
  83914. assert( argc==1 );
  83915. UNUSED_PARAMETER(argc);
  83916. pBlob = sqlite3_value_blob(argv[0]);
  83917. n = sqlite3_value_bytes(argv[0]);
  83918. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  83919. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  83920. if( zHex ){
  83921. for(i=0; i<n; i++, pBlob++){
  83922. unsigned char c = *pBlob;
  83923. *(z++) = hexdigits[(c>>4)&0xf];
  83924. *(z++) = hexdigits[c&0xf];
  83925. }
  83926. *z = 0;
  83927. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  83928. }
  83929. }
  83930. /*
  83931. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  83932. */
  83933. static void zeroblobFunc(
  83934. sqlite3_context *context,
  83935. int argc,
  83936. sqlite3_value **argv
  83937. ){
  83938. i64 n;
  83939. sqlite3 *db = sqlite3_context_db_handle(context);
  83940. assert( argc==1 );
  83941. UNUSED_PARAMETER(argc);
  83942. n = sqlite3_value_int64(argv[0]);
  83943. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  83944. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  83945. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  83946. sqlite3_result_error_toobig(context);
  83947. }else{
  83948. sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
  83949. }
  83950. }
  83951. /*
  83952. ** The replace() function. Three arguments are all strings: call
  83953. ** them A, B, and C. The result is also a string which is derived
  83954. ** from A by replacing every occurrence of B with C. The match
  83955. ** must be exact. Collating sequences are not used.
  83956. */
  83957. static void replaceFunc(
  83958. sqlite3_context *context,
  83959. int argc,
  83960. sqlite3_value **argv
  83961. ){
  83962. const unsigned char *zStr; /* The input string A */
  83963. const unsigned char *zPattern; /* The pattern string B */
  83964. const unsigned char *zRep; /* The replacement string C */
  83965. unsigned char *zOut; /* The output */
  83966. int nStr; /* Size of zStr */
  83967. int nPattern; /* Size of zPattern */
  83968. int nRep; /* Size of zRep */
  83969. i64 nOut; /* Maximum size of zOut */
  83970. int loopLimit; /* Last zStr[] that might match zPattern[] */
  83971. int i, j; /* Loop counters */
  83972. assert( argc==3 );
  83973. UNUSED_PARAMETER(argc);
  83974. zStr = sqlite3_value_text(argv[0]);
  83975. if( zStr==0 ) return;
  83976. nStr = sqlite3_value_bytes(argv[0]);
  83977. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  83978. zPattern = sqlite3_value_text(argv[1]);
  83979. if( zPattern==0 ){
  83980. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  83981. || sqlite3_context_db_handle(context)->mallocFailed );
  83982. return;
  83983. }
  83984. if( zPattern[0]==0 ){
  83985. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  83986. sqlite3_result_value(context, argv[0]);
  83987. return;
  83988. }
  83989. nPattern = sqlite3_value_bytes(argv[1]);
  83990. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  83991. zRep = sqlite3_value_text(argv[2]);
  83992. if( zRep==0 ) return;
  83993. nRep = sqlite3_value_bytes(argv[2]);
  83994. assert( zRep==sqlite3_value_text(argv[2]) );
  83995. nOut = nStr + 1;
  83996. assert( nOut<SQLITE_MAX_LENGTH );
  83997. zOut = contextMalloc(context, (i64)nOut);
  83998. if( zOut==0 ){
  83999. return;
  84000. }
  84001. loopLimit = nStr - nPattern;
  84002. for(i=j=0; i<=loopLimit; i++){
  84003. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  84004. zOut[j++] = zStr[i];
  84005. }else{
  84006. u8 *zOld;
  84007. sqlite3 *db = sqlite3_context_db_handle(context);
  84008. nOut += nRep - nPattern;
  84009. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  84010. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  84011. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  84012. sqlite3_result_error_toobig(context);
  84013. sqlite3_free(zOut);
  84014. return;
  84015. }
  84016. zOld = zOut;
  84017. zOut = sqlite3_realloc(zOut, (int)nOut);
  84018. if( zOut==0 ){
  84019. sqlite3_result_error_nomem(context);
  84020. sqlite3_free(zOld);
  84021. return;
  84022. }
  84023. memcpy(&zOut[j], zRep, nRep);
  84024. j += nRep;
  84025. i += nPattern-1;
  84026. }
  84027. }
  84028. assert( j+nStr-i+1==nOut );
  84029. memcpy(&zOut[j], &zStr[i], nStr-i);
  84030. j += nStr - i;
  84031. assert( j<=nOut );
  84032. zOut[j] = 0;
  84033. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  84034. }
  84035. /*
  84036. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  84037. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  84038. */
  84039. static void trimFunc(
  84040. sqlite3_context *context,
  84041. int argc,
  84042. sqlite3_value **argv
  84043. ){
  84044. const unsigned char *zIn; /* Input string */
  84045. const unsigned char *zCharSet; /* Set of characters to trim */
  84046. int nIn; /* Number of bytes in input */
  84047. int flags; /* 1: trimleft 2: trimright 3: trim */
  84048. int i; /* Loop counter */
  84049. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  84050. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  84051. int nChar; /* Number of characters in zCharSet */
  84052. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  84053. return;
  84054. }
  84055. zIn = sqlite3_value_text(argv[0]);
  84056. if( zIn==0 ) return;
  84057. nIn = sqlite3_value_bytes(argv[0]);
  84058. assert( zIn==sqlite3_value_text(argv[0]) );
  84059. if( argc==1 ){
  84060. static const unsigned char lenOne[] = { 1 };
  84061. static unsigned char * const azOne[] = { (u8*)" " };
  84062. nChar = 1;
  84063. aLen = (u8*)lenOne;
  84064. azChar = (unsigned char **)azOne;
  84065. zCharSet = 0;
  84066. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  84067. return;
  84068. }else{
  84069. const unsigned char *z;
  84070. for(z=zCharSet, nChar=0; *z; nChar++){
  84071. SQLITE_SKIP_UTF8(z);
  84072. }
  84073. if( nChar>0 ){
  84074. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  84075. if( azChar==0 ){
  84076. return;
  84077. }
  84078. aLen = (unsigned char*)&azChar[nChar];
  84079. for(z=zCharSet, nChar=0; *z; nChar++){
  84080. azChar[nChar] = (unsigned char *)z;
  84081. SQLITE_SKIP_UTF8(z);
  84082. aLen[nChar] = (u8)(z - azChar[nChar]);
  84083. }
  84084. }
  84085. }
  84086. if( nChar>0 ){
  84087. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  84088. if( flags & 1 ){
  84089. while( nIn>0 ){
  84090. int len = 0;
  84091. for(i=0; i<nChar; i++){
  84092. len = aLen[i];
  84093. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  84094. }
  84095. if( i>=nChar ) break;
  84096. zIn += len;
  84097. nIn -= len;
  84098. }
  84099. }
  84100. if( flags & 2 ){
  84101. while( nIn>0 ){
  84102. int len = 0;
  84103. for(i=0; i<nChar; i++){
  84104. len = aLen[i];
  84105. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  84106. }
  84107. if( i>=nChar ) break;
  84108. nIn -= len;
  84109. }
  84110. }
  84111. if( zCharSet ){
  84112. sqlite3_free(azChar);
  84113. }
  84114. }
  84115. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  84116. }
  84117. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  84118. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  84119. ** when SQLite is built.
  84120. */
  84121. #ifdef SQLITE_SOUNDEX
  84122. /*
  84123. ** Compute the soundex encoding of a word.
  84124. **
  84125. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  84126. ** soundex encoding of the string X.
  84127. */
  84128. static void soundexFunc(
  84129. sqlite3_context *context,
  84130. int argc,
  84131. sqlite3_value **argv
  84132. ){
  84133. char zResult[8];
  84134. const u8 *zIn;
  84135. int i, j;
  84136. static const unsigned char iCode[] = {
  84137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  84138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  84139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  84140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  84141. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  84142. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  84143. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  84144. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  84145. };
  84146. assert( argc==1 );
  84147. zIn = (u8*)sqlite3_value_text(argv[0]);
  84148. if( zIn==0 ) zIn = (u8*)"";
  84149. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  84150. if( zIn[i] ){
  84151. u8 prevcode = iCode[zIn[i]&0x7f];
  84152. zResult[0] = sqlite3Toupper(zIn[i]);
  84153. for(j=1; j<4 && zIn[i]; i++){
  84154. int code = iCode[zIn[i]&0x7f];
  84155. if( code>0 ){
  84156. if( code!=prevcode ){
  84157. prevcode = code;
  84158. zResult[j++] = code + '0';
  84159. }
  84160. }else{
  84161. prevcode = 0;
  84162. }
  84163. }
  84164. while( j<4 ){
  84165. zResult[j++] = '0';
  84166. }
  84167. zResult[j] = 0;
  84168. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  84169. }else{
  84170. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  84171. ** is NULL or contains no ASCII alphabetic characters. */
  84172. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  84173. }
  84174. }
  84175. #endif /* SQLITE_SOUNDEX */
  84176. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  84177. /*
  84178. ** A function that loads a shared-library extension then returns NULL.
  84179. */
  84180. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  84181. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  84182. const char *zProc;
  84183. sqlite3 *db = sqlite3_context_db_handle(context);
  84184. char *zErrMsg = 0;
  84185. if( argc==2 ){
  84186. zProc = (const char *)sqlite3_value_text(argv[1]);
  84187. }else{
  84188. zProc = 0;
  84189. }
  84190. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  84191. sqlite3_result_error(context, zErrMsg, -1);
  84192. sqlite3_free(zErrMsg);
  84193. }
  84194. }
  84195. #endif
  84196. /*
  84197. ** An instance of the following structure holds the context of a
  84198. ** sum() or avg() aggregate computation.
  84199. */
  84200. typedef struct SumCtx SumCtx;
  84201. struct SumCtx {
  84202. double rSum; /* Floating point sum */
  84203. i64 iSum; /* Integer sum */
  84204. i64 cnt; /* Number of elements summed */
  84205. u8 overflow; /* True if integer overflow seen */
  84206. u8 approx; /* True if non-integer value was input to the sum */
  84207. };
  84208. /*
  84209. ** Routines used to compute the sum, average, and total.
  84210. **
  84211. ** The SUM() function follows the (broken) SQL standard which means
  84212. ** that it returns NULL if it sums over no inputs. TOTAL returns
  84213. ** 0.0 in that case. In addition, TOTAL always returns a float where
  84214. ** SUM might return an integer if it never encounters a floating point
  84215. ** value. TOTAL never fails, but SUM might through an exception if
  84216. ** it overflows an integer.
  84217. */
  84218. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  84219. SumCtx *p;
  84220. int type;
  84221. assert( argc==1 );
  84222. UNUSED_PARAMETER(argc);
  84223. p = sqlite3_aggregate_context(context, sizeof(*p));
  84224. type = sqlite3_value_numeric_type(argv[0]);
  84225. if( p && type!=SQLITE_NULL ){
  84226. p->cnt++;
  84227. if( type==SQLITE_INTEGER ){
  84228. i64 v = sqlite3_value_int64(argv[0]);
  84229. p->rSum += v;
  84230. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  84231. p->overflow = 1;
  84232. }
  84233. }else{
  84234. p->rSum += sqlite3_value_double(argv[0]);
  84235. p->approx = 1;
  84236. }
  84237. }
  84238. }
  84239. static void sumFinalize(sqlite3_context *context){
  84240. SumCtx *p;
  84241. p = sqlite3_aggregate_context(context, 0);
  84242. if( p && p->cnt>0 ){
  84243. if( p->overflow ){
  84244. sqlite3_result_error(context,"integer overflow",-1);
  84245. }else if( p->approx ){
  84246. sqlite3_result_double(context, p->rSum);
  84247. }else{
  84248. sqlite3_result_int64(context, p->iSum);
  84249. }
  84250. }
  84251. }
  84252. static void avgFinalize(sqlite3_context *context){
  84253. SumCtx *p;
  84254. p = sqlite3_aggregate_context(context, 0);
  84255. if( p && p->cnt>0 ){
  84256. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  84257. }
  84258. }
  84259. static void totalFinalize(sqlite3_context *context){
  84260. SumCtx *p;
  84261. p = sqlite3_aggregate_context(context, 0);
  84262. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  84263. sqlite3_result_double(context, p ? p->rSum : (double)0);
  84264. }
  84265. /*
  84266. ** The following structure keeps track of state information for the
  84267. ** count() aggregate function.
  84268. */
  84269. typedef struct CountCtx CountCtx;
  84270. struct CountCtx {
  84271. i64 n;
  84272. };
  84273. /*
  84274. ** Routines to implement the count() aggregate function.
  84275. */
  84276. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  84277. CountCtx *p;
  84278. p = sqlite3_aggregate_context(context, sizeof(*p));
  84279. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  84280. p->n++;
  84281. }
  84282. #ifndef SQLITE_OMIT_DEPRECATED
  84283. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  84284. ** sure it still operates correctly, verify that its count agrees with our
  84285. ** internal count when using count(*) and when the total count can be
  84286. ** expressed as a 32-bit integer. */
  84287. assert( argc==1 || p==0 || p->n>0x7fffffff
  84288. || p->n==sqlite3_aggregate_count(context) );
  84289. #endif
  84290. }
  84291. static void countFinalize(sqlite3_context *context){
  84292. CountCtx *p;
  84293. p = sqlite3_aggregate_context(context, 0);
  84294. sqlite3_result_int64(context, p ? p->n : 0);
  84295. }
  84296. /*
  84297. ** Routines to implement min() and max() aggregate functions.
  84298. */
  84299. static void minmaxStep(
  84300. sqlite3_context *context,
  84301. int NotUsed,
  84302. sqlite3_value **argv
  84303. ){
  84304. Mem *pArg = (Mem *)argv[0];
  84305. Mem *pBest;
  84306. UNUSED_PARAMETER(NotUsed);
  84307. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  84308. if( !pBest ) return;
  84309. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  84310. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  84311. }else if( pBest->flags ){
  84312. int max;
  84313. int cmp;
  84314. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  84315. /* This step function is used for both the min() and max() aggregates,
  84316. ** the only difference between the two being that the sense of the
  84317. ** comparison is inverted. For the max() aggregate, the
  84318. ** sqlite3_user_data() function returns (void *)-1. For min() it
  84319. ** returns (void *)db, where db is the sqlite3* database pointer.
  84320. ** Therefore the next statement sets variable 'max' to 1 for the max()
  84321. ** aggregate, or 0 for min().
  84322. */
  84323. max = sqlite3_user_data(context)!=0;
  84324. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  84325. if( (max && cmp<0) || (!max && cmp>0) ){
  84326. sqlite3VdbeMemCopy(pBest, pArg);
  84327. }else{
  84328. sqlite3SkipAccumulatorLoad(context);
  84329. }
  84330. }else{
  84331. sqlite3VdbeMemCopy(pBest, pArg);
  84332. }
  84333. }
  84334. static void minMaxFinalize(sqlite3_context *context){
  84335. sqlite3_value *pRes;
  84336. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  84337. if( pRes ){
  84338. if( pRes->flags ){
  84339. sqlite3_result_value(context, pRes);
  84340. }
  84341. sqlite3VdbeMemRelease(pRes);
  84342. }
  84343. }
  84344. /*
  84345. ** group_concat(EXPR, ?SEPARATOR?)
  84346. */
  84347. static void groupConcatStep(
  84348. sqlite3_context *context,
  84349. int argc,
  84350. sqlite3_value **argv
  84351. ){
  84352. const char *zVal;
  84353. StrAccum *pAccum;
  84354. const char *zSep;
  84355. int nVal, nSep;
  84356. assert( argc==1 || argc==2 );
  84357. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  84358. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  84359. if( pAccum ){
  84360. sqlite3 *db = sqlite3_context_db_handle(context);
  84361. int firstTerm = pAccum->useMalloc==0;
  84362. pAccum->useMalloc = 2;
  84363. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  84364. if( !firstTerm ){
  84365. if( argc==2 ){
  84366. zSep = (char*)sqlite3_value_text(argv[1]);
  84367. nSep = sqlite3_value_bytes(argv[1]);
  84368. }else{
  84369. zSep = ",";
  84370. nSep = 1;
  84371. }
  84372. sqlite3StrAccumAppend(pAccum, zSep, nSep);
  84373. }
  84374. zVal = (char*)sqlite3_value_text(argv[0]);
  84375. nVal = sqlite3_value_bytes(argv[0]);
  84376. sqlite3StrAccumAppend(pAccum, zVal, nVal);
  84377. }
  84378. }
  84379. static void groupConcatFinalize(sqlite3_context *context){
  84380. StrAccum *pAccum;
  84381. pAccum = sqlite3_aggregate_context(context, 0);
  84382. if( pAccum ){
  84383. if( pAccum->accError==STRACCUM_TOOBIG ){
  84384. sqlite3_result_error_toobig(context);
  84385. }else if( pAccum->accError==STRACCUM_NOMEM ){
  84386. sqlite3_result_error_nomem(context);
  84387. }else{
  84388. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  84389. sqlite3_free);
  84390. }
  84391. }
  84392. }
  84393. /*
  84394. ** This routine does per-connection function registration. Most
  84395. ** of the built-in functions above are part of the global function set.
  84396. ** This routine only deals with those that are not global.
  84397. */
  84398. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  84399. int rc = sqlite3_overload_function(db, "MATCH", 2);
  84400. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  84401. if( rc==SQLITE_NOMEM ){
  84402. db->mallocFailed = 1;
  84403. }
  84404. }
  84405. /*
  84406. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  84407. */
  84408. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  84409. FuncDef *pDef;
  84410. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  84411. 2, SQLITE_UTF8, 0);
  84412. if( ALWAYS(pDef) ){
  84413. pDef->funcFlags |= flagVal;
  84414. }
  84415. }
  84416. /*
  84417. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  84418. ** parameter determines whether or not the LIKE operator is case
  84419. ** sensitive. GLOB is always case sensitive.
  84420. */
  84421. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  84422. struct compareInfo *pInfo;
  84423. if( caseSensitive ){
  84424. pInfo = (struct compareInfo*)&likeInfoAlt;
  84425. }else{
  84426. pInfo = (struct compareInfo*)&likeInfoNorm;
  84427. }
  84428. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  84429. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  84430. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  84431. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  84432. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  84433. setLikeOptFlag(db, "like",
  84434. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  84435. }
  84436. /*
  84437. ** pExpr points to an expression which implements a function. If
  84438. ** it is appropriate to apply the LIKE optimization to that function
  84439. ** then set aWc[0] through aWc[2] to the wildcard characters and
  84440. ** return TRUE. If the function is not a LIKE-style function then
  84441. ** return FALSE.
  84442. */
  84443. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  84444. FuncDef *pDef;
  84445. if( pExpr->op!=TK_FUNCTION
  84446. || !pExpr->x.pList
  84447. || pExpr->x.pList->nExpr!=2
  84448. ){
  84449. return 0;
  84450. }
  84451. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  84452. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  84453. sqlite3Strlen30(pExpr->u.zToken),
  84454. 2, SQLITE_UTF8, 0);
  84455. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  84456. return 0;
  84457. }
  84458. /* The memcpy() statement assumes that the wildcard characters are
  84459. ** the first three statements in the compareInfo structure. The
  84460. ** asserts() that follow verify that assumption
  84461. */
  84462. memcpy(aWc, pDef->pUserData, 3);
  84463. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  84464. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  84465. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  84466. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  84467. return 1;
  84468. }
  84469. /*
  84470. ** All all of the FuncDef structures in the aBuiltinFunc[] array above
  84471. ** to the global function hash table. This occurs at start-time (as
  84472. ** a consequence of calling sqlite3_initialize()).
  84473. **
  84474. ** After this routine runs
  84475. */
  84476. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  84477. /*
  84478. ** The following array holds FuncDef structures for all of the functions
  84479. ** defined in this file.
  84480. **
  84481. ** The array cannot be constant since changes are made to the
  84482. ** FuncDef.pHash elements at start-time. The elements of this array
  84483. ** are read-only after initialization is complete.
  84484. */
  84485. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  84486. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  84487. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  84488. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  84489. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  84490. FUNCTION(trim, 1, 3, 0, trimFunc ),
  84491. FUNCTION(trim, 2, 3, 0, trimFunc ),
  84492. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  84493. FUNCTION(min, 0, 0, 1, 0 ),
  84494. AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
  84495. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  84496. FUNCTION(max, 0, 1, 1, 0 ),
  84497. AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
  84498. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  84499. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  84500. FUNCTION(instr, 2, 0, 0, instrFunc ),
  84501. FUNCTION(substr, 2, 0, 0, substrFunc ),
  84502. FUNCTION(substr, 3, 0, 0, substrFunc ),
  84503. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  84504. FUNCTION(char, -1, 0, 0, charFunc ),
  84505. FUNCTION(abs, 1, 0, 0, absFunc ),
  84506. #ifndef SQLITE_OMIT_FLOATING_POINT
  84507. FUNCTION(round, 1, 0, 0, roundFunc ),
  84508. FUNCTION(round, 2, 0, 0, roundFunc ),
  84509. #endif
  84510. FUNCTION(upper, 1, 0, 0, upperFunc ),
  84511. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  84512. FUNCTION(coalesce, 1, 0, 0, 0 ),
  84513. FUNCTION(coalesce, 0, 0, 0, 0 ),
  84514. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  84515. FUNCTION(hex, 1, 0, 0, hexFunc ),
  84516. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  84517. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  84518. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  84519. FUNCTION(random, 0, 0, 0, randomFunc ),
  84520. FUNCTION(randomblob, 1, 0, 0, randomBlob ),
  84521. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  84522. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  84523. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  84524. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  84525. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  84526. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  84527. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  84528. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  84529. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  84530. FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  84531. FUNCTION(changes, 0, 0, 0, changes ),
  84532. FUNCTION(total_changes, 0, 0, 0, total_changes ),
  84533. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  84534. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  84535. #ifdef SQLITE_SOUNDEX
  84536. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  84537. #endif
  84538. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  84539. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  84540. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  84541. #endif
  84542. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  84543. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  84544. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  84545. /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
  84546. {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
  84547. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  84548. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  84549. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  84550. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  84551. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  84552. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  84553. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  84554. #else
  84555. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  84556. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  84557. #endif
  84558. };
  84559. int i;
  84560. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  84561. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  84562. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  84563. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  84564. }
  84565. sqlite3RegisterDateTimeFunctions();
  84566. #ifndef SQLITE_OMIT_ALTERTABLE
  84567. sqlite3AlterFunctions();
  84568. #endif
  84569. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  84570. sqlite3AnalyzeFunctions();
  84571. #endif
  84572. }
  84573. /************** End of func.c ************************************************/
  84574. /************** Begin file fkey.c ********************************************/
  84575. /*
  84576. **
  84577. ** The author disclaims copyright to this source code. In place of
  84578. ** a legal notice, here is a blessing:
  84579. **
  84580. ** May you do good and not evil.
  84581. ** May you find forgiveness for yourself and forgive others.
  84582. ** May you share freely, never taking more than you give.
  84583. **
  84584. *************************************************************************
  84585. ** This file contains code used by the compiler to add foreign key
  84586. ** support to compiled SQL statements.
  84587. */
  84588. #ifndef SQLITE_OMIT_FOREIGN_KEY
  84589. #ifndef SQLITE_OMIT_TRIGGER
  84590. /*
  84591. ** Deferred and Immediate FKs
  84592. ** --------------------------
  84593. **
  84594. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  84595. ** If an immediate foreign key constraint is violated,
  84596. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  84597. ** statement transaction rolled back. If a
  84598. ** deferred foreign key constraint is violated, no action is taken
  84599. ** immediately. However if the application attempts to commit the
  84600. ** transaction before fixing the constraint violation, the attempt fails.
  84601. **
  84602. ** Deferred constraints are implemented using a simple counter associated
  84603. ** with the database handle. The counter is set to zero each time a
  84604. ** database transaction is opened. Each time a statement is executed
  84605. ** that causes a foreign key violation, the counter is incremented. Each
  84606. ** time a statement is executed that removes an existing violation from
  84607. ** the database, the counter is decremented. When the transaction is
  84608. ** committed, the commit fails if the current value of the counter is
  84609. ** greater than zero. This scheme has two big drawbacks:
  84610. **
  84611. ** * When a commit fails due to a deferred foreign key constraint,
  84612. ** there is no way to tell which foreign constraint is not satisfied,
  84613. ** or which row it is not satisfied for.
  84614. **
  84615. ** * If the database contains foreign key violations when the
  84616. ** transaction is opened, this may cause the mechanism to malfunction.
  84617. **
  84618. ** Despite these problems, this approach is adopted as it seems simpler
  84619. ** than the alternatives.
  84620. **
  84621. ** INSERT operations:
  84622. **
  84623. ** I.1) For each FK for which the table is the child table, search
  84624. ** the parent table for a match. If none is found increment the
  84625. ** constraint counter.
  84626. **
  84627. ** I.2) For each FK for which the table is the parent table,
  84628. ** search the child table for rows that correspond to the new
  84629. ** row in the parent table. Decrement the counter for each row
  84630. ** found (as the constraint is now satisfied).
  84631. **
  84632. ** DELETE operations:
  84633. **
  84634. ** D.1) For each FK for which the table is the child table,
  84635. ** search the parent table for a row that corresponds to the
  84636. ** deleted row in the child table. If such a row is not found,
  84637. ** decrement the counter.
  84638. **
  84639. ** D.2) For each FK for which the table is the parent table, search
  84640. ** the child table for rows that correspond to the deleted row
  84641. ** in the parent table. For each found increment the counter.
  84642. **
  84643. ** UPDATE operations:
  84644. **
  84645. ** An UPDATE command requires that all 4 steps above are taken, but only
  84646. ** for FK constraints for which the affected columns are actually
  84647. ** modified (values must be compared at runtime).
  84648. **
  84649. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  84650. ** This simplifies the implementation a bit.
  84651. **
  84652. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  84653. ** resolution is considered to delete rows before the new row is inserted.
  84654. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  84655. ** is thrown, even if the FK constraint would be satisfied after the new
  84656. ** row is inserted.
  84657. **
  84658. ** Immediate constraints are usually handled similarly. The only difference
  84659. ** is that the counter used is stored as part of each individual statement
  84660. ** object (struct Vdbe). If, after the statement has run, its immediate
  84661. ** constraint counter is greater than zero,
  84662. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  84663. ** and the statement transaction is rolled back. An exception is an INSERT
  84664. ** statement that inserts a single row only (no triggers). In this case,
  84665. ** instead of using a counter, an exception is thrown immediately if the
  84666. ** INSERT violates a foreign key constraint. This is necessary as such
  84667. ** an INSERT does not open a statement transaction.
  84668. **
  84669. ** TODO: How should dropping a table be handled? How should renaming a
  84670. ** table be handled?
  84671. **
  84672. **
  84673. ** Query API Notes
  84674. ** ---------------
  84675. **
  84676. ** Before coding an UPDATE or DELETE row operation, the code-generator
  84677. ** for those two operations needs to know whether or not the operation
  84678. ** requires any FK processing and, if so, which columns of the original
  84679. ** row are required by the FK processing VDBE code (i.e. if FKs were
  84680. ** implemented using triggers, which of the old.* columns would be
  84681. ** accessed). No information is required by the code-generator before
  84682. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  84683. ** generation code to query for this information are:
  84684. **
  84685. ** sqlite3FkRequired() - Test to see if FK processing is required.
  84686. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  84687. **
  84688. **
  84689. ** Externally accessible module functions
  84690. ** --------------------------------------
  84691. **
  84692. ** sqlite3FkCheck() - Check for foreign key violations.
  84693. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  84694. ** sqlite3FkDelete() - Delete an FKey structure.
  84695. */
  84696. /*
  84697. ** VDBE Calling Convention
  84698. ** -----------------------
  84699. **
  84700. ** Example:
  84701. **
  84702. ** For the following INSERT statement:
  84703. **
  84704. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  84705. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  84706. **
  84707. ** Register (x): 2 (type integer)
  84708. ** Register (x+1): 1 (type integer)
  84709. ** Register (x+2): NULL (type NULL)
  84710. ** Register (x+3): 3.1 (type real)
  84711. */
  84712. /*
  84713. ** A foreign key constraint requires that the key columns in the parent
  84714. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  84715. ** Given that pParent is the parent table for foreign key constraint pFKey,
  84716. ** search the schema for a unique index on the parent key columns.
  84717. **
  84718. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  84719. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  84720. ** is set to point to the unique index.
  84721. **
  84722. ** If the parent key consists of a single column (the foreign key constraint
  84723. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  84724. ** Otherwise, it is set to point to an allocated array of size N, where
  84725. ** N is the number of columns in the parent key. The first element of the
  84726. ** array is the index of the child table column that is mapped by the FK
  84727. ** constraint to the parent table column stored in the left-most column
  84728. ** of index *ppIdx. The second element of the array is the index of the
  84729. ** child table column that corresponds to the second left-most column of
  84730. ** *ppIdx, and so on.
  84731. **
  84732. ** If the required index cannot be found, either because:
  84733. **
  84734. ** 1) The named parent key columns do not exist, or
  84735. **
  84736. ** 2) The named parent key columns do exist, but are not subject to a
  84737. ** UNIQUE or PRIMARY KEY constraint, or
  84738. **
  84739. ** 3) No parent key columns were provided explicitly as part of the
  84740. ** foreign key definition, and the parent table does not have a
  84741. ** PRIMARY KEY, or
  84742. **
  84743. ** 4) No parent key columns were provided explicitly as part of the
  84744. ** foreign key definition, and the PRIMARY KEY of the parent table
  84745. ** consists of a a different number of columns to the child key in
  84746. ** the child table.
  84747. **
  84748. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  84749. ** into pParse. If an OOM error occurs, non-zero is returned and the
  84750. ** pParse->db->mallocFailed flag is set.
  84751. */
  84752. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  84753. Parse *pParse, /* Parse context to store any error in */
  84754. Table *pParent, /* Parent table of FK constraint pFKey */
  84755. FKey *pFKey, /* Foreign key to find index for */
  84756. Index **ppIdx, /* OUT: Unique index on parent table */
  84757. int **paiCol /* OUT: Map of index columns in pFKey */
  84758. ){
  84759. Index *pIdx = 0; /* Value to return via *ppIdx */
  84760. int *aiCol = 0; /* Value to return via *paiCol */
  84761. int nCol = pFKey->nCol; /* Number of columns in parent key */
  84762. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  84763. /* The caller is responsible for zeroing output parameters. */
  84764. assert( ppIdx && *ppIdx==0 );
  84765. assert( !paiCol || *paiCol==0 );
  84766. assert( pParse );
  84767. /* If this is a non-composite (single column) foreign key, check if it
  84768. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  84769. ** and *paiCol set to zero and return early.
  84770. **
  84771. ** Otherwise, for a composite foreign key (more than one column), allocate
  84772. ** space for the aiCol array (returned via output parameter *paiCol).
  84773. ** Non-composite foreign keys do not require the aiCol array.
  84774. */
  84775. if( nCol==1 ){
  84776. /* The FK maps to the IPK if any of the following are true:
  84777. **
  84778. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  84779. ** mapped to the primary key of table pParent, or
  84780. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  84781. ** PRIMARY KEY.
  84782. */
  84783. if( pParent->iPKey>=0 ){
  84784. if( !zKey ) return 0;
  84785. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  84786. }
  84787. }else if( paiCol ){
  84788. assert( nCol>1 );
  84789. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  84790. if( !aiCol ) return 1;
  84791. *paiCol = aiCol;
  84792. }
  84793. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  84794. if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
  84795. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  84796. ** of columns. If each indexed column corresponds to a foreign key
  84797. ** column of pFKey, then this index is a winner. */
  84798. if( zKey==0 ){
  84799. /* If zKey is NULL, then this foreign key is implicitly mapped to
  84800. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  84801. ** identified by the test (Index.autoIndex==2). */
  84802. if( pIdx->autoIndex==2 ){
  84803. if( aiCol ){
  84804. int i;
  84805. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  84806. }
  84807. break;
  84808. }
  84809. }else{
  84810. /* If zKey is non-NULL, then this foreign key was declared to
  84811. ** map to an explicit list of columns in table pParent. Check if this
  84812. ** index matches those columns. Also, check that the index uses
  84813. ** the default collation sequences for each column. */
  84814. int i, j;
  84815. for(i=0; i<nCol; i++){
  84816. int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  84817. char *zDfltColl; /* Def. collation for column */
  84818. char *zIdxCol; /* Name of indexed column */
  84819. /* If the index uses a collation sequence that is different from
  84820. ** the default collation sequence for the column, this index is
  84821. ** unusable. Bail out early in this case. */
  84822. zDfltColl = pParent->aCol[iCol].zColl;
  84823. if( !zDfltColl ){
  84824. zDfltColl = "BINARY";
  84825. }
  84826. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  84827. zIdxCol = pParent->aCol[iCol].zName;
  84828. for(j=0; j<nCol; j++){
  84829. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  84830. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  84831. break;
  84832. }
  84833. }
  84834. if( j==nCol ) break;
  84835. }
  84836. if( i==nCol ) break; /* pIdx is usable */
  84837. }
  84838. }
  84839. }
  84840. if( !pIdx ){
  84841. if( !pParse->disableTriggers ){
  84842. sqlite3ErrorMsg(pParse,
  84843. "foreign key mismatch - \"%w\" referencing \"%w\"",
  84844. pFKey->pFrom->zName, pFKey->zTo);
  84845. }
  84846. sqlite3DbFree(pParse->db, aiCol);
  84847. return 1;
  84848. }
  84849. *ppIdx = pIdx;
  84850. return 0;
  84851. }
  84852. /*
  84853. ** This function is called when a row is inserted into or deleted from the
  84854. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  84855. ** on the child table of pFKey, this function is invoked twice for each row
  84856. ** affected - once to "delete" the old row, and then again to "insert" the
  84857. ** new row.
  84858. **
  84859. ** Each time it is called, this function generates VDBE code to locate the
  84860. ** row in the parent table that corresponds to the row being inserted into
  84861. ** or deleted from the child table. If the parent row can be found, no
  84862. ** special action is taken. Otherwise, if the parent row can *not* be
  84863. ** found in the parent table:
  84864. **
  84865. ** Operation | FK type | Action taken
  84866. ** --------------------------------------------------------------------------
  84867. ** INSERT immediate Increment the "immediate constraint counter".
  84868. **
  84869. ** DELETE immediate Decrement the "immediate constraint counter".
  84870. **
  84871. ** INSERT deferred Increment the "deferred constraint counter".
  84872. **
  84873. ** DELETE deferred Decrement the "deferred constraint counter".
  84874. **
  84875. ** These operations are identified in the comment at the top of this file
  84876. ** (fkey.c) as "I.1" and "D.1".
  84877. */
  84878. static void fkLookupParent(
  84879. Parse *pParse, /* Parse context */
  84880. int iDb, /* Index of database housing pTab */
  84881. Table *pTab, /* Parent table of FK pFKey */
  84882. Index *pIdx, /* Unique index on parent key columns in pTab */
  84883. FKey *pFKey, /* Foreign key constraint */
  84884. int *aiCol, /* Map from parent key columns to child table columns */
  84885. int regData, /* Address of array containing child table row */
  84886. int nIncr, /* Increment constraint counter by this */
  84887. int isIgnore /* If true, pretend pTab contains all NULL values */
  84888. ){
  84889. int i; /* Iterator variable */
  84890. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  84891. int iCur = pParse->nTab - 1; /* Cursor number to use */
  84892. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  84893. /* If nIncr is less than zero, then check at runtime if there are any
  84894. ** outstanding constraints to resolve. If there are not, there is no need
  84895. ** to check if deleting this row resolves any outstanding violations.
  84896. **
  84897. ** Check if any of the key columns in the child table row are NULL. If
  84898. ** any are, then the constraint is considered satisfied. No need to
  84899. ** search for a matching row in the parent table. */
  84900. if( nIncr<0 ){
  84901. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  84902. }
  84903. for(i=0; i<pFKey->nCol; i++){
  84904. int iReg = aiCol[i] + regData + 1;
  84905. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
  84906. }
  84907. if( isIgnore==0 ){
  84908. if( pIdx==0 ){
  84909. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  84910. ** column of the parent table (table pTab). */
  84911. int iMustBeInt; /* Address of MustBeInt instruction */
  84912. int regTemp = sqlite3GetTempReg(pParse);
  84913. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  84914. ** apply the affinity of the parent key). If this fails, then there
  84915. ** is no matching parent key. Before using MustBeInt, make a copy of
  84916. ** the value. Otherwise, the value inserted into the child key column
  84917. ** will have INTEGER affinity applied to it, which may not be correct. */
  84918. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  84919. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  84920. /* If the parent table is the same as the child table, and we are about
  84921. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  84922. ** then check if the row being inserted matches itself. If so, do not
  84923. ** increment the constraint-counter. */
  84924. if( pTab==pFKey->pFrom && nIncr==1 ){
  84925. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
  84926. }
  84927. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  84928. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
  84929. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  84930. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  84931. sqlite3VdbeJumpHere(v, iMustBeInt);
  84932. sqlite3ReleaseTempReg(pParse, regTemp);
  84933. }else{
  84934. int nCol = pFKey->nCol;
  84935. int regTemp = sqlite3GetTempRange(pParse, nCol);
  84936. int regRec = sqlite3GetTempReg(pParse);
  84937. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  84938. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  84939. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  84940. for(i=0; i<nCol; i++){
  84941. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  84942. }
  84943. /* If the parent table is the same as the child table, and we are about
  84944. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  84945. ** then check if the row being inserted matches itself. If so, do not
  84946. ** increment the constraint-counter.
  84947. **
  84948. ** If any of the parent-key values are NULL, then the row cannot match
  84949. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  84950. ** of the parent-key values are NULL (at this point it is known that
  84951. ** none of the child key values are).
  84952. */
  84953. if( pTab==pFKey->pFrom && nIncr==1 ){
  84954. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  84955. for(i=0; i<nCol; i++){
  84956. int iChild = aiCol[i]+1+regData;
  84957. int iParent = pIdx->aiColumn[i]+1+regData;
  84958. assert( aiCol[i]!=pTab->iPKey );
  84959. if( pIdx->aiColumn[i]==pTab->iPKey ){
  84960. /* The parent key is a composite key that includes the IPK column */
  84961. iParent = regData;
  84962. }
  84963. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
  84964. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  84965. }
  84966. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  84967. }
  84968. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
  84969. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  84970. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
  84971. sqlite3ReleaseTempReg(pParse, regRec);
  84972. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  84973. }
  84974. }
  84975. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  84976. && !pParse->pToplevel
  84977. && !pParse->isMultiWrite
  84978. ){
  84979. /* Special case: If this is an INSERT statement that will insert exactly
  84980. ** one row into the table, raise a constraint immediately instead of
  84981. ** incrementing a counter. This is necessary as the VM code is being
  84982. ** generated for will not open a statement transaction. */
  84983. assert( nIncr==1 );
  84984. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  84985. OE_Abort, "foreign key constraint failed", P4_STATIC
  84986. );
  84987. }else{
  84988. if( nIncr>0 && pFKey->isDeferred==0 ){
  84989. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  84990. }
  84991. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  84992. }
  84993. sqlite3VdbeResolveLabel(v, iOk);
  84994. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  84995. }
  84996. /*
  84997. ** This function is called to generate code executed when a row is deleted
  84998. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  84999. ** deferred, when a row is inserted into the same table. When generating
  85000. ** code for an SQL UPDATE operation, this function may be called twice -
  85001. ** once to "delete" the old row and once to "insert" the new row.
  85002. **
  85003. ** The code generated by this function scans through the rows in the child
  85004. ** table that correspond to the parent table row being deleted or inserted.
  85005. ** For each child row found, one of the following actions is taken:
  85006. **
  85007. ** Operation | FK type | Action taken
  85008. ** --------------------------------------------------------------------------
  85009. ** DELETE immediate Increment the "immediate constraint counter".
  85010. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  85011. ** throw a "foreign key constraint failed" exception.
  85012. **
  85013. ** INSERT immediate Decrement the "immediate constraint counter".
  85014. **
  85015. ** DELETE deferred Increment the "deferred constraint counter".
  85016. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  85017. ** throw a "foreign key constraint failed" exception.
  85018. **
  85019. ** INSERT deferred Decrement the "deferred constraint counter".
  85020. **
  85021. ** These operations are identified in the comment at the top of this file
  85022. ** (fkey.c) as "I.2" and "D.2".
  85023. */
  85024. static void fkScanChildren(
  85025. Parse *pParse, /* Parse context */
  85026. SrcList *pSrc, /* SrcList containing the table to scan */
  85027. Table *pTab,
  85028. Index *pIdx, /* Foreign key index */
  85029. FKey *pFKey, /* Foreign key relationship */
  85030. int *aiCol, /* Map from pIdx cols to child table cols */
  85031. int regData, /* Referenced table data starts here */
  85032. int nIncr /* Amount to increment deferred counter by */
  85033. ){
  85034. sqlite3 *db = pParse->db; /* Database handle */
  85035. int i; /* Iterator variable */
  85036. Expr *pWhere = 0; /* WHERE clause to scan with */
  85037. NameContext sNameContext; /* Context used to resolve WHERE clause */
  85038. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  85039. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  85040. Vdbe *v = sqlite3GetVdbe(pParse);
  85041. assert( !pIdx || pIdx->pTable==pTab );
  85042. if( nIncr<0 ){
  85043. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  85044. }
  85045. /* Create an Expr object representing an SQL expression like:
  85046. **
  85047. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  85048. **
  85049. ** The collation sequence used for the comparison should be that of
  85050. ** the parent key columns. The affinity of the parent key column should
  85051. ** be applied to each child key value before the comparison takes place.
  85052. */
  85053. for(i=0; i<pFKey->nCol; i++){
  85054. Expr *pLeft; /* Value from parent table row */
  85055. Expr *pRight; /* Column ref to child table */
  85056. Expr *pEq; /* Expression (pLeft = pRight) */
  85057. int iCol; /* Index of column in child table */
  85058. const char *zCol; /* Name of column in child table */
  85059. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  85060. if( pLeft ){
  85061. /* Set the collation sequence and affinity of the LHS of each TK_EQ
  85062. ** expression to the parent key column defaults. */
  85063. if( pIdx ){
  85064. Column *pCol;
  85065. const char *zColl;
  85066. iCol = pIdx->aiColumn[i];
  85067. pCol = &pTab->aCol[iCol];
  85068. if( pTab->iPKey==iCol ) iCol = -1;
  85069. pLeft->iTable = regData+iCol+1;
  85070. pLeft->affinity = pCol->affinity;
  85071. zColl = pCol->zColl;
  85072. if( zColl==0 ) zColl = db->pDfltColl->zName;
  85073. pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
  85074. }else{
  85075. pLeft->iTable = regData;
  85076. pLeft->affinity = SQLITE_AFF_INTEGER;
  85077. }
  85078. }
  85079. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  85080. assert( iCol>=0 );
  85081. zCol = pFKey->pFrom->aCol[iCol].zName;
  85082. pRight = sqlite3Expr(db, TK_ID, zCol);
  85083. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  85084. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  85085. }
  85086. /* If the child table is the same as the parent table, and this scan
  85087. ** is taking place as part of a DELETE operation (operation D.2), omit the
  85088. ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
  85089. ** clause, where $rowid is the rowid of the row being deleted. */
  85090. if( pTab==pFKey->pFrom && nIncr>0 ){
  85091. Expr *pEq; /* Expression (pLeft = pRight) */
  85092. Expr *pLeft; /* Value from parent table row */
  85093. Expr *pRight; /* Column ref to child table */
  85094. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  85095. pRight = sqlite3Expr(db, TK_COLUMN, 0);
  85096. if( pLeft && pRight ){
  85097. pLeft->iTable = regData;
  85098. pLeft->affinity = SQLITE_AFF_INTEGER;
  85099. pRight->iTable = pSrc->a[0].iCursor;
  85100. pRight->iColumn = -1;
  85101. }
  85102. pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  85103. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  85104. }
  85105. /* Resolve the references in the WHERE clause. */
  85106. memset(&sNameContext, 0, sizeof(NameContext));
  85107. sNameContext.pSrcList = pSrc;
  85108. sNameContext.pParse = pParse;
  85109. sqlite3ResolveExprNames(&sNameContext, pWhere);
  85110. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  85111. ** clause. If the constraint is not deferred, throw an exception for
  85112. ** each row found. Otherwise, for deferred constraints, increment the
  85113. ** deferred constraint counter by nIncr for each row selected. */
  85114. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  85115. if( nIncr>0 && pFKey->isDeferred==0 ){
  85116. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  85117. }
  85118. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  85119. if( pWInfo ){
  85120. sqlite3WhereEnd(pWInfo);
  85121. }
  85122. /* Clean up the WHERE clause constructed above. */
  85123. sqlite3ExprDelete(db, pWhere);
  85124. if( iFkIfZero ){
  85125. sqlite3VdbeJumpHere(v, iFkIfZero);
  85126. }
  85127. }
  85128. /*
  85129. ** This function returns a pointer to the head of a linked list of FK
  85130. ** constraints for which table pTab is the parent table. For example,
  85131. ** given the following schema:
  85132. **
  85133. ** CREATE TABLE t1(a PRIMARY KEY);
  85134. ** CREATE TABLE t2(b REFERENCES t1(a);
  85135. **
  85136. ** Calling this function with table "t1" as an argument returns a pointer
  85137. ** to the FKey structure representing the foreign key constraint on table
  85138. ** "t2". Calling this function with "t2" as the argument would return a
  85139. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  85140. ** table).
  85141. */
  85142. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  85143. int nName = sqlite3Strlen30(pTab->zName);
  85144. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
  85145. }
  85146. /*
  85147. ** The second argument is a Trigger structure allocated by the
  85148. ** fkActionTrigger() routine. This function deletes the Trigger structure
  85149. ** and all of its sub-components.
  85150. **
  85151. ** The Trigger structure or any of its sub-components may be allocated from
  85152. ** the lookaside buffer belonging to database handle dbMem.
  85153. */
  85154. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  85155. if( p ){
  85156. TriggerStep *pStep = p->step_list;
  85157. sqlite3ExprDelete(dbMem, pStep->pWhere);
  85158. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  85159. sqlite3SelectDelete(dbMem, pStep->pSelect);
  85160. sqlite3ExprDelete(dbMem, p->pWhen);
  85161. sqlite3DbFree(dbMem, p);
  85162. }
  85163. }
  85164. /*
  85165. ** This function is called to generate code that runs when table pTab is
  85166. ** being dropped from the database. The SrcList passed as the second argument
  85167. ** to this function contains a single entry guaranteed to resolve to
  85168. ** table pTab.
  85169. **
  85170. ** Normally, no code is required. However, if either
  85171. **
  85172. ** (a) The table is the parent table of a FK constraint, or
  85173. ** (b) The table is the child table of a deferred FK constraint and it is
  85174. ** determined at runtime that there are outstanding deferred FK
  85175. ** constraint violations in the database,
  85176. **
  85177. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  85178. ** the table from the database. Triggers are disabled while running this
  85179. ** DELETE, but foreign key actions are not.
  85180. */
  85181. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  85182. sqlite3 *db = pParse->db;
  85183. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  85184. int iSkip = 0;
  85185. Vdbe *v = sqlite3GetVdbe(pParse);
  85186. assert( v ); /* VDBE has already been allocated */
  85187. if( sqlite3FkReferences(pTab)==0 ){
  85188. /* Search for a deferred foreign key constraint for which this table
  85189. ** is the child table. If one cannot be found, return without
  85190. ** generating any VDBE code. If one can be found, then jump over
  85191. ** the entire DELETE if there are no outstanding deferred constraints
  85192. ** when this statement is run. */
  85193. FKey *p;
  85194. for(p=pTab->pFKey; p; p=p->pNextFrom){
  85195. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  85196. }
  85197. if( !p ) return;
  85198. iSkip = sqlite3VdbeMakeLabel(v);
  85199. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
  85200. }
  85201. pParse->disableTriggers = 1;
  85202. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  85203. pParse->disableTriggers = 0;
  85204. /* If the DELETE has generated immediate foreign key constraint
  85205. ** violations, halt the VDBE and return an error at this point, before
  85206. ** any modifications to the schema are made. This is because statement
  85207. ** transactions are not able to rollback schema changes.
  85208. **
  85209. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  85210. ** the statement transaction will not be rolled back even if FK
  85211. ** constraints are violated.
  85212. */
  85213. if( (db->flags & SQLITE_DeferFKs)==0 ){
  85214. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  85215. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  85216. OE_Abort, "foreign key constraint failed", P4_STATIC
  85217. );
  85218. }
  85219. if( iSkip ){
  85220. sqlite3VdbeResolveLabel(v, iSkip);
  85221. }
  85222. }
  85223. }
  85224. /*
  85225. ** The second argument points to an FKey object representing a foreign key
  85226. ** for which pTab is the child table. An UPDATE statement against pTab
  85227. ** is currently being processed. For each column of the table that is
  85228. ** actually updated, the corresponding element in the aChange[] array
  85229. ** is zero or greater (if a column is unmodified the corresponding element
  85230. ** is set to -1). If the rowid column is modified by the UPDATE statement
  85231. ** the bChngRowid argument is non-zero.
  85232. **
  85233. ** This function returns true if any of the columns that are part of the
  85234. ** child key for FK constraint *p are modified.
  85235. */
  85236. static int fkChildIsModified(
  85237. Table *pTab, /* Table being updated */
  85238. FKey *p, /* Foreign key for which pTab is the child */
  85239. int *aChange, /* Array indicating modified columns */
  85240. int bChngRowid /* True if rowid is modified by this update */
  85241. ){
  85242. int i;
  85243. for(i=0; i<p->nCol; i++){
  85244. int iChildKey = p->aCol[i].iFrom;
  85245. if( aChange[iChildKey]>=0 ) return 1;
  85246. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  85247. }
  85248. return 0;
  85249. }
  85250. /*
  85251. ** The second argument points to an FKey object representing a foreign key
  85252. ** for which pTab is the parent table. An UPDATE statement against pTab
  85253. ** is currently being processed. For each column of the table that is
  85254. ** actually updated, the corresponding element in the aChange[] array
  85255. ** is zero or greater (if a column is unmodified the corresponding element
  85256. ** is set to -1). If the rowid column is modified by the UPDATE statement
  85257. ** the bChngRowid argument is non-zero.
  85258. **
  85259. ** This function returns true if any of the columns that are part of the
  85260. ** parent key for FK constraint *p are modified.
  85261. */
  85262. static int fkParentIsModified(
  85263. Table *pTab,
  85264. FKey *p,
  85265. int *aChange,
  85266. int bChngRowid
  85267. ){
  85268. int i;
  85269. for(i=0; i<p->nCol; i++){
  85270. char *zKey = p->aCol[i].zCol;
  85271. int iKey;
  85272. for(iKey=0; iKey<pTab->nCol; iKey++){
  85273. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  85274. Column *pCol = &pTab->aCol[iKey];
  85275. if( zKey ){
  85276. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  85277. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  85278. return 1;
  85279. }
  85280. }
  85281. }
  85282. }
  85283. return 0;
  85284. }
  85285. /*
  85286. ** This function is called when inserting, deleting or updating a row of
  85287. ** table pTab to generate VDBE code to perform foreign key constraint
  85288. ** processing for the operation.
  85289. **
  85290. ** For a DELETE operation, parameter regOld is passed the index of the
  85291. ** first register in an array of (pTab->nCol+1) registers containing the
  85292. ** rowid of the row being deleted, followed by each of the column values
  85293. ** of the row being deleted, from left to right. Parameter regNew is passed
  85294. ** zero in this case.
  85295. **
  85296. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  85297. ** first register of an array of (pTab->nCol+1) registers containing the new
  85298. ** row data.
  85299. **
  85300. ** For an UPDATE operation, this function is called twice. Once before
  85301. ** the original record is deleted from the table using the calling convention
  85302. ** described for DELETE. Then again after the original record is deleted
  85303. ** but before the new record is inserted using the INSERT convention.
  85304. */
  85305. SQLITE_PRIVATE void sqlite3FkCheck(
  85306. Parse *pParse, /* Parse context */
  85307. Table *pTab, /* Row is being deleted from this table */
  85308. int regOld, /* Previous row data is stored here */
  85309. int regNew, /* New row data is stored here */
  85310. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  85311. int bChngRowid /* True if rowid is UPDATEd */
  85312. ){
  85313. sqlite3 *db = pParse->db; /* Database handle */
  85314. FKey *pFKey; /* Used to iterate through FKs */
  85315. int iDb; /* Index of database containing pTab */
  85316. const char *zDb; /* Name of database containing pTab */
  85317. int isIgnoreErrors = pParse->disableTriggers;
  85318. /* Exactly one of regOld and regNew should be non-zero. */
  85319. assert( (regOld==0)!=(regNew==0) );
  85320. /* If foreign-keys are disabled, this function is a no-op. */
  85321. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  85322. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85323. zDb = db->aDb[iDb].zName;
  85324. /* Loop through all the foreign key constraints for which pTab is the
  85325. ** child table (the table that the foreign key definition is part of). */
  85326. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  85327. Table *pTo; /* Parent table of foreign key pFKey */
  85328. Index *pIdx = 0; /* Index on key columns in pTo */
  85329. int *aiFree = 0;
  85330. int *aiCol;
  85331. int iCol;
  85332. int i;
  85333. int isIgnore = 0;
  85334. if( aChange
  85335. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  85336. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  85337. ){
  85338. continue;
  85339. }
  85340. /* Find the parent table of this foreign key. Also find a unique index
  85341. ** on the parent key columns in the parent table. If either of these
  85342. ** schema items cannot be located, set an error in pParse and return
  85343. ** early. */
  85344. if( pParse->disableTriggers ){
  85345. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  85346. }else{
  85347. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  85348. }
  85349. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  85350. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  85351. if( !isIgnoreErrors || db->mallocFailed ) return;
  85352. if( pTo==0 ){
  85353. /* If isIgnoreErrors is true, then a table is being dropped. In this
  85354. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  85355. ** before actually dropping it in order to check FK constraints.
  85356. ** If the parent table of an FK constraint on the current table is
  85357. ** missing, behave as if it is empty. i.e. decrement the relevant
  85358. ** FK counter for each row of the current table with non-NULL keys.
  85359. */
  85360. Vdbe *v = sqlite3GetVdbe(pParse);
  85361. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  85362. for(i=0; i<pFKey->nCol; i++){
  85363. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  85364. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
  85365. }
  85366. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  85367. }
  85368. continue;
  85369. }
  85370. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  85371. if( aiFree ){
  85372. aiCol = aiFree;
  85373. }else{
  85374. iCol = pFKey->aCol[0].iFrom;
  85375. aiCol = &iCol;
  85376. }
  85377. for(i=0; i<pFKey->nCol; i++){
  85378. if( aiCol[i]==pTab->iPKey ){
  85379. aiCol[i] = -1;
  85380. }
  85381. #ifndef SQLITE_OMIT_AUTHORIZATION
  85382. /* Request permission to read the parent key columns. If the
  85383. ** authorization callback returns SQLITE_IGNORE, behave as if any
  85384. ** values read from the parent table are NULL. */
  85385. if( db->xAuth ){
  85386. int rcauth;
  85387. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  85388. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  85389. isIgnore = (rcauth==SQLITE_IGNORE);
  85390. }
  85391. #endif
  85392. }
  85393. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  85394. ** a cursor to use to search the unique index on the parent key columns
  85395. ** in the parent table. */
  85396. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  85397. pParse->nTab++;
  85398. if( regOld!=0 ){
  85399. /* A row is being removed from the child table. Search for the parent.
  85400. ** If the parent does not exist, removing the child row resolves an
  85401. ** outstanding foreign key constraint violation. */
  85402. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
  85403. }
  85404. if( regNew!=0 ){
  85405. /* A row is being added to the child table. If a parent row cannot
  85406. ** be found, adding the child row has violated the FK constraint. */
  85407. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
  85408. }
  85409. sqlite3DbFree(db, aiFree);
  85410. }
  85411. /* Loop through all the foreign key constraints that refer to this table */
  85412. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  85413. Index *pIdx = 0; /* Foreign key index for pFKey */
  85414. SrcList *pSrc;
  85415. int *aiCol = 0;
  85416. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  85417. continue;
  85418. }
  85419. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  85420. && !pParse->pToplevel && !pParse->isMultiWrite
  85421. ){
  85422. assert( regOld==0 && regNew!=0 );
  85423. /* Inserting a single row into a parent table cannot cause an immediate
  85424. ** foreign key violation. So do nothing in this case. */
  85425. continue;
  85426. }
  85427. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  85428. if( !isIgnoreErrors || db->mallocFailed ) return;
  85429. continue;
  85430. }
  85431. assert( aiCol || pFKey->nCol==1 );
  85432. /* Create a SrcList structure containing a single table (the table
  85433. ** the foreign key that refers to this table is attached to). This
  85434. ** is required for the sqlite3WhereXXX() interface. */
  85435. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  85436. if( pSrc ){
  85437. struct SrcList_item *pItem = pSrc->a;
  85438. pItem->pTab = pFKey->pFrom;
  85439. pItem->zName = pFKey->pFrom->zName;
  85440. pItem->pTab->nRef++;
  85441. pItem->iCursor = pParse->nTab++;
  85442. if( regNew!=0 ){
  85443. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  85444. }
  85445. if( regOld!=0 ){
  85446. /* If there is a RESTRICT action configured for the current operation
  85447. ** on the parent table of this FK, then throw an exception
  85448. ** immediately if the FK constraint is violated, even if this is a
  85449. ** deferred trigger. That's what RESTRICT means. To defer checking
  85450. ** the constraint, the FK should specify NO ACTION (represented
  85451. ** using OE_None). NO ACTION is the default. */
  85452. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  85453. }
  85454. pItem->zName = 0;
  85455. sqlite3SrcListDelete(db, pSrc);
  85456. }
  85457. sqlite3DbFree(db, aiCol);
  85458. }
  85459. }
  85460. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  85461. /*
  85462. ** This function is called before generating code to update or delete a
  85463. ** row contained in table pTab.
  85464. */
  85465. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  85466. Parse *pParse, /* Parse context */
  85467. Table *pTab /* Table being modified */
  85468. ){
  85469. u32 mask = 0;
  85470. if( pParse->db->flags&SQLITE_ForeignKeys ){
  85471. FKey *p;
  85472. int i;
  85473. for(p=pTab->pFKey; p; p=p->pNextFrom){
  85474. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  85475. }
  85476. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  85477. Index *pIdx = 0;
  85478. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  85479. if( pIdx ){
  85480. for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  85481. }
  85482. }
  85483. }
  85484. return mask;
  85485. }
  85486. /*
  85487. ** This function is called before generating code to update or delete a
  85488. ** row contained in table pTab. If the operation is a DELETE, then
  85489. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  85490. ** to an array of size N, where N is the number of columns in table pTab.
  85491. ** If the i'th column is not modified by the UPDATE, then the corresponding
  85492. ** entry in the aChange[] array is set to -1. If the column is modified,
  85493. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  85494. ** UPDATE statement modifies the rowid fields of the table.
  85495. **
  85496. ** If any foreign key processing will be required, this function returns
  85497. ** true. If there is no foreign key related processing, this function
  85498. ** returns false.
  85499. */
  85500. SQLITE_PRIVATE int sqlite3FkRequired(
  85501. Parse *pParse, /* Parse context */
  85502. Table *pTab, /* Table being modified */
  85503. int *aChange, /* Non-NULL for UPDATE operations */
  85504. int chngRowid /* True for UPDATE that affects rowid */
  85505. ){
  85506. if( pParse->db->flags&SQLITE_ForeignKeys ){
  85507. if( !aChange ){
  85508. /* A DELETE operation. Foreign key processing is required if the
  85509. ** table in question is either the child or parent table for any
  85510. ** foreign key constraint. */
  85511. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  85512. }else{
  85513. /* This is an UPDATE. Foreign key processing is only required if the
  85514. ** operation modifies one or more child or parent key columns. */
  85515. FKey *p;
  85516. /* Check if any child key columns are being modified. */
  85517. for(p=pTab->pFKey; p; p=p->pNextFrom){
  85518. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  85519. }
  85520. /* Check if any parent key columns are being modified. */
  85521. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  85522. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  85523. }
  85524. }
  85525. }
  85526. return 0;
  85527. }
  85528. /*
  85529. ** This function is called when an UPDATE or DELETE operation is being
  85530. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  85531. ** If the current operation is an UPDATE, then the pChanges parameter is
  85532. ** passed a pointer to the list of columns being modified. If it is a
  85533. ** DELETE, pChanges is passed a NULL pointer.
  85534. **
  85535. ** It returns a pointer to a Trigger structure containing a trigger
  85536. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  85537. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  85538. ** returned (these actions require no special handling by the triggers
  85539. ** sub-system, code for them is created by fkScanChildren()).
  85540. **
  85541. ** For example, if pFKey is the foreign key and pTab is table "p" in
  85542. ** the following schema:
  85543. **
  85544. ** CREATE TABLE p(pk PRIMARY KEY);
  85545. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  85546. **
  85547. ** then the returned trigger structure is equivalent to:
  85548. **
  85549. ** CREATE TRIGGER ... DELETE ON p BEGIN
  85550. ** DELETE FROM c WHERE ck = old.pk;
  85551. ** END;
  85552. **
  85553. ** The returned pointer is cached as part of the foreign key object. It
  85554. ** is eventually freed along with the rest of the foreign key object by
  85555. ** sqlite3FkDelete().
  85556. */
  85557. static Trigger *fkActionTrigger(
  85558. Parse *pParse, /* Parse context */
  85559. Table *pTab, /* Table being updated or deleted from */
  85560. FKey *pFKey, /* Foreign key to get action for */
  85561. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  85562. ){
  85563. sqlite3 *db = pParse->db; /* Database handle */
  85564. int action; /* One of OE_None, OE_Cascade etc. */
  85565. Trigger *pTrigger; /* Trigger definition to return */
  85566. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  85567. action = pFKey->aAction[iAction];
  85568. pTrigger = pFKey->apTrigger[iAction];
  85569. if( action!=OE_None && !pTrigger ){
  85570. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  85571. char const *zFrom; /* Name of child table */
  85572. int nFrom; /* Length in bytes of zFrom */
  85573. Index *pIdx = 0; /* Parent key index for this FK */
  85574. int *aiCol = 0; /* child table cols -> parent key cols */
  85575. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  85576. Expr *pWhere = 0; /* WHERE clause of trigger step */
  85577. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  85578. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  85579. int i; /* Iterator variable */
  85580. Expr *pWhen = 0; /* WHEN clause for the trigger */
  85581. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  85582. assert( aiCol || pFKey->nCol==1 );
  85583. for(i=0; i<pFKey->nCol; i++){
  85584. Token tOld = { "old", 3 }; /* Literal "old" token */
  85585. Token tNew = { "new", 3 }; /* Literal "new" token */
  85586. Token tFromCol; /* Name of column in child table */
  85587. Token tToCol; /* Name of column in parent table */
  85588. int iFromCol; /* Idx of column in child table */
  85589. Expr *pEq; /* tFromCol = OLD.tToCol */
  85590. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  85591. assert( iFromCol>=0 );
  85592. tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
  85593. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  85594. tToCol.n = sqlite3Strlen30(tToCol.z);
  85595. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  85596. /* Create the expression "OLD.zToCol = zFromCol". It is important
  85597. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  85598. ** that the affinity and collation sequence associated with the
  85599. ** parent table are used for the comparison. */
  85600. pEq = sqlite3PExpr(pParse, TK_EQ,
  85601. sqlite3PExpr(pParse, TK_DOT,
  85602. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  85603. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  85604. , 0),
  85605. sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
  85606. , 0);
  85607. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  85608. /* For ON UPDATE, construct the next term of the WHEN clause.
  85609. ** The final WHEN clause will be like this:
  85610. **
  85611. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  85612. */
  85613. if( pChanges ){
  85614. pEq = sqlite3PExpr(pParse, TK_IS,
  85615. sqlite3PExpr(pParse, TK_DOT,
  85616. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  85617. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  85618. 0),
  85619. sqlite3PExpr(pParse, TK_DOT,
  85620. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  85621. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  85622. 0),
  85623. 0);
  85624. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  85625. }
  85626. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  85627. Expr *pNew;
  85628. if( action==OE_Cascade ){
  85629. pNew = sqlite3PExpr(pParse, TK_DOT,
  85630. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  85631. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  85632. , 0);
  85633. }else if( action==OE_SetDflt ){
  85634. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  85635. if( pDflt ){
  85636. pNew = sqlite3ExprDup(db, pDflt, 0);
  85637. }else{
  85638. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  85639. }
  85640. }else{
  85641. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  85642. }
  85643. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  85644. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  85645. }
  85646. }
  85647. sqlite3DbFree(db, aiCol);
  85648. zFrom = pFKey->pFrom->zName;
  85649. nFrom = sqlite3Strlen30(zFrom);
  85650. if( action==OE_Restrict ){
  85651. Token tFrom;
  85652. Expr *pRaise;
  85653. tFrom.z = zFrom;
  85654. tFrom.n = nFrom;
  85655. pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
  85656. if( pRaise ){
  85657. pRaise->affinity = OE_Abort;
  85658. }
  85659. pSelect = sqlite3SelectNew(pParse,
  85660. sqlite3ExprListAppend(pParse, 0, pRaise),
  85661. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  85662. pWhere,
  85663. 0, 0, 0, 0, 0, 0
  85664. );
  85665. pWhere = 0;
  85666. }
  85667. /* Disable lookaside memory allocation */
  85668. enableLookaside = db->lookaside.bEnabled;
  85669. db->lookaside.bEnabled = 0;
  85670. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  85671. sizeof(Trigger) + /* struct Trigger */
  85672. sizeof(TriggerStep) + /* Single step in trigger program */
  85673. nFrom + 1 /* Space for pStep->target.z */
  85674. );
  85675. if( pTrigger ){
  85676. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  85677. pStep->target.z = (char *)&pStep[1];
  85678. pStep->target.n = nFrom;
  85679. memcpy((char *)pStep->target.z, zFrom, nFrom);
  85680. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  85681. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  85682. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  85683. if( pWhen ){
  85684. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  85685. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  85686. }
  85687. }
  85688. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  85689. db->lookaside.bEnabled = enableLookaside;
  85690. sqlite3ExprDelete(db, pWhere);
  85691. sqlite3ExprDelete(db, pWhen);
  85692. sqlite3ExprListDelete(db, pList);
  85693. sqlite3SelectDelete(db, pSelect);
  85694. if( db->mallocFailed==1 ){
  85695. fkTriggerDelete(db, pTrigger);
  85696. return 0;
  85697. }
  85698. assert( pStep!=0 );
  85699. switch( action ){
  85700. case OE_Restrict:
  85701. pStep->op = TK_SELECT;
  85702. break;
  85703. case OE_Cascade:
  85704. if( !pChanges ){
  85705. pStep->op = TK_DELETE;
  85706. break;
  85707. }
  85708. default:
  85709. pStep->op = TK_UPDATE;
  85710. }
  85711. pStep->pTrig = pTrigger;
  85712. pTrigger->pSchema = pTab->pSchema;
  85713. pTrigger->pTabSchema = pTab->pSchema;
  85714. pFKey->apTrigger[iAction] = pTrigger;
  85715. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  85716. }
  85717. return pTrigger;
  85718. }
  85719. /*
  85720. ** This function is called when deleting or updating a row to implement
  85721. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  85722. */
  85723. SQLITE_PRIVATE void sqlite3FkActions(
  85724. Parse *pParse, /* Parse context */
  85725. Table *pTab, /* Table being updated or deleted from */
  85726. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  85727. int regOld, /* Address of array containing old row */
  85728. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  85729. int bChngRowid /* True if rowid is UPDATEd */
  85730. ){
  85731. /* If foreign-key support is enabled, iterate through all FKs that
  85732. ** refer to table pTab. If there is an action associated with the FK
  85733. ** for this operation (either update or delete), invoke the associated
  85734. ** trigger sub-program. */
  85735. if( pParse->db->flags&SQLITE_ForeignKeys ){
  85736. FKey *pFKey; /* Iterator variable */
  85737. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  85738. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  85739. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  85740. if( pAct ){
  85741. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  85742. }
  85743. }
  85744. }
  85745. }
  85746. }
  85747. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  85748. /*
  85749. ** Free all memory associated with foreign key definitions attached to
  85750. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  85751. ** hash table.
  85752. */
  85753. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  85754. FKey *pFKey; /* Iterator variable */
  85755. FKey *pNext; /* Copy of pFKey->pNextFrom */
  85756. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  85757. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  85758. /* Remove the FK from the fkeyHash hash table. */
  85759. if( !db || db->pnBytesFreed==0 ){
  85760. if( pFKey->pPrevTo ){
  85761. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  85762. }else{
  85763. void *p = (void *)pFKey->pNextTo;
  85764. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  85765. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
  85766. }
  85767. if( pFKey->pNextTo ){
  85768. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  85769. }
  85770. }
  85771. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  85772. ** classified as either immediate or deferred.
  85773. */
  85774. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  85775. /* Delete any triggers created to implement actions for this FK. */
  85776. #ifndef SQLITE_OMIT_TRIGGER
  85777. fkTriggerDelete(db, pFKey->apTrigger[0]);
  85778. fkTriggerDelete(db, pFKey->apTrigger[1]);
  85779. #endif
  85780. pNext = pFKey->pNextFrom;
  85781. sqlite3DbFree(db, pFKey);
  85782. }
  85783. }
  85784. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  85785. /************** End of fkey.c ************************************************/
  85786. /************** Begin file insert.c ******************************************/
  85787. /*
  85788. ** 2001 September 15
  85789. **
  85790. ** The author disclaims copyright to this source code. In place of
  85791. ** a legal notice, here is a blessing:
  85792. **
  85793. ** May you do good and not evil.
  85794. ** May you find forgiveness for yourself and forgive others.
  85795. ** May you share freely, never taking more than you give.
  85796. **
  85797. *************************************************************************
  85798. ** This file contains C code routines that are called by the parser
  85799. ** to handle INSERT statements in SQLite.
  85800. */
  85801. /*
  85802. ** Generate code that will open a table for reading.
  85803. */
  85804. SQLITE_PRIVATE void sqlite3OpenTable(
  85805. Parse *p, /* Generate code into this VDBE */
  85806. int iCur, /* The cursor number of the table */
  85807. int iDb, /* The database index in sqlite3.aDb[] */
  85808. Table *pTab, /* The table to be opened */
  85809. int opcode /* OP_OpenRead or OP_OpenWrite */
  85810. ){
  85811. Vdbe *v;
  85812. assert( !IsVirtual(pTab) );
  85813. v = sqlite3GetVdbe(p);
  85814. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  85815. sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
  85816. sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
  85817. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
  85818. VdbeComment((v, "%s", pTab->zName));
  85819. }
  85820. /*
  85821. ** Return a pointer to the column affinity string associated with index
  85822. ** pIdx. A column affinity string has one character for each column in
  85823. ** the table, according to the affinity of the column:
  85824. **
  85825. ** Character Column affinity
  85826. ** ------------------------------
  85827. ** 'a' TEXT
  85828. ** 'b' NONE
  85829. ** 'c' NUMERIC
  85830. ** 'd' INTEGER
  85831. ** 'e' REAL
  85832. **
  85833. ** An extra 'd' is appended to the end of the string to cover the
  85834. ** rowid that appears as the last column in every index.
  85835. **
  85836. ** Memory for the buffer containing the column index affinity string
  85837. ** is managed along with the rest of the Index structure. It will be
  85838. ** released when sqlite3DeleteIndex() is called.
  85839. */
  85840. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  85841. if( !pIdx->zColAff ){
  85842. /* The first time a column affinity string for a particular index is
  85843. ** required, it is allocated and populated here. It is then stored as
  85844. ** a member of the Index structure for subsequent use.
  85845. **
  85846. ** The column affinity string will eventually be deleted by
  85847. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  85848. ** up.
  85849. */
  85850. int n;
  85851. Table *pTab = pIdx->pTable;
  85852. sqlite3 *db = sqlite3VdbeDb(v);
  85853. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
  85854. if( !pIdx->zColAff ){
  85855. db->mallocFailed = 1;
  85856. return 0;
  85857. }
  85858. for(n=0; n<pIdx->nColumn; n++){
  85859. pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
  85860. }
  85861. pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
  85862. pIdx->zColAff[n] = 0;
  85863. }
  85864. return pIdx->zColAff;
  85865. }
  85866. /*
  85867. ** Set P4 of the most recently inserted opcode to a column affinity
  85868. ** string for table pTab. A column affinity string has one character
  85869. ** for each column indexed by the index, according to the affinity of the
  85870. ** column:
  85871. **
  85872. ** Character Column affinity
  85873. ** ------------------------------
  85874. ** 'a' TEXT
  85875. ** 'b' NONE
  85876. ** 'c' NUMERIC
  85877. ** 'd' INTEGER
  85878. ** 'e' REAL
  85879. */
  85880. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  85881. /* The first time a column affinity string for a particular table
  85882. ** is required, it is allocated and populated here. It is then
  85883. ** stored as a member of the Table structure for subsequent use.
  85884. **
  85885. ** The column affinity string will eventually be deleted by
  85886. ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  85887. */
  85888. if( !pTab->zColAff ){
  85889. char *zColAff;
  85890. int i;
  85891. sqlite3 *db = sqlite3VdbeDb(v);
  85892. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  85893. if( !zColAff ){
  85894. db->mallocFailed = 1;
  85895. return;
  85896. }
  85897. for(i=0; i<pTab->nCol; i++){
  85898. zColAff[i] = pTab->aCol[i].affinity;
  85899. }
  85900. zColAff[pTab->nCol] = '\0';
  85901. pTab->zColAff = zColAff;
  85902. }
  85903. sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
  85904. }
  85905. /*
  85906. ** Return non-zero if the table pTab in database iDb or any of its indices
  85907. ** have been opened at any point in the VDBE program beginning at location
  85908. ** iStartAddr throught the end of the program. This is used to see if
  85909. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  85910. ** run without using temporary table for the results of the SELECT.
  85911. */
  85912. static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
  85913. Vdbe *v = sqlite3GetVdbe(p);
  85914. int i;
  85915. int iEnd = sqlite3VdbeCurrentAddr(v);
  85916. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85917. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  85918. #endif
  85919. for(i=iStartAddr; i<iEnd; i++){
  85920. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  85921. assert( pOp!=0 );
  85922. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  85923. Index *pIndex;
  85924. int tnum = pOp->p2;
  85925. if( tnum==pTab->tnum ){
  85926. return 1;
  85927. }
  85928. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  85929. if( tnum==pIndex->tnum ){
  85930. return 1;
  85931. }
  85932. }
  85933. }
  85934. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85935. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  85936. assert( pOp->p4.pVtab!=0 );
  85937. assert( pOp->p4type==P4_VTAB );
  85938. return 1;
  85939. }
  85940. #endif
  85941. }
  85942. return 0;
  85943. }
  85944. #ifndef SQLITE_OMIT_AUTOINCREMENT
  85945. /*
  85946. ** Locate or create an AutoincInfo structure associated with table pTab
  85947. ** which is in database iDb. Return the register number for the register
  85948. ** that holds the maximum rowid.
  85949. **
  85950. ** There is at most one AutoincInfo structure per table even if the
  85951. ** same table is autoincremented multiple times due to inserts within
  85952. ** triggers. A new AutoincInfo structure is created if this is the
  85953. ** first use of table pTab. On 2nd and subsequent uses, the original
  85954. ** AutoincInfo structure is used.
  85955. **
  85956. ** Three memory locations are allocated:
  85957. **
  85958. ** (1) Register to hold the name of the pTab table.
  85959. ** (2) Register to hold the maximum ROWID of pTab.
  85960. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  85961. **
  85962. ** The 2nd register is the one that is returned. That is all the
  85963. ** insert routine needs to know about.
  85964. */
  85965. static int autoIncBegin(
  85966. Parse *pParse, /* Parsing context */
  85967. int iDb, /* Index of the database holding pTab */
  85968. Table *pTab /* The table we are writing to */
  85969. ){
  85970. int memId = 0; /* Register holding maximum rowid */
  85971. if( pTab->tabFlags & TF_Autoincrement ){
  85972. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  85973. AutoincInfo *pInfo;
  85974. pInfo = pToplevel->pAinc;
  85975. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  85976. if( pInfo==0 ){
  85977. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  85978. if( pInfo==0 ) return 0;
  85979. pInfo->pNext = pToplevel->pAinc;
  85980. pToplevel->pAinc = pInfo;
  85981. pInfo->pTab = pTab;
  85982. pInfo->iDb = iDb;
  85983. pToplevel->nMem++; /* Register to hold name of table */
  85984. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  85985. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  85986. }
  85987. memId = pInfo->regCtr;
  85988. }
  85989. return memId;
  85990. }
  85991. /*
  85992. ** This routine generates code that will initialize all of the
  85993. ** register used by the autoincrement tracker.
  85994. */
  85995. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  85996. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  85997. sqlite3 *db = pParse->db; /* The database connection */
  85998. Db *pDb; /* Database only autoinc table */
  85999. int memId; /* Register holding max rowid */
  86000. int addr; /* A VDBE address */
  86001. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  86002. /* This routine is never called during trigger-generation. It is
  86003. ** only called from the top-level */
  86004. assert( pParse->pTriggerTab==0 );
  86005. assert( pParse==sqlite3ParseToplevel(pParse) );
  86006. assert( v ); /* We failed long ago if this is not so */
  86007. for(p = pParse->pAinc; p; p = p->pNext){
  86008. pDb = &db->aDb[p->iDb];
  86009. memId = p->regCtr;
  86010. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  86011. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  86012. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  86013. addr = sqlite3VdbeCurrentAddr(v);
  86014. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  86015. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
  86016. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  86017. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
  86018. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  86019. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  86020. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  86021. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  86022. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
  86023. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  86024. sqlite3VdbeAddOp0(v, OP_Close);
  86025. }
  86026. }
  86027. /*
  86028. ** Update the maximum rowid for an autoincrement calculation.
  86029. **
  86030. ** This routine should be called when the top of the stack holds a
  86031. ** new rowid that is about to be inserted. If that new rowid is
  86032. ** larger than the maximum rowid in the memId memory cell, then the
  86033. ** memory cell is updated. The stack is unchanged.
  86034. */
  86035. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  86036. if( memId>0 ){
  86037. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  86038. }
  86039. }
  86040. /*
  86041. ** This routine generates the code needed to write autoincrement
  86042. ** maximum rowid values back into the sqlite_sequence register.
  86043. ** Every statement that might do an INSERT into an autoincrement
  86044. ** table (either directly or through triggers) needs to call this
  86045. ** routine just before the "exit" code.
  86046. */
  86047. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  86048. AutoincInfo *p;
  86049. Vdbe *v = pParse->pVdbe;
  86050. sqlite3 *db = pParse->db;
  86051. assert( v );
  86052. for(p = pParse->pAinc; p; p = p->pNext){
  86053. Db *pDb = &db->aDb[p->iDb];
  86054. int j1, j2, j3, j4, j5;
  86055. int iRec;
  86056. int memId = p->regCtr;
  86057. iRec = sqlite3GetTempReg(pParse);
  86058. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  86059. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  86060. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
  86061. j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
  86062. j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
  86063. j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
  86064. sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
  86065. sqlite3VdbeJumpHere(v, j2);
  86066. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  86067. j5 = sqlite3VdbeAddOp0(v, OP_Goto);
  86068. sqlite3VdbeJumpHere(v, j4);
  86069. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  86070. sqlite3VdbeJumpHere(v, j1);
  86071. sqlite3VdbeJumpHere(v, j5);
  86072. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  86073. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  86074. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  86075. sqlite3VdbeAddOp0(v, OP_Close);
  86076. sqlite3ReleaseTempReg(pParse, iRec);
  86077. }
  86078. }
  86079. #else
  86080. /*
  86081. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  86082. ** above are all no-ops
  86083. */
  86084. # define autoIncBegin(A,B,C) (0)
  86085. # define autoIncStep(A,B,C)
  86086. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  86087. /*
  86088. ** Generate code for a co-routine that will evaluate a subquery one
  86089. ** row at a time.
  86090. **
  86091. ** The pSelect parameter is the subquery that the co-routine will evaluation.
  86092. ** Information about the location of co-routine and the registers it will use
  86093. ** is returned by filling in the pDest object.
  86094. **
  86095. ** Registers are allocated as follows:
  86096. **
  86097. ** pDest->iSDParm The register holding the next entry-point of the
  86098. ** co-routine. Run the co-routine to its next breakpoint
  86099. ** by calling "OP_Yield $X" where $X is pDest->iSDParm.
  86100. **
  86101. ** pDest->iSDParm+1 The register holding the "completed" flag for the
  86102. ** co-routine. This register is 0 if the previous Yield
  86103. ** generated a new result row, or 1 if the subquery
  86104. ** has completed. If the Yield is called again
  86105. ** after this register becomes 1, then the VDBE will
  86106. ** halt with an SQLITE_INTERNAL error.
  86107. **
  86108. ** pDest->iSdst First result register.
  86109. **
  86110. ** pDest->nSdst Number of result registers.
  86111. **
  86112. ** This routine handles all of the register allocation and fills in the
  86113. ** pDest structure appropriately.
  86114. **
  86115. ** Here is a schematic of the generated code assuming that X is the
  86116. ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
  86117. ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
  86118. ** registers that hold the result set, reg[pDest->iSdst] through
  86119. ** reg[pDest->iSdst+pDest->nSdst-1]:
  86120. **
  86121. ** X <- A
  86122. ** EOF <- 0
  86123. ** goto B
  86124. ** A: setup for the SELECT
  86125. ** loop rows in the SELECT
  86126. ** load results into registers R..S
  86127. ** yield X
  86128. ** end loop
  86129. ** cleanup after the SELECT
  86130. ** EOF <- 1
  86131. ** yield X
  86132. ** halt-error
  86133. ** B:
  86134. **
  86135. ** To use this subroutine, the caller generates code as follows:
  86136. **
  86137. ** [ Co-routine generated by this subroutine, shown above ]
  86138. ** S: yield X
  86139. ** if EOF goto E
  86140. ** if skip this row, goto C
  86141. ** if terminate loop, goto E
  86142. ** deal with this row
  86143. ** C: goto S
  86144. ** E:
  86145. */
  86146. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
  86147. int regYield; /* Register holding co-routine entry-point */
  86148. int regEof; /* Register holding co-routine completion flag */
  86149. int addrTop; /* Top of the co-routine */
  86150. int j1; /* Jump instruction */
  86151. int rc; /* Result code */
  86152. Vdbe *v; /* VDBE under construction */
  86153. regYield = ++pParse->nMem;
  86154. regEof = ++pParse->nMem;
  86155. v = sqlite3GetVdbe(pParse);
  86156. addrTop = sqlite3VdbeCurrentAddr(v);
  86157. sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
  86158. VdbeComment((v, "Co-routine entry point"));
  86159. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
  86160. VdbeComment((v, "Co-routine completion flag"));
  86161. sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
  86162. j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  86163. rc = sqlite3Select(pParse, pSelect, pDest);
  86164. assert( pParse->nErr==0 || rc );
  86165. if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
  86166. if( rc ) return rc;
  86167. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
  86168. sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */
  86169. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
  86170. VdbeComment((v, "End of coroutine"));
  86171. sqlite3VdbeJumpHere(v, j1); /* label B: */
  86172. return rc;
  86173. }
  86174. /* Forward declaration */
  86175. static int xferOptimization(
  86176. Parse *pParse, /* Parser context */
  86177. Table *pDest, /* The table we are inserting into */
  86178. Select *pSelect, /* A SELECT statement to use as the data source */
  86179. int onError, /* How to handle constraint errors */
  86180. int iDbDest /* The database of pDest */
  86181. );
  86182. /*
  86183. ** This routine is call to handle SQL of the following forms:
  86184. **
  86185. ** insert into TABLE (IDLIST) values(EXPRLIST)
  86186. ** insert into TABLE (IDLIST) select
  86187. **
  86188. ** The IDLIST following the table name is always optional. If omitted,
  86189. ** then a list of all columns for the table is substituted. The IDLIST
  86190. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  86191. **
  86192. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  86193. ** statement above, and pSelect is NULL. For the second form, pList is
  86194. ** NULL and pSelect is a pointer to the select statement used to generate
  86195. ** data for the insert.
  86196. **
  86197. ** The code generated follows one of four templates. For a simple
  86198. ** select with data coming from a VALUES clause, the code executes
  86199. ** once straight down through. Pseudo-code follows (we call this
  86200. ** the "1st template"):
  86201. **
  86202. ** open write cursor to <table> and its indices
  86203. ** puts VALUES clause expressions onto the stack
  86204. ** write the resulting record into <table>
  86205. ** cleanup
  86206. **
  86207. ** The three remaining templates assume the statement is of the form
  86208. **
  86209. ** INSERT INTO <table> SELECT ...
  86210. **
  86211. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  86212. ** in other words if the SELECT pulls all columns from a single table
  86213. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  86214. ** if <table2> and <table1> are distinct tables but have identical
  86215. ** schemas, including all the same indices, then a special optimization
  86216. ** is invoked that copies raw records from <table2> over to <table1>.
  86217. ** See the xferOptimization() function for the implementation of this
  86218. ** template. This is the 2nd template.
  86219. **
  86220. ** open a write cursor to <table>
  86221. ** open read cursor on <table2>
  86222. ** transfer all records in <table2> over to <table>
  86223. ** close cursors
  86224. ** foreach index on <table>
  86225. ** open a write cursor on the <table> index
  86226. ** open a read cursor on the corresponding <table2> index
  86227. ** transfer all records from the read to the write cursors
  86228. ** close cursors
  86229. ** end foreach
  86230. **
  86231. ** The 3rd template is for when the second template does not apply
  86232. ** and the SELECT clause does not read from <table> at any time.
  86233. ** The generated code follows this template:
  86234. **
  86235. ** EOF <- 0
  86236. ** X <- A
  86237. ** goto B
  86238. ** A: setup for the SELECT
  86239. ** loop over the rows in the SELECT
  86240. ** load values into registers R..R+n
  86241. ** yield X
  86242. ** end loop
  86243. ** cleanup after the SELECT
  86244. ** EOF <- 1
  86245. ** yield X
  86246. ** goto A
  86247. ** B: open write cursor to <table> and its indices
  86248. ** C: yield X
  86249. ** if EOF goto D
  86250. ** insert the select result into <table> from R..R+n
  86251. ** goto C
  86252. ** D: cleanup
  86253. **
  86254. ** The 4th template is used if the insert statement takes its
  86255. ** values from a SELECT but the data is being inserted into a table
  86256. ** that is also read as part of the SELECT. In the third form,
  86257. ** we have to use a intermediate table to store the results of
  86258. ** the select. The template is like this:
  86259. **
  86260. ** EOF <- 0
  86261. ** X <- A
  86262. ** goto B
  86263. ** A: setup for the SELECT
  86264. ** loop over the tables in the SELECT
  86265. ** load value into register R..R+n
  86266. ** yield X
  86267. ** end loop
  86268. ** cleanup after the SELECT
  86269. ** EOF <- 1
  86270. ** yield X
  86271. ** halt-error
  86272. ** B: open temp table
  86273. ** L: yield X
  86274. ** if EOF goto M
  86275. ** insert row from R..R+n into temp table
  86276. ** goto L
  86277. ** M: open write cursor to <table> and its indices
  86278. ** rewind temp table
  86279. ** C: loop over rows of intermediate table
  86280. ** transfer values form intermediate table into <table>
  86281. ** end loop
  86282. ** D: cleanup
  86283. */
  86284. SQLITE_PRIVATE void sqlite3Insert(
  86285. Parse *pParse, /* Parser context */
  86286. SrcList *pTabList, /* Name of table into which we are inserting */
  86287. ExprList *pList, /* List of values to be inserted */
  86288. Select *pSelect, /* A SELECT statement to use as the data source */
  86289. IdList *pColumn, /* Column names corresponding to IDLIST. */
  86290. int onError /* How to handle constraint errors */
  86291. ){
  86292. sqlite3 *db; /* The main database structure */
  86293. Table *pTab; /* The table to insert into. aka TABLE */
  86294. char *zTab; /* Name of the table into which we are inserting */
  86295. const char *zDb; /* Name of the database holding this table */
  86296. int i, j, idx; /* Loop counters */
  86297. Vdbe *v; /* Generate code into this virtual machine */
  86298. Index *pIdx; /* For looping over indices of the table */
  86299. int nColumn; /* Number of columns in the data */
  86300. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  86301. int baseCur = 0; /* VDBE Cursor number for pTab */
  86302. int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  86303. int endOfLoop; /* Label for the end of the insertion loop */
  86304. int useTempTable = 0; /* Store SELECT results in intermediate table */
  86305. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  86306. int addrInsTop = 0; /* Jump to label "D" */
  86307. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  86308. int addrSelect = 0; /* Address of coroutine that implements the SELECT */
  86309. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  86310. int iDb; /* Index of database holding TABLE */
  86311. Db *pDb; /* The database containing table being inserted into */
  86312. int appendFlag = 0; /* True if the insert is likely to be an append */
  86313. /* Register allocations */
  86314. int regFromSelect = 0;/* Base register for data coming from SELECT */
  86315. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  86316. int regRowCount = 0; /* Memory cell used for the row counter */
  86317. int regIns; /* Block of regs holding rowid+data being inserted */
  86318. int regRowid; /* registers holding insert rowid */
  86319. int regData; /* register holding first column to insert */
  86320. int regEof = 0; /* Register recording end of SELECT data */
  86321. int *aRegIdx = 0; /* One register allocated to each index */
  86322. #ifndef SQLITE_OMIT_TRIGGER
  86323. int isView; /* True if attempting to insert into a view */
  86324. Trigger *pTrigger; /* List of triggers on pTab, if required */
  86325. int tmask; /* Mask of trigger times */
  86326. #endif
  86327. db = pParse->db;
  86328. memset(&dest, 0, sizeof(dest));
  86329. if( pParse->nErr || db->mallocFailed ){
  86330. goto insert_cleanup;
  86331. }
  86332. /* Locate the table into which we will be inserting new information.
  86333. */
  86334. assert( pTabList->nSrc==1 );
  86335. zTab = pTabList->a[0].zName;
  86336. if( NEVER(zTab==0) ) goto insert_cleanup;
  86337. pTab = sqlite3SrcListLookup(pParse, pTabList);
  86338. if( pTab==0 ){
  86339. goto insert_cleanup;
  86340. }
  86341. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  86342. assert( iDb<db->nDb );
  86343. pDb = &db->aDb[iDb];
  86344. zDb = pDb->zName;
  86345. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  86346. goto insert_cleanup;
  86347. }
  86348. /* Figure out if we have any triggers and if the table being
  86349. ** inserted into is a view
  86350. */
  86351. #ifndef SQLITE_OMIT_TRIGGER
  86352. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  86353. isView = pTab->pSelect!=0;
  86354. #else
  86355. # define pTrigger 0
  86356. # define tmask 0
  86357. # define isView 0
  86358. #endif
  86359. #ifdef SQLITE_OMIT_VIEW
  86360. # undef isView
  86361. # define isView 0
  86362. #endif
  86363. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  86364. /* If pTab is really a view, make sure it has been initialized.
  86365. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
  86366. ** module table).
  86367. */
  86368. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  86369. goto insert_cleanup;
  86370. }
  86371. /* Ensure that:
  86372. * (a) the table is not read-only,
  86373. * (b) that if it is a view then ON INSERT triggers exist
  86374. */
  86375. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  86376. goto insert_cleanup;
  86377. }
  86378. /* Allocate a VDBE
  86379. */
  86380. v = sqlite3GetVdbe(pParse);
  86381. if( v==0 ) goto insert_cleanup;
  86382. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  86383. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  86384. #ifndef SQLITE_OMIT_XFER_OPT
  86385. /* If the statement is of the form
  86386. **
  86387. ** INSERT INTO <table1> SELECT * FROM <table2>;
  86388. **
  86389. ** Then special optimizations can be applied that make the transfer
  86390. ** very fast and which reduce fragmentation of indices.
  86391. **
  86392. ** This is the 2nd template.
  86393. */
  86394. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  86395. assert( !pTrigger );
  86396. assert( pList==0 );
  86397. goto insert_end;
  86398. }
  86399. #endif /* SQLITE_OMIT_XFER_OPT */
  86400. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  86401. ** sqlite_sequence table and store it in memory cell regAutoinc.
  86402. */
  86403. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  86404. /* Figure out how many columns of data are supplied. If the data
  86405. ** is coming from a SELECT statement, then generate a co-routine that
  86406. ** produces a single row of the SELECT on each invocation. The
  86407. ** co-routine is the common header to the 3rd and 4th templates.
  86408. */
  86409. if( pSelect ){
  86410. /* Data is coming from a SELECT. Generate a co-routine to run that
  86411. ** SELECT. */
  86412. int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
  86413. if( rc ) goto insert_cleanup;
  86414. regEof = dest.iSDParm + 1;
  86415. regFromSelect = dest.iSdst;
  86416. assert( pSelect->pEList );
  86417. nColumn = pSelect->pEList->nExpr;
  86418. assert( dest.nSdst==nColumn );
  86419. /* Set useTempTable to TRUE if the result of the SELECT statement
  86420. ** should be written into a temporary table (template 4). Set to
  86421. ** FALSE if each* row of the SELECT can be written directly into
  86422. ** the destination table (template 3).
  86423. **
  86424. ** A temp table must be used if the table being updated is also one
  86425. ** of the tables being read by the SELECT statement. Also use a
  86426. ** temp table in the case of row triggers.
  86427. */
  86428. if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
  86429. useTempTable = 1;
  86430. }
  86431. if( useTempTable ){
  86432. /* Invoke the coroutine to extract information from the SELECT
  86433. ** and add it to a transient table srcTab. The code generated
  86434. ** here is from the 4th template:
  86435. **
  86436. ** B: open temp table
  86437. ** L: yield X
  86438. ** if EOF goto M
  86439. ** insert row from R..R+n into temp table
  86440. ** goto L
  86441. ** M: ...
  86442. */
  86443. int regRec; /* Register to hold packed record */
  86444. int regTempRowid; /* Register to hold temp table ROWID */
  86445. int addrTop; /* Label "L" */
  86446. int addrIf; /* Address of jump to M */
  86447. srcTab = pParse->nTab++;
  86448. regRec = sqlite3GetTempReg(pParse);
  86449. regTempRowid = sqlite3GetTempReg(pParse);
  86450. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  86451. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  86452. addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
  86453. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  86454. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  86455. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  86456. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  86457. sqlite3VdbeJumpHere(v, addrIf);
  86458. sqlite3ReleaseTempReg(pParse, regRec);
  86459. sqlite3ReleaseTempReg(pParse, regTempRowid);
  86460. }
  86461. }else{
  86462. /* This is the case if the data for the INSERT is coming from a VALUES
  86463. ** clause
  86464. */
  86465. NameContext sNC;
  86466. memset(&sNC, 0, sizeof(sNC));
  86467. sNC.pParse = pParse;
  86468. srcTab = -1;
  86469. assert( useTempTable==0 );
  86470. nColumn = pList ? pList->nExpr : 0;
  86471. for(i=0; i<nColumn; i++){
  86472. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  86473. goto insert_cleanup;
  86474. }
  86475. }
  86476. }
  86477. /* Make sure the number of columns in the source data matches the number
  86478. ** of columns to be inserted into the table.
  86479. */
  86480. if( IsVirtual(pTab) ){
  86481. for(i=0; i<pTab->nCol; i++){
  86482. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  86483. }
  86484. }
  86485. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  86486. sqlite3ErrorMsg(pParse,
  86487. "table %S has %d columns but %d values were supplied",
  86488. pTabList, 0, pTab->nCol-nHidden, nColumn);
  86489. goto insert_cleanup;
  86490. }
  86491. if( pColumn!=0 && nColumn!=pColumn->nId ){
  86492. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  86493. goto insert_cleanup;
  86494. }
  86495. /* If the INSERT statement included an IDLIST term, then make sure
  86496. ** all elements of the IDLIST really are columns of the table and
  86497. ** remember the column indices.
  86498. **
  86499. ** If the table has an INTEGER PRIMARY KEY column and that column
  86500. ** is named in the IDLIST, then record in the keyColumn variable
  86501. ** the index into IDLIST of the primary key column. keyColumn is
  86502. ** the index of the primary key as it appears in IDLIST, not as
  86503. ** is appears in the original table. (The index of the primary
  86504. ** key in the original table is pTab->iPKey.)
  86505. */
  86506. if( pColumn ){
  86507. for(i=0; i<pColumn->nId; i++){
  86508. pColumn->a[i].idx = -1;
  86509. }
  86510. for(i=0; i<pColumn->nId; i++){
  86511. for(j=0; j<pTab->nCol; j++){
  86512. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  86513. pColumn->a[i].idx = j;
  86514. if( j==pTab->iPKey ){
  86515. keyColumn = i;
  86516. }
  86517. break;
  86518. }
  86519. }
  86520. if( j>=pTab->nCol ){
  86521. if( sqlite3IsRowid(pColumn->a[i].zName) ){
  86522. keyColumn = i;
  86523. }else{
  86524. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  86525. pTabList, 0, pColumn->a[i].zName);
  86526. pParse->checkSchema = 1;
  86527. goto insert_cleanup;
  86528. }
  86529. }
  86530. }
  86531. }
  86532. /* If there is no IDLIST term but the table has an integer primary
  86533. ** key, the set the keyColumn variable to the primary key column index
  86534. ** in the original table definition.
  86535. */
  86536. if( pColumn==0 && nColumn>0 ){
  86537. keyColumn = pTab->iPKey;
  86538. }
  86539. /* Initialize the count of rows to be inserted
  86540. */
  86541. if( db->flags & SQLITE_CountRows ){
  86542. regRowCount = ++pParse->nMem;
  86543. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  86544. }
  86545. /* If this is not a view, open the table and and all indices */
  86546. if( !isView ){
  86547. int nIdx;
  86548. baseCur = pParse->nTab;
  86549. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
  86550. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  86551. if( aRegIdx==0 ){
  86552. goto insert_cleanup;
  86553. }
  86554. for(i=0; i<nIdx; i++){
  86555. aRegIdx[i] = ++pParse->nMem;
  86556. }
  86557. }
  86558. /* This is the top of the main insertion loop */
  86559. if( useTempTable ){
  86560. /* This block codes the top of loop only. The complete loop is the
  86561. ** following pseudocode (template 4):
  86562. **
  86563. ** rewind temp table
  86564. ** C: loop over rows of intermediate table
  86565. ** transfer values form intermediate table into <table>
  86566. ** end loop
  86567. ** D: ...
  86568. */
  86569. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
  86570. addrCont = sqlite3VdbeCurrentAddr(v);
  86571. }else if( pSelect ){
  86572. /* This block codes the top of loop only. The complete loop is the
  86573. ** following pseudocode (template 3):
  86574. **
  86575. ** C: yield X
  86576. ** if EOF goto D
  86577. ** insert the select result into <table> from R..R+n
  86578. ** goto C
  86579. ** D: ...
  86580. */
  86581. addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  86582. addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
  86583. }
  86584. /* Allocate registers for holding the rowid of the new row,
  86585. ** the content of the new row, and the assemblied row record.
  86586. */
  86587. regRowid = regIns = pParse->nMem+1;
  86588. pParse->nMem += pTab->nCol + 1;
  86589. if( IsVirtual(pTab) ){
  86590. regRowid++;
  86591. pParse->nMem++;
  86592. }
  86593. regData = regRowid+1;
  86594. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  86595. */
  86596. endOfLoop = sqlite3VdbeMakeLabel(v);
  86597. if( tmask & TRIGGER_BEFORE ){
  86598. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  86599. /* build the NEW.* reference row. Note that if there is an INTEGER
  86600. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  86601. ** translated into a unique ID for the row. But on a BEFORE trigger,
  86602. ** we do not know what the unique ID will be (because the insert has
  86603. ** not happened yet) so we substitute a rowid of -1
  86604. */
  86605. if( keyColumn<0 ){
  86606. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  86607. }else{
  86608. int j1;
  86609. if( useTempTable ){
  86610. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
  86611. }else{
  86612. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  86613. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
  86614. }
  86615. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
  86616. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  86617. sqlite3VdbeJumpHere(v, j1);
  86618. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
  86619. }
  86620. /* Cannot have triggers on a virtual table. If it were possible,
  86621. ** this block would have to account for hidden column.
  86622. */
  86623. assert( !IsVirtual(pTab) );
  86624. /* Create the new column data
  86625. */
  86626. for(i=0; i<pTab->nCol; i++){
  86627. if( pColumn==0 ){
  86628. j = i;
  86629. }else{
  86630. for(j=0; j<pColumn->nId; j++){
  86631. if( pColumn->a[j].idx==i ) break;
  86632. }
  86633. }
  86634. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  86635. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  86636. }else if( useTempTable ){
  86637. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  86638. }else{
  86639. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  86640. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  86641. }
  86642. }
  86643. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  86644. ** do not attempt any conversions before assembling the record.
  86645. ** If this is a real table, attempt conversions as required by the
  86646. ** table column affinities.
  86647. */
  86648. if( !isView ){
  86649. sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
  86650. sqlite3TableAffinityStr(v, pTab);
  86651. }
  86652. /* Fire BEFORE or INSTEAD OF triggers */
  86653. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  86654. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  86655. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  86656. }
  86657. /* Push the record number for the new entry onto the stack. The
  86658. ** record number is a randomly generate integer created by NewRowid
  86659. ** except when the table has an INTEGER PRIMARY KEY column, in which
  86660. ** case the record number is the same as that column.
  86661. */
  86662. if( !isView ){
  86663. if( IsVirtual(pTab) ){
  86664. /* The row that the VUpdate opcode will delete: none */
  86665. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  86666. }
  86667. if( keyColumn>=0 ){
  86668. if( useTempTable ){
  86669. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
  86670. }else if( pSelect ){
  86671. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
  86672. }else{
  86673. VdbeOp *pOp;
  86674. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
  86675. pOp = sqlite3VdbeGetOp(v, -1);
  86676. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  86677. appendFlag = 1;
  86678. pOp->opcode = OP_NewRowid;
  86679. pOp->p1 = baseCur;
  86680. pOp->p2 = regRowid;
  86681. pOp->p3 = regAutoinc;
  86682. }
  86683. }
  86684. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  86685. ** to generate a unique primary key value.
  86686. */
  86687. if( !appendFlag ){
  86688. int j1;
  86689. if( !IsVirtual(pTab) ){
  86690. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
  86691. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  86692. sqlite3VdbeJumpHere(v, j1);
  86693. }else{
  86694. j1 = sqlite3VdbeCurrentAddr(v);
  86695. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
  86696. }
  86697. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  86698. }
  86699. }else if( IsVirtual(pTab) ){
  86700. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  86701. }else{
  86702. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  86703. appendFlag = 1;
  86704. }
  86705. autoIncStep(pParse, regAutoinc, regRowid);
  86706. /* Push onto the stack, data for all columns of the new entry, beginning
  86707. ** with the first column.
  86708. */
  86709. nHidden = 0;
  86710. for(i=0; i<pTab->nCol; i++){
  86711. int iRegStore = regRowid+1+i;
  86712. if( i==pTab->iPKey ){
  86713. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  86714. ** Whenever this column is read, the record number will be substituted
  86715. ** in its place. So will fill this column with a NULL to avoid
  86716. ** taking up data space with information that will never be used. */
  86717. sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
  86718. continue;
  86719. }
  86720. if( pColumn==0 ){
  86721. if( IsHiddenColumn(&pTab->aCol[i]) ){
  86722. assert( IsVirtual(pTab) );
  86723. j = -1;
  86724. nHidden++;
  86725. }else{
  86726. j = i - nHidden;
  86727. }
  86728. }else{
  86729. for(j=0; j<pColumn->nId; j++){
  86730. if( pColumn->a[j].idx==i ) break;
  86731. }
  86732. }
  86733. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  86734. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
  86735. }else if( useTempTable ){
  86736. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  86737. }else if( pSelect ){
  86738. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  86739. }else{
  86740. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  86741. }
  86742. }
  86743. /* Generate code to check constraints and generate index keys and
  86744. ** do the insertion.
  86745. */
  86746. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86747. if( IsVirtual(pTab) ){
  86748. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  86749. sqlite3VtabMakeWritable(pParse, pTab);
  86750. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  86751. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  86752. sqlite3MayAbort(pParse);
  86753. }else
  86754. #endif
  86755. {
  86756. int isReplace; /* Set to true if constraints may cause a replace */
  86757. sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
  86758. keyColumn>=0, 0, onError, endOfLoop, &isReplace
  86759. );
  86760. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  86761. sqlite3CompleteInsertion(
  86762. pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
  86763. );
  86764. }
  86765. }
  86766. /* Update the count of rows that are inserted
  86767. */
  86768. if( (db->flags & SQLITE_CountRows)!=0 ){
  86769. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  86770. }
  86771. if( pTrigger ){
  86772. /* Code AFTER triggers */
  86773. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  86774. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  86775. }
  86776. /* The bottom of the main insertion loop, if the data source
  86777. ** is a SELECT statement.
  86778. */
  86779. sqlite3VdbeResolveLabel(v, endOfLoop);
  86780. if( useTempTable ){
  86781. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
  86782. sqlite3VdbeJumpHere(v, addrInsTop);
  86783. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  86784. }else if( pSelect ){
  86785. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  86786. sqlite3VdbeJumpHere(v, addrInsTop);
  86787. }
  86788. if( !IsVirtual(pTab) && !isView ){
  86789. /* Close all tables opened */
  86790. sqlite3VdbeAddOp1(v, OP_Close, baseCur);
  86791. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  86792. sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
  86793. }
  86794. }
  86795. insert_end:
  86796. /* Update the sqlite_sequence table by storing the content of the
  86797. ** maximum rowid counter values recorded while inserting into
  86798. ** autoincrement tables.
  86799. */
  86800. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  86801. sqlite3AutoincrementEnd(pParse);
  86802. }
  86803. /*
  86804. ** Return the number of rows inserted. If this routine is
  86805. ** generating code because of a call to sqlite3NestedParse(), do not
  86806. ** invoke the callback function.
  86807. */
  86808. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  86809. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  86810. sqlite3VdbeSetNumCols(v, 1);
  86811. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  86812. }
  86813. insert_cleanup:
  86814. sqlite3SrcListDelete(db, pTabList);
  86815. sqlite3ExprListDelete(db, pList);
  86816. sqlite3SelectDelete(db, pSelect);
  86817. sqlite3IdListDelete(db, pColumn);
  86818. sqlite3DbFree(db, aRegIdx);
  86819. }
  86820. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  86821. ** thely may interfere with compilation of other functions in this file
  86822. ** (or in another file, if this file becomes part of the amalgamation). */
  86823. #ifdef isView
  86824. #undef isView
  86825. #endif
  86826. #ifdef pTrigger
  86827. #undef pTrigger
  86828. #endif
  86829. #ifdef tmask
  86830. #undef tmask
  86831. #endif
  86832. /*
  86833. ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  86834. **
  86835. ** The input is a range of consecutive registers as follows:
  86836. **
  86837. ** 1. The rowid of the row after the update.
  86838. **
  86839. ** 2. The data in the first column of the entry after the update.
  86840. **
  86841. ** i. Data from middle columns...
  86842. **
  86843. ** N. The data in the last column of the entry after the update.
  86844. **
  86845. ** The regRowid parameter is the index of the register containing (1).
  86846. **
  86847. ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
  86848. ** the address of a register containing the rowid before the update takes
  86849. ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
  86850. ** is false, indicating an INSERT statement, then a non-zero rowidChng
  86851. ** indicates that the rowid was explicitly specified as part of the
  86852. ** INSERT statement. If rowidChng is false, it means that the rowid is
  86853. ** computed automatically in an insert or that the rowid value is not
  86854. ** modified by an update.
  86855. **
  86856. ** The code generated by this routine store new index entries into
  86857. ** registers identified by aRegIdx[]. No index entry is created for
  86858. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  86859. ** the same as the order of indices on the linked list of indices
  86860. ** attached to the table.
  86861. **
  86862. ** This routine also generates code to check constraints. NOT NULL,
  86863. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  86864. ** then the appropriate action is performed. There are five possible
  86865. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  86866. **
  86867. ** Constraint type Action What Happens
  86868. ** --------------- ---------- ----------------------------------------
  86869. ** any ROLLBACK The current transaction is rolled back and
  86870. ** sqlite3_exec() returns immediately with a
  86871. ** return code of SQLITE_CONSTRAINT.
  86872. **
  86873. ** any ABORT Back out changes from the current command
  86874. ** only (do not do a complete rollback) then
  86875. ** cause sqlite3_exec() to return immediately
  86876. ** with SQLITE_CONSTRAINT.
  86877. **
  86878. ** any FAIL Sqlite3_exec() returns immediately with a
  86879. ** return code of SQLITE_CONSTRAINT. The
  86880. ** transaction is not rolled back and any
  86881. ** prior changes are retained.
  86882. **
  86883. ** any IGNORE The record number and data is popped from
  86884. ** the stack and there is an immediate jump
  86885. ** to label ignoreDest.
  86886. **
  86887. ** NOT NULL REPLACE The NULL value is replace by the default
  86888. ** value for that column. If the default value
  86889. ** is NULL, the action is the same as ABORT.
  86890. **
  86891. ** UNIQUE REPLACE The other row that conflicts with the row
  86892. ** being inserted is removed.
  86893. **
  86894. ** CHECK REPLACE Illegal. The results in an exception.
  86895. **
  86896. ** Which action to take is determined by the overrideError parameter.
  86897. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  86898. ** is used. Or if pParse->onError==OE_Default then the onError value
  86899. ** for the constraint is used.
  86900. **
  86901. ** The calling routine must open a read/write cursor for pTab with
  86902. ** cursor number "baseCur". All indices of pTab must also have open
  86903. ** read/write cursors with cursor number baseCur+i for the i-th cursor.
  86904. ** Except, if there is no possibility of a REPLACE action then
  86905. ** cursors do not need to be open for indices where aRegIdx[i]==0.
  86906. */
  86907. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  86908. Parse *pParse, /* The parser context */
  86909. Table *pTab, /* the table into which we are inserting */
  86910. int baseCur, /* Index of a read/write cursor pointing at pTab */
  86911. int regRowid, /* Index of the range of input registers */
  86912. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  86913. int rowidChng, /* True if the rowid might collide with existing entry */
  86914. int isUpdate, /* True for UPDATE, False for INSERT */
  86915. int overrideError, /* Override onError to this if not OE_Default */
  86916. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  86917. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  86918. ){
  86919. int i; /* loop counter */
  86920. Vdbe *v; /* VDBE under constrution */
  86921. int nCol; /* Number of columns */
  86922. int onError; /* Conflict resolution strategy */
  86923. int j1; /* Addresss of jump instruction */
  86924. int j2 = 0, j3; /* Addresses of jump instructions */
  86925. int regData; /* Register containing first data column */
  86926. int iCur; /* Table cursor number */
  86927. Index *pIdx; /* Pointer to one of the indices */
  86928. sqlite3 *db; /* Database connection */
  86929. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  86930. int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
  86931. db = pParse->db;
  86932. v = sqlite3GetVdbe(pParse);
  86933. assert( v!=0 );
  86934. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  86935. nCol = pTab->nCol;
  86936. regData = regRowid + 1;
  86937. /* Test all NOT NULL constraints.
  86938. */
  86939. for(i=0; i<nCol; i++){
  86940. if( i==pTab->iPKey ){
  86941. continue;
  86942. }
  86943. onError = pTab->aCol[i].notNull;
  86944. if( onError==OE_None ) continue;
  86945. if( overrideError!=OE_Default ){
  86946. onError = overrideError;
  86947. }else if( onError==OE_Default ){
  86948. onError = OE_Abort;
  86949. }
  86950. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  86951. onError = OE_Abort;
  86952. }
  86953. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  86954. || onError==OE_Ignore || onError==OE_Replace );
  86955. switch( onError ){
  86956. case OE_Abort:
  86957. sqlite3MayAbort(pParse);
  86958. case OE_Rollback:
  86959. case OE_Fail: {
  86960. char *zMsg;
  86961. sqlite3VdbeAddOp3(v, OP_HaltIfNull,
  86962. SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
  86963. zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
  86964. pTab->zName, pTab->aCol[i].zName);
  86965. sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
  86966. break;
  86967. }
  86968. case OE_Ignore: {
  86969. sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
  86970. break;
  86971. }
  86972. default: {
  86973. assert( onError==OE_Replace );
  86974. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
  86975. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
  86976. sqlite3VdbeJumpHere(v, j1);
  86977. break;
  86978. }
  86979. }
  86980. }
  86981. /* Test all CHECK constraints
  86982. */
  86983. #ifndef SQLITE_OMIT_CHECK
  86984. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  86985. ExprList *pCheck = pTab->pCheck;
  86986. pParse->ckBase = regData;
  86987. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  86988. for(i=0; i<pCheck->nExpr; i++){
  86989. int allOk = sqlite3VdbeMakeLabel(v);
  86990. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  86991. if( onError==OE_Ignore ){
  86992. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  86993. }else{
  86994. char *zConsName = pCheck->a[i].zName;
  86995. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  86996. if( zConsName ){
  86997. zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
  86998. }else{
  86999. zConsName = 0;
  87000. }
  87001. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  87002. onError, zConsName, P4_DYNAMIC);
  87003. }
  87004. sqlite3VdbeResolveLabel(v, allOk);
  87005. }
  87006. }
  87007. #endif /* !defined(SQLITE_OMIT_CHECK) */
  87008. /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  87009. ** of the new record does not previously exist. Except, if this
  87010. ** is an UPDATE and the primary key is not changing, that is OK.
  87011. */
  87012. if( rowidChng ){
  87013. onError = pTab->keyConf;
  87014. if( overrideError!=OE_Default ){
  87015. onError = overrideError;
  87016. }else if( onError==OE_Default ){
  87017. onError = OE_Abort;
  87018. }
  87019. if( isUpdate ){
  87020. j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
  87021. }
  87022. j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
  87023. switch( onError ){
  87024. default: {
  87025. onError = OE_Abort;
  87026. /* Fall thru into the next case */
  87027. }
  87028. case OE_Rollback:
  87029. case OE_Abort:
  87030. case OE_Fail: {
  87031. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  87032. onError, "PRIMARY KEY must be unique", P4_STATIC);
  87033. break;
  87034. }
  87035. case OE_Replace: {
  87036. /* If there are DELETE triggers on this table and the
  87037. ** recursive-triggers flag is set, call GenerateRowDelete() to
  87038. ** remove the conflicting row from the table. This will fire
  87039. ** the triggers and remove both the table and index b-tree entries.
  87040. **
  87041. ** Otherwise, if there are no triggers or the recursive-triggers
  87042. ** flag is not set, but the table has one or more indexes, call
  87043. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  87044. ** only. The table b-tree entry will be replaced by the new entry
  87045. ** when it is inserted.
  87046. **
  87047. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  87048. ** also invoke MultiWrite() to indicate that this VDBE may require
  87049. ** statement rollback (if the statement is aborted after the delete
  87050. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  87051. ** but being more selective here allows statements like:
  87052. **
  87053. ** REPLACE INTO t(rowid) VALUES($newrowid)
  87054. **
  87055. ** to run without a statement journal if there are no indexes on the
  87056. ** table.
  87057. */
  87058. Trigger *pTrigger = 0;
  87059. if( db->flags&SQLITE_RecTriggers ){
  87060. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  87061. }
  87062. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  87063. sqlite3MultiWrite(pParse);
  87064. sqlite3GenerateRowDelete(
  87065. pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
  87066. );
  87067. }else if( pTab->pIndex ){
  87068. sqlite3MultiWrite(pParse);
  87069. sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
  87070. }
  87071. seenReplace = 1;
  87072. break;
  87073. }
  87074. case OE_Ignore: {
  87075. assert( seenReplace==0 );
  87076. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  87077. break;
  87078. }
  87079. }
  87080. sqlite3VdbeJumpHere(v, j3);
  87081. if( isUpdate ){
  87082. sqlite3VdbeJumpHere(v, j2);
  87083. }
  87084. }
  87085. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  87086. ** index and making sure that duplicate entries do not already exist.
  87087. ** Add the new records to the indices as we go.
  87088. */
  87089. for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  87090. int regIdx;
  87091. int regR;
  87092. int addrSkipRow = 0;
  87093. if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
  87094. if( pIdx->pPartIdxWhere ){
  87095. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
  87096. addrSkipRow = sqlite3VdbeMakeLabel(v);
  87097. pParse->ckBase = regData;
  87098. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
  87099. SQLITE_JUMPIFNULL);
  87100. pParse->ckBase = 0;
  87101. }
  87102. /* Create a key for accessing the index entry */
  87103. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
  87104. for(i=0; i<pIdx->nColumn; i++){
  87105. int idx = pIdx->aiColumn[i];
  87106. if( idx==pTab->iPKey ){
  87107. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  87108. }else{
  87109. sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
  87110. }
  87111. }
  87112. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  87113. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
  87114. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
  87115. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
  87116. /* Find out what action to take in case there is an indexing conflict */
  87117. onError = pIdx->onError;
  87118. if( onError==OE_None ){
  87119. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  87120. sqlite3VdbeResolveLabel(v, addrSkipRow);
  87121. continue; /* pIdx is not a UNIQUE index */
  87122. }
  87123. if( overrideError!=OE_Default ){
  87124. onError = overrideError;
  87125. }else if( onError==OE_Default ){
  87126. onError = OE_Abort;
  87127. }
  87128. if( seenReplace ){
  87129. if( onError==OE_Ignore ) onError = OE_Replace;
  87130. else if( onError==OE_Fail ) onError = OE_Abort;
  87131. }
  87132. /* Check to see if the new index entry will be unique */
  87133. regR = sqlite3GetTempReg(pParse);
  87134. sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
  87135. j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  87136. regR, SQLITE_INT_TO_PTR(regIdx),
  87137. P4_INT32);
  87138. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  87139. /* Generate code that executes if the new index entry is not unique */
  87140. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  87141. || onError==OE_Ignore || onError==OE_Replace );
  87142. switch( onError ){
  87143. case OE_Rollback:
  87144. case OE_Abort:
  87145. case OE_Fail: {
  87146. int j;
  87147. StrAccum errMsg;
  87148. const char *zSep;
  87149. char *zErr;
  87150. sqlite3StrAccumInit(&errMsg, 0, 0, 200);
  87151. errMsg.db = db;
  87152. zSep = pIdx->nColumn>1 ? "columns " : "column ";
  87153. for(j=0; j<pIdx->nColumn; j++){
  87154. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  87155. sqlite3StrAccumAppend(&errMsg, zSep, -1);
  87156. zSep = ", ";
  87157. sqlite3StrAccumAppend(&errMsg, zCol, -1);
  87158. }
  87159. sqlite3StrAccumAppend(&errMsg,
  87160. pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
  87161. zErr = sqlite3StrAccumFinish(&errMsg);
  87162. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  87163. onError, zErr, 0);
  87164. sqlite3DbFree(errMsg.db, zErr);
  87165. break;
  87166. }
  87167. case OE_Ignore: {
  87168. assert( seenReplace==0 );
  87169. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  87170. break;
  87171. }
  87172. default: {
  87173. Trigger *pTrigger = 0;
  87174. assert( onError==OE_Replace );
  87175. sqlite3MultiWrite(pParse);
  87176. if( db->flags&SQLITE_RecTriggers ){
  87177. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  87178. }
  87179. sqlite3GenerateRowDelete(
  87180. pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
  87181. );
  87182. seenReplace = 1;
  87183. break;
  87184. }
  87185. }
  87186. sqlite3VdbeJumpHere(v, j3);
  87187. sqlite3VdbeResolveLabel(v, addrSkipRow);
  87188. sqlite3ReleaseTempReg(pParse, regR);
  87189. }
  87190. if( pbMayReplace ){
  87191. *pbMayReplace = seenReplace;
  87192. }
  87193. }
  87194. /*
  87195. ** This routine generates code to finish the INSERT or UPDATE operation
  87196. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  87197. ** A consecutive range of registers starting at regRowid contains the
  87198. ** rowid and the content to be inserted.
  87199. **
  87200. ** The arguments to this routine should be the same as the first six
  87201. ** arguments to sqlite3GenerateConstraintChecks.
  87202. */
  87203. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  87204. Parse *pParse, /* The parser context */
  87205. Table *pTab, /* the table into which we are inserting */
  87206. int baseCur, /* Index of a read/write cursor pointing at pTab */
  87207. int regRowid, /* Range of content */
  87208. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  87209. int isUpdate, /* True for UPDATE, False for INSERT */
  87210. int appendBias, /* True if this is likely to be an append */
  87211. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  87212. ){
  87213. int i;
  87214. Vdbe *v;
  87215. Index *pIdx;
  87216. u8 pik_flags;
  87217. int regData;
  87218. int regRec;
  87219. v = sqlite3GetVdbe(pParse);
  87220. assert( v!=0 );
  87221. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  87222. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  87223. if( aRegIdx[i]==0 ) continue;
  87224. if( pIdx->pPartIdxWhere ){
  87225. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  87226. }
  87227. sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
  87228. if( useSeekResult ){
  87229. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  87230. }
  87231. }
  87232. regData = regRowid + 1;
  87233. regRec = sqlite3GetTempReg(pParse);
  87234. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  87235. sqlite3TableAffinityStr(v, pTab);
  87236. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  87237. if( pParse->nested ){
  87238. pik_flags = 0;
  87239. }else{
  87240. pik_flags = OPFLAG_NCHANGE;
  87241. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  87242. }
  87243. if( appendBias ){
  87244. pik_flags |= OPFLAG_APPEND;
  87245. }
  87246. if( useSeekResult ){
  87247. pik_flags |= OPFLAG_USESEEKRESULT;
  87248. }
  87249. sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
  87250. if( !pParse->nested ){
  87251. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  87252. }
  87253. sqlite3VdbeChangeP5(v, pik_flags);
  87254. }
  87255. /*
  87256. ** Generate code that will open cursors for a table and for all
  87257. ** indices of that table. The "baseCur" parameter is the cursor number used
  87258. ** for the table. Indices are opened on subsequent cursors.
  87259. **
  87260. ** Return the number of indices on the table.
  87261. */
  87262. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  87263. Parse *pParse, /* Parsing context */
  87264. Table *pTab, /* Table to be opened */
  87265. int baseCur, /* Cursor number assigned to the table */
  87266. int op /* OP_OpenRead or OP_OpenWrite */
  87267. ){
  87268. int i;
  87269. int iDb;
  87270. Index *pIdx;
  87271. Vdbe *v;
  87272. if( IsVirtual(pTab) ) return 0;
  87273. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  87274. v = sqlite3GetVdbe(pParse);
  87275. assert( v!=0 );
  87276. sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
  87277. for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  87278. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  87279. assert( pIdx->pSchema==pTab->pSchema );
  87280. sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
  87281. (char*)pKey, P4_KEYINFO_HANDOFF);
  87282. VdbeComment((v, "%s", pIdx->zName));
  87283. }
  87284. if( pParse->nTab<baseCur+i ){
  87285. pParse->nTab = baseCur+i;
  87286. }
  87287. return i-1;
  87288. }
  87289. #ifdef SQLITE_TEST
  87290. /*
  87291. ** The following global variable is incremented whenever the
  87292. ** transfer optimization is used. This is used for testing
  87293. ** purposes only - to make sure the transfer optimization really
  87294. ** is happening when it is suppose to.
  87295. */
  87296. SQLITE_API int sqlite3_xferopt_count;
  87297. #endif /* SQLITE_TEST */
  87298. #ifndef SQLITE_OMIT_XFER_OPT
  87299. /*
  87300. ** Check to collation names to see if they are compatible.
  87301. */
  87302. static int xferCompatibleCollation(const char *z1, const char *z2){
  87303. if( z1==0 ){
  87304. return z2==0;
  87305. }
  87306. if( z2==0 ){
  87307. return 0;
  87308. }
  87309. return sqlite3StrICmp(z1, z2)==0;
  87310. }
  87311. /*
  87312. ** Check to see if index pSrc is compatible as a source of data
  87313. ** for index pDest in an insert transfer optimization. The rules
  87314. ** for a compatible index:
  87315. **
  87316. ** * The index is over the same set of columns
  87317. ** * The same DESC and ASC markings occurs on all columns
  87318. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  87319. ** * The same collating sequence on each column
  87320. ** * The index has the exact same WHERE clause
  87321. */
  87322. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  87323. int i;
  87324. assert( pDest && pSrc );
  87325. assert( pDest->pTable!=pSrc->pTable );
  87326. if( pDest->nColumn!=pSrc->nColumn ){
  87327. return 0; /* Different number of columns */
  87328. }
  87329. if( pDest->onError!=pSrc->onError ){
  87330. return 0; /* Different conflict resolution strategies */
  87331. }
  87332. for(i=0; i<pSrc->nColumn; i++){
  87333. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  87334. return 0; /* Different columns indexed */
  87335. }
  87336. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  87337. return 0; /* Different sort orders */
  87338. }
  87339. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  87340. return 0; /* Different collating sequences */
  87341. }
  87342. }
  87343. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  87344. return 0; /* Different WHERE clauses */
  87345. }
  87346. /* If no test above fails then the indices must be compatible */
  87347. return 1;
  87348. }
  87349. /*
  87350. ** Attempt the transfer optimization on INSERTs of the form
  87351. **
  87352. ** INSERT INTO tab1 SELECT * FROM tab2;
  87353. **
  87354. ** The xfer optimization transfers raw records from tab2 over to tab1.
  87355. ** Columns are not decoded and reassemblied, which greatly improves
  87356. ** performance. Raw index records are transferred in the same way.
  87357. **
  87358. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  87359. ** There are lots of rules for determining compatibility - see comments
  87360. ** embedded in the code for details.
  87361. **
  87362. ** This routine returns TRUE if the optimization is guaranteed to be used.
  87363. ** Sometimes the xfer optimization will only work if the destination table
  87364. ** is empty - a factor that can only be determined at run-time. In that
  87365. ** case, this routine generates code for the xfer optimization but also
  87366. ** does a test to see if the destination table is empty and jumps over the
  87367. ** xfer optimization code if the test fails. In that case, this routine
  87368. ** returns FALSE so that the caller will know to go ahead and generate
  87369. ** an unoptimized transfer. This routine also returns FALSE if there
  87370. ** is no chance that the xfer optimization can be applied.
  87371. **
  87372. ** This optimization is particularly useful at making VACUUM run faster.
  87373. */
  87374. static int xferOptimization(
  87375. Parse *pParse, /* Parser context */
  87376. Table *pDest, /* The table we are inserting into */
  87377. Select *pSelect, /* A SELECT statement to use as the data source */
  87378. int onError, /* How to handle constraint errors */
  87379. int iDbDest /* The database of pDest */
  87380. ){
  87381. ExprList *pEList; /* The result set of the SELECT */
  87382. Table *pSrc; /* The table in the FROM clause of SELECT */
  87383. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  87384. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  87385. int i; /* Loop counter */
  87386. int iDbSrc; /* The database of pSrc */
  87387. int iSrc, iDest; /* Cursors from source and destination */
  87388. int addr1, addr2; /* Loop addresses */
  87389. int emptyDestTest; /* Address of test for empty pDest */
  87390. int emptySrcTest; /* Address of test for empty pSrc */
  87391. Vdbe *v; /* The VDBE we are building */
  87392. KeyInfo *pKey; /* Key information for an index */
  87393. int regAutoinc; /* Memory register used by AUTOINC */
  87394. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  87395. int regData, regRowid; /* Registers holding data and rowid */
  87396. if( pSelect==0 ){
  87397. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  87398. }
  87399. if( sqlite3TriggerList(pParse, pDest) ){
  87400. return 0; /* tab1 must not have triggers */
  87401. }
  87402. #ifndef SQLITE_OMIT_VIRTUALTABLE
  87403. if( pDest->tabFlags & TF_Virtual ){
  87404. return 0; /* tab1 must not be a virtual table */
  87405. }
  87406. #endif
  87407. if( onError==OE_Default ){
  87408. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  87409. if( onError==OE_Default ) onError = OE_Abort;
  87410. }
  87411. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  87412. if( pSelect->pSrc->nSrc!=1 ){
  87413. return 0; /* FROM clause must have exactly one term */
  87414. }
  87415. if( pSelect->pSrc->a[0].pSelect ){
  87416. return 0; /* FROM clause cannot contain a subquery */
  87417. }
  87418. if( pSelect->pWhere ){
  87419. return 0; /* SELECT may not have a WHERE clause */
  87420. }
  87421. if( pSelect->pOrderBy ){
  87422. return 0; /* SELECT may not have an ORDER BY clause */
  87423. }
  87424. /* Do not need to test for a HAVING clause. If HAVING is present but
  87425. ** there is no ORDER BY, we will get an error. */
  87426. if( pSelect->pGroupBy ){
  87427. return 0; /* SELECT may not have a GROUP BY clause */
  87428. }
  87429. if( pSelect->pLimit ){
  87430. return 0; /* SELECT may not have a LIMIT clause */
  87431. }
  87432. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  87433. if( pSelect->pPrior ){
  87434. return 0; /* SELECT may not be a compound query */
  87435. }
  87436. if( pSelect->selFlags & SF_Distinct ){
  87437. return 0; /* SELECT may not be DISTINCT */
  87438. }
  87439. pEList = pSelect->pEList;
  87440. assert( pEList!=0 );
  87441. if( pEList->nExpr!=1 ){
  87442. return 0; /* The result set must have exactly one column */
  87443. }
  87444. assert( pEList->a[0].pExpr );
  87445. if( pEList->a[0].pExpr->op!=TK_ALL ){
  87446. return 0; /* The result set must be the special operator "*" */
  87447. }
  87448. /* At this point we have established that the statement is of the
  87449. ** correct syntactic form to participate in this optimization. Now
  87450. ** we have to check the semantics.
  87451. */
  87452. pItem = pSelect->pSrc->a;
  87453. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  87454. if( pSrc==0 ){
  87455. return 0; /* FROM clause does not contain a real table */
  87456. }
  87457. if( pSrc==pDest ){
  87458. return 0; /* tab1 and tab2 may not be the same table */
  87459. }
  87460. #ifndef SQLITE_OMIT_VIRTUALTABLE
  87461. if( pSrc->tabFlags & TF_Virtual ){
  87462. return 0; /* tab2 must not be a virtual table */
  87463. }
  87464. #endif
  87465. if( pSrc->pSelect ){
  87466. return 0; /* tab2 may not be a view */
  87467. }
  87468. if( pDest->nCol!=pSrc->nCol ){
  87469. return 0; /* Number of columns must be the same in tab1 and tab2 */
  87470. }
  87471. if( pDest->iPKey!=pSrc->iPKey ){
  87472. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  87473. }
  87474. for(i=0; i<pDest->nCol; i++){
  87475. if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  87476. return 0; /* Affinity must be the same on all columns */
  87477. }
  87478. if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  87479. return 0; /* Collating sequence must be the same on all columns */
  87480. }
  87481. if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  87482. return 0; /* tab2 must be NOT NULL if tab1 is */
  87483. }
  87484. }
  87485. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  87486. if( pDestIdx->onError!=OE_None ){
  87487. destHasUniqueIdx = 1;
  87488. }
  87489. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  87490. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  87491. }
  87492. if( pSrcIdx==0 ){
  87493. return 0; /* pDestIdx has no corresponding index in pSrc */
  87494. }
  87495. }
  87496. #ifndef SQLITE_OMIT_CHECK
  87497. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  87498. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  87499. }
  87500. #endif
  87501. #ifndef SQLITE_OMIT_FOREIGN_KEY
  87502. /* Disallow the transfer optimization if the destination table constains
  87503. ** any foreign key constraints. This is more restrictive than necessary.
  87504. ** But the main beneficiary of the transfer optimization is the VACUUM
  87505. ** command, and the VACUUM command disables foreign key constraints. So
  87506. ** the extra complication to make this rule less restrictive is probably
  87507. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  87508. */
  87509. if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  87510. return 0;
  87511. }
  87512. #endif
  87513. if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
  87514. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  87515. }
  87516. /* If we get this far, it means that the xfer optimization is at
  87517. ** least a possibility, though it might only work if the destination
  87518. ** table (tab1) is initially empty.
  87519. */
  87520. #ifdef SQLITE_TEST
  87521. sqlite3_xferopt_count++;
  87522. #endif
  87523. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  87524. v = sqlite3GetVdbe(pParse);
  87525. sqlite3CodeVerifySchema(pParse, iDbSrc);
  87526. iSrc = pParse->nTab++;
  87527. iDest = pParse->nTab++;
  87528. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  87529. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  87530. if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  87531. || destHasUniqueIdx /* (2) */
  87532. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  87533. ){
  87534. /* In some circumstances, we are able to run the xfer optimization
  87535. ** only if the destination table is initially empty. This code makes
  87536. ** that determination. Conditions under which the destination must
  87537. ** be empty:
  87538. **
  87539. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  87540. ** (If the destination is not initially empty, the rowid fields
  87541. ** of index entries might need to change.)
  87542. **
  87543. ** (2) The destination has a unique index. (The xfer optimization
  87544. ** is unable to test uniqueness.)
  87545. **
  87546. ** (3) onError is something other than OE_Abort and OE_Rollback.
  87547. */
  87548. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
  87549. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  87550. sqlite3VdbeJumpHere(v, addr1);
  87551. }else{
  87552. emptyDestTest = 0;
  87553. }
  87554. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  87555. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  87556. regData = sqlite3GetTempReg(pParse);
  87557. regRowid = sqlite3GetTempReg(pParse);
  87558. if( pDest->iPKey>=0 ){
  87559. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  87560. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  87561. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  87562. onError, "PRIMARY KEY must be unique", P4_STATIC);
  87563. sqlite3VdbeJumpHere(v, addr2);
  87564. autoIncStep(pParse, regAutoinc, regRowid);
  87565. }else if( pDest->pIndex==0 ){
  87566. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  87567. }else{
  87568. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  87569. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  87570. }
  87571. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  87572. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  87573. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  87574. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  87575. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
  87576. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  87577. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  87578. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  87579. }
  87580. assert( pSrcIdx );
  87581. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  87582. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  87583. pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  87584. sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
  87585. (char*)pKey, P4_KEYINFO_HANDOFF);
  87586. VdbeComment((v, "%s", pSrcIdx->zName));
  87587. pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  87588. sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
  87589. (char*)pKey, P4_KEYINFO_HANDOFF);
  87590. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  87591. VdbeComment((v, "%s", pDestIdx->zName));
  87592. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  87593. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  87594. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  87595. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
  87596. sqlite3VdbeJumpHere(v, addr1);
  87597. }
  87598. sqlite3VdbeJumpHere(v, emptySrcTest);
  87599. sqlite3ReleaseTempReg(pParse, regRowid);
  87600. sqlite3ReleaseTempReg(pParse, regData);
  87601. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  87602. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  87603. if( emptyDestTest ){
  87604. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  87605. sqlite3VdbeJumpHere(v, emptyDestTest);
  87606. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  87607. return 0;
  87608. }else{
  87609. return 1;
  87610. }
  87611. }
  87612. #endif /* SQLITE_OMIT_XFER_OPT */
  87613. /************** End of insert.c **********************************************/
  87614. /************** Begin file legacy.c ******************************************/
  87615. /*
  87616. ** 2001 September 15
  87617. **
  87618. ** The author disclaims copyright to this source code. In place of
  87619. ** a legal notice, here is a blessing:
  87620. **
  87621. ** May you do good and not evil.
  87622. ** May you find forgiveness for yourself and forgive others.
  87623. ** May you share freely, never taking more than you give.
  87624. **
  87625. *************************************************************************
  87626. ** Main file for the SQLite library. The routines in this file
  87627. ** implement the programmer interface to the library. Routines in
  87628. ** other files are for internal use by SQLite and should not be
  87629. ** accessed by users of the library.
  87630. */
  87631. /*
  87632. ** Execute SQL code. Return one of the SQLITE_ success/failure
  87633. ** codes. Also write an error message into memory obtained from
  87634. ** malloc() and make *pzErrMsg point to that message.
  87635. **
  87636. ** If the SQL is a query, then for each row in the query result
  87637. ** the xCallback() function is called. pArg becomes the first
  87638. ** argument to xCallback(). If xCallback=NULL then no callback
  87639. ** is invoked, even for queries.
  87640. */
  87641. SQLITE_API int sqlite3_exec(
  87642. sqlite3 *db, /* The database on which the SQL executes */
  87643. const char *zSql, /* The SQL to be executed */
  87644. sqlite3_callback xCallback, /* Invoke this callback routine */
  87645. void *pArg, /* First argument to xCallback() */
  87646. char **pzErrMsg /* Write error messages here */
  87647. ){
  87648. int rc = SQLITE_OK; /* Return code */
  87649. const char *zLeftover; /* Tail of unprocessed SQL */
  87650. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  87651. char **azCols = 0; /* Names of result columns */
  87652. int callbackIsInit; /* True if callback data is initialized */
  87653. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  87654. if( zSql==0 ) zSql = "";
  87655. sqlite3_mutex_enter(db->mutex);
  87656. sqlite3Error(db, SQLITE_OK, 0);
  87657. while( rc==SQLITE_OK && zSql[0] ){
  87658. int nCol;
  87659. char **azVals = 0;
  87660. pStmt = 0;
  87661. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  87662. assert( rc==SQLITE_OK || pStmt==0 );
  87663. if( rc!=SQLITE_OK ){
  87664. continue;
  87665. }
  87666. if( !pStmt ){
  87667. /* this happens for a comment or white-space */
  87668. zSql = zLeftover;
  87669. continue;
  87670. }
  87671. callbackIsInit = 0;
  87672. nCol = sqlite3_column_count(pStmt);
  87673. while( 1 ){
  87674. int i;
  87675. rc = sqlite3_step(pStmt);
  87676. /* Invoke the callback function if required */
  87677. if( xCallback && (SQLITE_ROW==rc ||
  87678. (SQLITE_DONE==rc && !callbackIsInit
  87679. && db->flags&SQLITE_NullCallback)) ){
  87680. if( !callbackIsInit ){
  87681. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  87682. if( azCols==0 ){
  87683. goto exec_out;
  87684. }
  87685. for(i=0; i<nCol; i++){
  87686. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  87687. /* sqlite3VdbeSetColName() installs column names as UTF8
  87688. ** strings so there is no way for sqlite3_column_name() to fail. */
  87689. assert( azCols[i]!=0 );
  87690. }
  87691. callbackIsInit = 1;
  87692. }
  87693. if( rc==SQLITE_ROW ){
  87694. azVals = &azCols[nCol];
  87695. for(i=0; i<nCol; i++){
  87696. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  87697. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  87698. db->mallocFailed = 1;
  87699. goto exec_out;
  87700. }
  87701. }
  87702. }
  87703. if( xCallback(pArg, nCol, azVals, azCols) ){
  87704. rc = SQLITE_ABORT;
  87705. sqlite3VdbeFinalize((Vdbe *)pStmt);
  87706. pStmt = 0;
  87707. sqlite3Error(db, SQLITE_ABORT, 0);
  87708. goto exec_out;
  87709. }
  87710. }
  87711. if( rc!=SQLITE_ROW ){
  87712. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  87713. pStmt = 0;
  87714. zSql = zLeftover;
  87715. while( sqlite3Isspace(zSql[0]) ) zSql++;
  87716. break;
  87717. }
  87718. }
  87719. sqlite3DbFree(db, azCols);
  87720. azCols = 0;
  87721. }
  87722. exec_out:
  87723. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  87724. sqlite3DbFree(db, azCols);
  87725. rc = sqlite3ApiExit(db, rc);
  87726. if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
  87727. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  87728. *pzErrMsg = sqlite3Malloc(nErrMsg);
  87729. if( *pzErrMsg ){
  87730. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  87731. }else{
  87732. rc = SQLITE_NOMEM;
  87733. sqlite3Error(db, SQLITE_NOMEM, 0);
  87734. }
  87735. }else if( pzErrMsg ){
  87736. *pzErrMsg = 0;
  87737. }
  87738. assert( (rc&db->errMask)==rc );
  87739. sqlite3_mutex_leave(db->mutex);
  87740. return rc;
  87741. }
  87742. /************** End of legacy.c **********************************************/
  87743. /************** Begin file loadext.c *****************************************/
  87744. /*
  87745. ** 2006 June 7
  87746. **
  87747. ** The author disclaims copyright to this source code. In place of
  87748. ** a legal notice, here is a blessing:
  87749. **
  87750. ** May you do good and not evil.
  87751. ** May you find forgiveness for yourself and forgive others.
  87752. ** May you share freely, never taking more than you give.
  87753. **
  87754. *************************************************************************
  87755. ** This file contains code used to dynamically load extensions into
  87756. ** the SQLite library.
  87757. */
  87758. #ifndef SQLITE_CORE
  87759. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  87760. #endif
  87761. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  87762. /************** Begin file sqlite3ext.h **************************************/
  87763. /*
  87764. ** 2006 June 7
  87765. **
  87766. ** The author disclaims copyright to this source code. In place of
  87767. ** a legal notice, here is a blessing:
  87768. **
  87769. ** May you do good and not evil.
  87770. ** May you find forgiveness for yourself and forgive others.
  87771. ** May you share freely, never taking more than you give.
  87772. **
  87773. *************************************************************************
  87774. ** This header file defines the SQLite interface for use by
  87775. ** shared libraries that want to be imported as extensions into
  87776. ** an SQLite instance. Shared libraries that intend to be loaded
  87777. ** as extensions by SQLite should #include this file instead of
  87778. ** sqlite3.h.
  87779. */
  87780. #ifndef _SQLITE3EXT_H_
  87781. #define _SQLITE3EXT_H_
  87782. typedef struct sqlite3_api_routines sqlite3_api_routines;
  87783. /*
  87784. ** The following structure holds pointers to all of the SQLite API
  87785. ** routines.
  87786. **
  87787. ** WARNING: In order to maintain backwards compatibility, add new
  87788. ** interfaces to the end of this structure only. If you insert new
  87789. ** interfaces in the middle of this structure, then older different
  87790. ** versions of SQLite will not be able to load each others' shared
  87791. ** libraries!
  87792. */
  87793. struct sqlite3_api_routines {
  87794. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  87795. int (*aggregate_count)(sqlite3_context*);
  87796. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  87797. int (*bind_double)(sqlite3_stmt*,int,double);
  87798. int (*bind_int)(sqlite3_stmt*,int,int);
  87799. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  87800. int (*bind_null)(sqlite3_stmt*,int);
  87801. int (*bind_parameter_count)(sqlite3_stmt*);
  87802. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  87803. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  87804. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  87805. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  87806. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  87807. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  87808. int (*busy_timeout)(sqlite3*,int ms);
  87809. int (*changes)(sqlite3*);
  87810. int (*close)(sqlite3*);
  87811. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  87812. int eTextRep,const char*));
  87813. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  87814. int eTextRep,const void*));
  87815. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  87816. int (*column_bytes)(sqlite3_stmt*,int iCol);
  87817. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  87818. int (*column_count)(sqlite3_stmt*pStmt);
  87819. const char * (*column_database_name)(sqlite3_stmt*,int);
  87820. const void * (*column_database_name16)(sqlite3_stmt*,int);
  87821. const char * (*column_decltype)(sqlite3_stmt*,int i);
  87822. const void * (*column_decltype16)(sqlite3_stmt*,int);
  87823. double (*column_double)(sqlite3_stmt*,int iCol);
  87824. int (*column_int)(sqlite3_stmt*,int iCol);
  87825. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  87826. const char * (*column_name)(sqlite3_stmt*,int);
  87827. const void * (*column_name16)(sqlite3_stmt*,int);
  87828. const char * (*column_origin_name)(sqlite3_stmt*,int);
  87829. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  87830. const char * (*column_table_name)(sqlite3_stmt*,int);
  87831. const void * (*column_table_name16)(sqlite3_stmt*,int);
  87832. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  87833. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  87834. int (*column_type)(sqlite3_stmt*,int iCol);
  87835. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  87836. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  87837. int (*complete)(const char*sql);
  87838. int (*complete16)(const void*sql);
  87839. int (*create_collation)(sqlite3*,const char*,int,void*,
  87840. int(*)(void*,int,const void*,int,const void*));
  87841. int (*create_collation16)(sqlite3*,const void*,int,void*,
  87842. int(*)(void*,int,const void*,int,const void*));
  87843. int (*create_function)(sqlite3*,const char*,int,int,void*,
  87844. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  87845. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  87846. void (*xFinal)(sqlite3_context*));
  87847. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  87848. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  87849. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  87850. void (*xFinal)(sqlite3_context*));
  87851. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  87852. int (*data_count)(sqlite3_stmt*pStmt);
  87853. sqlite3 * (*db_handle)(sqlite3_stmt*);
  87854. int (*declare_vtab)(sqlite3*,const char*);
  87855. int (*enable_shared_cache)(int);
  87856. int (*errcode)(sqlite3*db);
  87857. const char * (*errmsg)(sqlite3*);
  87858. const void * (*errmsg16)(sqlite3*);
  87859. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  87860. int (*expired)(sqlite3_stmt*);
  87861. int (*finalize)(sqlite3_stmt*pStmt);
  87862. void (*free)(void*);
  87863. void (*free_table)(char**result);
  87864. int (*get_autocommit)(sqlite3*);
  87865. void * (*get_auxdata)(sqlite3_context*,int);
  87866. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  87867. int (*global_recover)(void);
  87868. void (*interruptx)(sqlite3*);
  87869. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  87870. const char * (*libversion)(void);
  87871. int (*libversion_number)(void);
  87872. void *(*malloc)(int);
  87873. char * (*mprintf)(const char*,...);
  87874. int (*open)(const char*,sqlite3**);
  87875. int (*open16)(const void*,sqlite3**);
  87876. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  87877. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  87878. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  87879. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  87880. void *(*realloc)(void*,int);
  87881. int (*reset)(sqlite3_stmt*pStmt);
  87882. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  87883. void (*result_double)(sqlite3_context*,double);
  87884. void (*result_error)(sqlite3_context*,const char*,int);
  87885. void (*result_error16)(sqlite3_context*,const void*,int);
  87886. void (*result_int)(sqlite3_context*,int);
  87887. void (*result_int64)(sqlite3_context*,sqlite_int64);
  87888. void (*result_null)(sqlite3_context*);
  87889. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  87890. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  87891. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  87892. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  87893. void (*result_value)(sqlite3_context*,sqlite3_value*);
  87894. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  87895. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  87896. const char*,const char*),void*);
  87897. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  87898. char * (*snprintf)(int,char*,const char*,...);
  87899. int (*step)(sqlite3_stmt*);
  87900. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  87901. char const**,char const**,int*,int*,int*);
  87902. void (*thread_cleanup)(void);
  87903. int (*total_changes)(sqlite3*);
  87904. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  87905. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  87906. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  87907. sqlite_int64),void*);
  87908. void * (*user_data)(sqlite3_context*);
  87909. const void * (*value_blob)(sqlite3_value*);
  87910. int (*value_bytes)(sqlite3_value*);
  87911. int (*value_bytes16)(sqlite3_value*);
  87912. double (*value_double)(sqlite3_value*);
  87913. int (*value_int)(sqlite3_value*);
  87914. sqlite_int64 (*value_int64)(sqlite3_value*);
  87915. int (*value_numeric_type)(sqlite3_value*);
  87916. const unsigned char * (*value_text)(sqlite3_value*);
  87917. const void * (*value_text16)(sqlite3_value*);
  87918. const void * (*value_text16be)(sqlite3_value*);
  87919. const void * (*value_text16le)(sqlite3_value*);
  87920. int (*value_type)(sqlite3_value*);
  87921. char *(*vmprintf)(const char*,va_list);
  87922. /* Added ??? */
  87923. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  87924. /* Added by 3.3.13 */
  87925. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  87926. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  87927. int (*clear_bindings)(sqlite3_stmt*);
  87928. /* Added by 3.4.1 */
  87929. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  87930. void (*xDestroy)(void *));
  87931. /* Added by 3.5.0 */
  87932. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  87933. int (*blob_bytes)(sqlite3_blob*);
  87934. int (*blob_close)(sqlite3_blob*);
  87935. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  87936. int,sqlite3_blob**);
  87937. int (*blob_read)(sqlite3_blob*,void*,int,int);
  87938. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  87939. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  87940. int(*)(void*,int,const void*,int,const void*),
  87941. void(*)(void*));
  87942. int (*file_control)(sqlite3*,const char*,int,void*);
  87943. sqlite3_int64 (*memory_highwater)(int);
  87944. sqlite3_int64 (*memory_used)(void);
  87945. sqlite3_mutex *(*mutex_alloc)(int);
  87946. void (*mutex_enter)(sqlite3_mutex*);
  87947. void (*mutex_free)(sqlite3_mutex*);
  87948. void (*mutex_leave)(sqlite3_mutex*);
  87949. int (*mutex_try)(sqlite3_mutex*);
  87950. int (*open_v2)(const char*,sqlite3**,int,const char*);
  87951. int (*release_memory)(int);
  87952. void (*result_error_nomem)(sqlite3_context*);
  87953. void (*result_error_toobig)(sqlite3_context*);
  87954. int (*sleep)(int);
  87955. void (*soft_heap_limit)(int);
  87956. sqlite3_vfs *(*vfs_find)(const char*);
  87957. int (*vfs_register)(sqlite3_vfs*,int);
  87958. int (*vfs_unregister)(sqlite3_vfs*);
  87959. int (*xthreadsafe)(void);
  87960. void (*result_zeroblob)(sqlite3_context*,int);
  87961. void (*result_error_code)(sqlite3_context*,int);
  87962. int (*test_control)(int, ...);
  87963. void (*randomness)(int,void*);
  87964. sqlite3 *(*context_db_handle)(sqlite3_context*);
  87965. int (*extended_result_codes)(sqlite3*,int);
  87966. int (*limit)(sqlite3*,int,int);
  87967. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  87968. const char *(*sql)(sqlite3_stmt*);
  87969. int (*status)(int,int*,int*,int);
  87970. int (*backup_finish)(sqlite3_backup*);
  87971. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  87972. int (*backup_pagecount)(sqlite3_backup*);
  87973. int (*backup_remaining)(sqlite3_backup*);
  87974. int (*backup_step)(sqlite3_backup*,int);
  87975. const char *(*compileoption_get)(int);
  87976. int (*compileoption_used)(const char*);
  87977. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  87978. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  87979. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  87980. void (*xFinal)(sqlite3_context*),
  87981. void(*xDestroy)(void*));
  87982. int (*db_config)(sqlite3*,int,...);
  87983. sqlite3_mutex *(*db_mutex)(sqlite3*);
  87984. int (*db_status)(sqlite3*,int,int*,int*,int);
  87985. int (*extended_errcode)(sqlite3*);
  87986. void (*log)(int,const char*,...);
  87987. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  87988. const char *(*sourceid)(void);
  87989. int (*stmt_status)(sqlite3_stmt*,int,int);
  87990. int (*strnicmp)(const char*,const char*,int);
  87991. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  87992. int (*wal_autocheckpoint)(sqlite3*,int);
  87993. int (*wal_checkpoint)(sqlite3*,const char*);
  87994. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  87995. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  87996. int (*vtab_config)(sqlite3*,int op,...);
  87997. int (*vtab_on_conflict)(sqlite3*);
  87998. /* Version 3.7.16 and later */
  87999. int (*close_v2)(sqlite3*);
  88000. const char *(*db_filename)(sqlite3*,const char*);
  88001. int (*db_readonly)(sqlite3*,const char*);
  88002. int (*db_release_memory)(sqlite3*);
  88003. const char *(*errstr)(int);
  88004. int (*stmt_busy)(sqlite3_stmt*);
  88005. int (*stmt_readonly)(sqlite3_stmt*);
  88006. int (*stricmp)(const char*,const char*);
  88007. int (*uri_boolean)(const char*,const char*,int);
  88008. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  88009. const char *(*uri_parameter)(const char*,const char*);
  88010. char *(*vsnprintf)(int,char*,const char*,va_list);
  88011. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  88012. };
  88013. /*
  88014. ** The following macros redefine the API routines so that they are
  88015. ** redirected throught the global sqlite3_api structure.
  88016. **
  88017. ** This header file is also used by the loadext.c source file
  88018. ** (part of the main SQLite library - not an extension) so that
  88019. ** it can get access to the sqlite3_api_routines structure
  88020. ** definition. But the main library does not want to redefine
  88021. ** the API. So the redefinition macros are only valid if the
  88022. ** SQLITE_CORE macros is undefined.
  88023. */
  88024. #ifndef SQLITE_CORE
  88025. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  88026. #ifndef SQLITE_OMIT_DEPRECATED
  88027. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  88028. #endif
  88029. #define sqlite3_bind_blob sqlite3_api->bind_blob
  88030. #define sqlite3_bind_double sqlite3_api->bind_double
  88031. #define sqlite3_bind_int sqlite3_api->bind_int
  88032. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  88033. #define sqlite3_bind_null sqlite3_api->bind_null
  88034. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  88035. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  88036. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  88037. #define sqlite3_bind_text sqlite3_api->bind_text
  88038. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  88039. #define sqlite3_bind_value sqlite3_api->bind_value
  88040. #define sqlite3_busy_handler sqlite3_api->busy_handler
  88041. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  88042. #define sqlite3_changes sqlite3_api->changes
  88043. #define sqlite3_close sqlite3_api->close
  88044. #define sqlite3_collation_needed sqlite3_api->collation_needed
  88045. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  88046. #define sqlite3_column_blob sqlite3_api->column_blob
  88047. #define sqlite3_column_bytes sqlite3_api->column_bytes
  88048. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  88049. #define sqlite3_column_count sqlite3_api->column_count
  88050. #define sqlite3_column_database_name sqlite3_api->column_database_name
  88051. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  88052. #define sqlite3_column_decltype sqlite3_api->column_decltype
  88053. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  88054. #define sqlite3_column_double sqlite3_api->column_double
  88055. #define sqlite3_column_int sqlite3_api->column_int
  88056. #define sqlite3_column_int64 sqlite3_api->column_int64
  88057. #define sqlite3_column_name sqlite3_api->column_name
  88058. #define sqlite3_column_name16 sqlite3_api->column_name16
  88059. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  88060. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  88061. #define sqlite3_column_table_name sqlite3_api->column_table_name
  88062. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  88063. #define sqlite3_column_text sqlite3_api->column_text
  88064. #define sqlite3_column_text16 sqlite3_api->column_text16
  88065. #define sqlite3_column_type sqlite3_api->column_type
  88066. #define sqlite3_column_value sqlite3_api->column_value
  88067. #define sqlite3_commit_hook sqlite3_api->commit_hook
  88068. #define sqlite3_complete sqlite3_api->complete
  88069. #define sqlite3_complete16 sqlite3_api->complete16
  88070. #define sqlite3_create_collation sqlite3_api->create_collation
  88071. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  88072. #define sqlite3_create_function sqlite3_api->create_function
  88073. #define sqlite3_create_function16 sqlite3_api->create_function16
  88074. #define sqlite3_create_module sqlite3_api->create_module
  88075. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  88076. #define sqlite3_data_count sqlite3_api->data_count
  88077. #define sqlite3_db_handle sqlite3_api->db_handle
  88078. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  88079. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  88080. #define sqlite3_errcode sqlite3_api->errcode
  88081. #define sqlite3_errmsg sqlite3_api->errmsg
  88082. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  88083. #define sqlite3_exec sqlite3_api->exec
  88084. #ifndef SQLITE_OMIT_DEPRECATED
  88085. #define sqlite3_expired sqlite3_api->expired
  88086. #endif
  88087. #define sqlite3_finalize sqlite3_api->finalize
  88088. #define sqlite3_free sqlite3_api->free
  88089. #define sqlite3_free_table sqlite3_api->free_table
  88090. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  88091. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  88092. #define sqlite3_get_table sqlite3_api->get_table
  88093. #ifndef SQLITE_OMIT_DEPRECATED
  88094. #define sqlite3_global_recover sqlite3_api->global_recover
  88095. #endif
  88096. #define sqlite3_interrupt sqlite3_api->interruptx
  88097. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  88098. #define sqlite3_libversion sqlite3_api->libversion
  88099. #define sqlite3_libversion_number sqlite3_api->libversion_number
  88100. #define sqlite3_malloc sqlite3_api->malloc
  88101. #define sqlite3_mprintf sqlite3_api->mprintf
  88102. #define sqlite3_open sqlite3_api->open
  88103. #define sqlite3_open16 sqlite3_api->open16
  88104. #define sqlite3_prepare sqlite3_api->prepare
  88105. #define sqlite3_prepare16 sqlite3_api->prepare16
  88106. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  88107. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  88108. #define sqlite3_profile sqlite3_api->profile
  88109. #define sqlite3_progress_handler sqlite3_api->progress_handler
  88110. #define sqlite3_realloc sqlite3_api->realloc
  88111. #define sqlite3_reset sqlite3_api->reset
  88112. #define sqlite3_result_blob sqlite3_api->result_blob
  88113. #define sqlite3_result_double sqlite3_api->result_double
  88114. #define sqlite3_result_error sqlite3_api->result_error
  88115. #define sqlite3_result_error16 sqlite3_api->result_error16
  88116. #define sqlite3_result_int sqlite3_api->result_int
  88117. #define sqlite3_result_int64 sqlite3_api->result_int64
  88118. #define sqlite3_result_null sqlite3_api->result_null
  88119. #define sqlite3_result_text sqlite3_api->result_text
  88120. #define sqlite3_result_text16 sqlite3_api->result_text16
  88121. #define sqlite3_result_text16be sqlite3_api->result_text16be
  88122. #define sqlite3_result_text16le sqlite3_api->result_text16le
  88123. #define sqlite3_result_value sqlite3_api->result_value
  88124. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  88125. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  88126. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  88127. #define sqlite3_snprintf sqlite3_api->snprintf
  88128. #define sqlite3_step sqlite3_api->step
  88129. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  88130. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  88131. #define sqlite3_total_changes sqlite3_api->total_changes
  88132. #define sqlite3_trace sqlite3_api->trace
  88133. #ifndef SQLITE_OMIT_DEPRECATED
  88134. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  88135. #endif
  88136. #define sqlite3_update_hook sqlite3_api->update_hook
  88137. #define sqlite3_user_data sqlite3_api->user_data
  88138. #define sqlite3_value_blob sqlite3_api->value_blob
  88139. #define sqlite3_value_bytes sqlite3_api->value_bytes
  88140. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  88141. #define sqlite3_value_double sqlite3_api->value_double
  88142. #define sqlite3_value_int sqlite3_api->value_int
  88143. #define sqlite3_value_int64 sqlite3_api->value_int64
  88144. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  88145. #define sqlite3_value_text sqlite3_api->value_text
  88146. #define sqlite3_value_text16 sqlite3_api->value_text16
  88147. #define sqlite3_value_text16be sqlite3_api->value_text16be
  88148. #define sqlite3_value_text16le sqlite3_api->value_text16le
  88149. #define sqlite3_value_type sqlite3_api->value_type
  88150. #define sqlite3_vmprintf sqlite3_api->vmprintf
  88151. #define sqlite3_overload_function sqlite3_api->overload_function
  88152. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  88153. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  88154. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  88155. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  88156. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  88157. #define sqlite3_blob_close sqlite3_api->blob_close
  88158. #define sqlite3_blob_open sqlite3_api->blob_open
  88159. #define sqlite3_blob_read sqlite3_api->blob_read
  88160. #define sqlite3_blob_write sqlite3_api->blob_write
  88161. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  88162. #define sqlite3_file_control sqlite3_api->file_control
  88163. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  88164. #define sqlite3_memory_used sqlite3_api->memory_used
  88165. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  88166. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  88167. #define sqlite3_mutex_free sqlite3_api->mutex_free
  88168. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  88169. #define sqlite3_mutex_try sqlite3_api->mutex_try
  88170. #define sqlite3_open_v2 sqlite3_api->open_v2
  88171. #define sqlite3_release_memory sqlite3_api->release_memory
  88172. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  88173. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  88174. #define sqlite3_sleep sqlite3_api->sleep
  88175. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  88176. #define sqlite3_vfs_find sqlite3_api->vfs_find
  88177. #define sqlite3_vfs_register sqlite3_api->vfs_register
  88178. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  88179. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  88180. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  88181. #define sqlite3_result_error_code sqlite3_api->result_error_code
  88182. #define sqlite3_test_control sqlite3_api->test_control
  88183. #define sqlite3_randomness sqlite3_api->randomness
  88184. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  88185. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  88186. #define sqlite3_limit sqlite3_api->limit
  88187. #define sqlite3_next_stmt sqlite3_api->next_stmt
  88188. #define sqlite3_sql sqlite3_api->sql
  88189. #define sqlite3_status sqlite3_api->status
  88190. #define sqlite3_backup_finish sqlite3_api->backup_finish
  88191. #define sqlite3_backup_init sqlite3_api->backup_init
  88192. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  88193. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  88194. #define sqlite3_backup_step sqlite3_api->backup_step
  88195. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  88196. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  88197. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  88198. #define sqlite3_db_config sqlite3_api->db_config
  88199. #define sqlite3_db_mutex sqlite3_api->db_mutex
  88200. #define sqlite3_db_status sqlite3_api->db_status
  88201. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  88202. #define sqlite3_log sqlite3_api->log
  88203. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  88204. #define sqlite3_sourceid sqlite3_api->sourceid
  88205. #define sqlite3_stmt_status sqlite3_api->stmt_status
  88206. #define sqlite3_strnicmp sqlite3_api->strnicmp
  88207. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  88208. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  88209. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  88210. #define sqlite3_wal_hook sqlite3_api->wal_hook
  88211. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  88212. #define sqlite3_vtab_config sqlite3_api->vtab_config
  88213. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  88214. /* Version 3.7.16 and later */
  88215. #define sqlite3_close_v2 sqlite3_api->close_v2
  88216. #define sqlite3_db_filename sqlite3_api->db_filename
  88217. #define sqlite3_db_readonly sqlite3_api->db_readonly
  88218. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  88219. #define sqlite3_errstr sqlite3_api->errstr
  88220. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  88221. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  88222. #define sqlite3_stricmp sqlite3_api->stricmp
  88223. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  88224. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  88225. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  88226. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  88227. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  88228. #endif /* SQLITE_CORE */
  88229. #ifndef SQLITE_CORE
  88230. /* This case when the file really is being compiled as a loadable
  88231. ** extension */
  88232. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  88233. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  88234. # define SQLITE_EXTENSION_INIT3 \
  88235. extern const sqlite3_api_routines *sqlite3_api;
  88236. #else
  88237. /* This case when the file is being statically linked into the
  88238. ** application */
  88239. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  88240. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  88241. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  88242. #endif
  88243. #endif /* _SQLITE3EXT_H_ */
  88244. /************** End of sqlite3ext.h ******************************************/
  88245. /************** Continuing where we left off in loadext.c ********************/
  88246. /* #include <string.h> */
  88247. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  88248. /*
  88249. ** Some API routines are omitted when various features are
  88250. ** excluded from a build of SQLite. Substitute a NULL pointer
  88251. ** for any missing APIs.
  88252. */
  88253. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  88254. # define sqlite3_column_database_name 0
  88255. # define sqlite3_column_database_name16 0
  88256. # define sqlite3_column_table_name 0
  88257. # define sqlite3_column_table_name16 0
  88258. # define sqlite3_column_origin_name 0
  88259. # define sqlite3_column_origin_name16 0
  88260. # define sqlite3_table_column_metadata 0
  88261. #endif
  88262. #ifdef SQLITE_OMIT_AUTHORIZATION
  88263. # define sqlite3_set_authorizer 0
  88264. #endif
  88265. #ifdef SQLITE_OMIT_UTF16
  88266. # define sqlite3_bind_text16 0
  88267. # define sqlite3_collation_needed16 0
  88268. # define sqlite3_column_decltype16 0
  88269. # define sqlite3_column_name16 0
  88270. # define sqlite3_column_text16 0
  88271. # define sqlite3_complete16 0
  88272. # define sqlite3_create_collation16 0
  88273. # define sqlite3_create_function16 0
  88274. # define sqlite3_errmsg16 0
  88275. # define sqlite3_open16 0
  88276. # define sqlite3_prepare16 0
  88277. # define sqlite3_prepare16_v2 0
  88278. # define sqlite3_result_error16 0
  88279. # define sqlite3_result_text16 0
  88280. # define sqlite3_result_text16be 0
  88281. # define sqlite3_result_text16le 0
  88282. # define sqlite3_value_text16 0
  88283. # define sqlite3_value_text16be 0
  88284. # define sqlite3_value_text16le 0
  88285. # define sqlite3_column_database_name16 0
  88286. # define sqlite3_column_table_name16 0
  88287. # define sqlite3_column_origin_name16 0
  88288. #endif
  88289. #ifdef SQLITE_OMIT_COMPLETE
  88290. # define sqlite3_complete 0
  88291. # define sqlite3_complete16 0
  88292. #endif
  88293. #ifdef SQLITE_OMIT_DECLTYPE
  88294. # define sqlite3_column_decltype16 0
  88295. # define sqlite3_column_decltype 0
  88296. #endif
  88297. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  88298. # define sqlite3_progress_handler 0
  88299. #endif
  88300. #ifdef SQLITE_OMIT_VIRTUALTABLE
  88301. # define sqlite3_create_module 0
  88302. # define sqlite3_create_module_v2 0
  88303. # define sqlite3_declare_vtab 0
  88304. # define sqlite3_vtab_config 0
  88305. # define sqlite3_vtab_on_conflict 0
  88306. #endif
  88307. #ifdef SQLITE_OMIT_SHARED_CACHE
  88308. # define sqlite3_enable_shared_cache 0
  88309. #endif
  88310. #ifdef SQLITE_OMIT_TRACE
  88311. # define sqlite3_profile 0
  88312. # define sqlite3_trace 0
  88313. #endif
  88314. #ifdef SQLITE_OMIT_GET_TABLE
  88315. # define sqlite3_free_table 0
  88316. # define sqlite3_get_table 0
  88317. #endif
  88318. #ifdef SQLITE_OMIT_INCRBLOB
  88319. #define sqlite3_bind_zeroblob 0
  88320. #define sqlite3_blob_bytes 0
  88321. #define sqlite3_blob_close 0
  88322. #define sqlite3_blob_open 0
  88323. #define sqlite3_blob_read 0
  88324. #define sqlite3_blob_write 0
  88325. #define sqlite3_blob_reopen 0
  88326. #endif
  88327. /*
  88328. ** The following structure contains pointers to all SQLite API routines.
  88329. ** A pointer to this structure is passed into extensions when they are
  88330. ** loaded so that the extension can make calls back into the SQLite
  88331. ** library.
  88332. **
  88333. ** When adding new APIs, add them to the bottom of this structure
  88334. ** in order to preserve backwards compatibility.
  88335. **
  88336. ** Extensions that use newer APIs should first call the
  88337. ** sqlite3_libversion_number() to make sure that the API they
  88338. ** intend to use is supported by the library. Extensions should
  88339. ** also check to make sure that the pointer to the function is
  88340. ** not NULL before calling it.
  88341. */
  88342. static const sqlite3_api_routines sqlite3Apis = {
  88343. sqlite3_aggregate_context,
  88344. #ifndef SQLITE_OMIT_DEPRECATED
  88345. sqlite3_aggregate_count,
  88346. #else
  88347. 0,
  88348. #endif
  88349. sqlite3_bind_blob,
  88350. sqlite3_bind_double,
  88351. sqlite3_bind_int,
  88352. sqlite3_bind_int64,
  88353. sqlite3_bind_null,
  88354. sqlite3_bind_parameter_count,
  88355. sqlite3_bind_parameter_index,
  88356. sqlite3_bind_parameter_name,
  88357. sqlite3_bind_text,
  88358. sqlite3_bind_text16,
  88359. sqlite3_bind_value,
  88360. sqlite3_busy_handler,
  88361. sqlite3_busy_timeout,
  88362. sqlite3_changes,
  88363. sqlite3_close,
  88364. sqlite3_collation_needed,
  88365. sqlite3_collation_needed16,
  88366. sqlite3_column_blob,
  88367. sqlite3_column_bytes,
  88368. sqlite3_column_bytes16,
  88369. sqlite3_column_count,
  88370. sqlite3_column_database_name,
  88371. sqlite3_column_database_name16,
  88372. sqlite3_column_decltype,
  88373. sqlite3_column_decltype16,
  88374. sqlite3_column_double,
  88375. sqlite3_column_int,
  88376. sqlite3_column_int64,
  88377. sqlite3_column_name,
  88378. sqlite3_column_name16,
  88379. sqlite3_column_origin_name,
  88380. sqlite3_column_origin_name16,
  88381. sqlite3_column_table_name,
  88382. sqlite3_column_table_name16,
  88383. sqlite3_column_text,
  88384. sqlite3_column_text16,
  88385. sqlite3_column_type,
  88386. sqlite3_column_value,
  88387. sqlite3_commit_hook,
  88388. sqlite3_complete,
  88389. sqlite3_complete16,
  88390. sqlite3_create_collation,
  88391. sqlite3_create_collation16,
  88392. sqlite3_create_function,
  88393. sqlite3_create_function16,
  88394. sqlite3_create_module,
  88395. sqlite3_data_count,
  88396. sqlite3_db_handle,
  88397. sqlite3_declare_vtab,
  88398. sqlite3_enable_shared_cache,
  88399. sqlite3_errcode,
  88400. sqlite3_errmsg,
  88401. sqlite3_errmsg16,
  88402. sqlite3_exec,
  88403. #ifndef SQLITE_OMIT_DEPRECATED
  88404. sqlite3_expired,
  88405. #else
  88406. 0,
  88407. #endif
  88408. sqlite3_finalize,
  88409. sqlite3_free,
  88410. sqlite3_free_table,
  88411. sqlite3_get_autocommit,
  88412. sqlite3_get_auxdata,
  88413. sqlite3_get_table,
  88414. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  88415. sqlite3_interrupt,
  88416. sqlite3_last_insert_rowid,
  88417. sqlite3_libversion,
  88418. sqlite3_libversion_number,
  88419. sqlite3_malloc,
  88420. sqlite3_mprintf,
  88421. sqlite3_open,
  88422. sqlite3_open16,
  88423. sqlite3_prepare,
  88424. sqlite3_prepare16,
  88425. sqlite3_profile,
  88426. sqlite3_progress_handler,
  88427. sqlite3_realloc,
  88428. sqlite3_reset,
  88429. sqlite3_result_blob,
  88430. sqlite3_result_double,
  88431. sqlite3_result_error,
  88432. sqlite3_result_error16,
  88433. sqlite3_result_int,
  88434. sqlite3_result_int64,
  88435. sqlite3_result_null,
  88436. sqlite3_result_text,
  88437. sqlite3_result_text16,
  88438. sqlite3_result_text16be,
  88439. sqlite3_result_text16le,
  88440. sqlite3_result_value,
  88441. sqlite3_rollback_hook,
  88442. sqlite3_set_authorizer,
  88443. sqlite3_set_auxdata,
  88444. sqlite3_snprintf,
  88445. sqlite3_step,
  88446. sqlite3_table_column_metadata,
  88447. #ifndef SQLITE_OMIT_DEPRECATED
  88448. sqlite3_thread_cleanup,
  88449. #else
  88450. 0,
  88451. #endif
  88452. sqlite3_total_changes,
  88453. sqlite3_trace,
  88454. #ifndef SQLITE_OMIT_DEPRECATED
  88455. sqlite3_transfer_bindings,
  88456. #else
  88457. 0,
  88458. #endif
  88459. sqlite3_update_hook,
  88460. sqlite3_user_data,
  88461. sqlite3_value_blob,
  88462. sqlite3_value_bytes,
  88463. sqlite3_value_bytes16,
  88464. sqlite3_value_double,
  88465. sqlite3_value_int,
  88466. sqlite3_value_int64,
  88467. sqlite3_value_numeric_type,
  88468. sqlite3_value_text,
  88469. sqlite3_value_text16,
  88470. sqlite3_value_text16be,
  88471. sqlite3_value_text16le,
  88472. sqlite3_value_type,
  88473. sqlite3_vmprintf,
  88474. /*
  88475. ** The original API set ends here. All extensions can call any
  88476. ** of the APIs above provided that the pointer is not NULL. But
  88477. ** before calling APIs that follow, extension should check the
  88478. ** sqlite3_libversion_number() to make sure they are dealing with
  88479. ** a library that is new enough to support that API.
  88480. *************************************************************************
  88481. */
  88482. sqlite3_overload_function,
  88483. /*
  88484. ** Added after 3.3.13
  88485. */
  88486. sqlite3_prepare_v2,
  88487. sqlite3_prepare16_v2,
  88488. sqlite3_clear_bindings,
  88489. /*
  88490. ** Added for 3.4.1
  88491. */
  88492. sqlite3_create_module_v2,
  88493. /*
  88494. ** Added for 3.5.0
  88495. */
  88496. sqlite3_bind_zeroblob,
  88497. sqlite3_blob_bytes,
  88498. sqlite3_blob_close,
  88499. sqlite3_blob_open,
  88500. sqlite3_blob_read,
  88501. sqlite3_blob_write,
  88502. sqlite3_create_collation_v2,
  88503. sqlite3_file_control,
  88504. sqlite3_memory_highwater,
  88505. sqlite3_memory_used,
  88506. #ifdef SQLITE_MUTEX_OMIT
  88507. 0,
  88508. 0,
  88509. 0,
  88510. 0,
  88511. 0,
  88512. #else
  88513. sqlite3_mutex_alloc,
  88514. sqlite3_mutex_enter,
  88515. sqlite3_mutex_free,
  88516. sqlite3_mutex_leave,
  88517. sqlite3_mutex_try,
  88518. #endif
  88519. sqlite3_open_v2,
  88520. sqlite3_release_memory,
  88521. sqlite3_result_error_nomem,
  88522. sqlite3_result_error_toobig,
  88523. sqlite3_sleep,
  88524. sqlite3_soft_heap_limit,
  88525. sqlite3_vfs_find,
  88526. sqlite3_vfs_register,
  88527. sqlite3_vfs_unregister,
  88528. /*
  88529. ** Added for 3.5.8
  88530. */
  88531. sqlite3_threadsafe,
  88532. sqlite3_result_zeroblob,
  88533. sqlite3_result_error_code,
  88534. sqlite3_test_control,
  88535. sqlite3_randomness,
  88536. sqlite3_context_db_handle,
  88537. /*
  88538. ** Added for 3.6.0
  88539. */
  88540. sqlite3_extended_result_codes,
  88541. sqlite3_limit,
  88542. sqlite3_next_stmt,
  88543. sqlite3_sql,
  88544. sqlite3_status,
  88545. /*
  88546. ** Added for 3.7.4
  88547. */
  88548. sqlite3_backup_finish,
  88549. sqlite3_backup_init,
  88550. sqlite3_backup_pagecount,
  88551. sqlite3_backup_remaining,
  88552. sqlite3_backup_step,
  88553. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  88554. sqlite3_compileoption_get,
  88555. sqlite3_compileoption_used,
  88556. #else
  88557. 0,
  88558. 0,
  88559. #endif
  88560. sqlite3_create_function_v2,
  88561. sqlite3_db_config,
  88562. sqlite3_db_mutex,
  88563. sqlite3_db_status,
  88564. sqlite3_extended_errcode,
  88565. sqlite3_log,
  88566. sqlite3_soft_heap_limit64,
  88567. sqlite3_sourceid,
  88568. sqlite3_stmt_status,
  88569. sqlite3_strnicmp,
  88570. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  88571. sqlite3_unlock_notify,
  88572. #else
  88573. 0,
  88574. #endif
  88575. #ifndef SQLITE_OMIT_WAL
  88576. sqlite3_wal_autocheckpoint,
  88577. sqlite3_wal_checkpoint,
  88578. sqlite3_wal_hook,
  88579. #else
  88580. 0,
  88581. 0,
  88582. 0,
  88583. #endif
  88584. sqlite3_blob_reopen,
  88585. sqlite3_vtab_config,
  88586. sqlite3_vtab_on_conflict,
  88587. sqlite3_close_v2,
  88588. sqlite3_db_filename,
  88589. sqlite3_db_readonly,
  88590. sqlite3_db_release_memory,
  88591. sqlite3_errstr,
  88592. sqlite3_stmt_busy,
  88593. sqlite3_stmt_readonly,
  88594. sqlite3_stricmp,
  88595. sqlite3_uri_boolean,
  88596. sqlite3_uri_int64,
  88597. sqlite3_uri_parameter,
  88598. sqlite3_vsnprintf,
  88599. sqlite3_wal_checkpoint_v2
  88600. };
  88601. /*
  88602. ** Attempt to load an SQLite extension library contained in the file
  88603. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  88604. ** default entry point name (sqlite3_extension_init) is used. Use
  88605. ** of the default name is recommended.
  88606. **
  88607. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  88608. **
  88609. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  88610. ** error message text. The calling function should free this memory
  88611. ** by calling sqlite3DbFree(db, ).
  88612. */
  88613. static int sqlite3LoadExtension(
  88614. sqlite3 *db, /* Load the extension into this database connection */
  88615. const char *zFile, /* Name of the shared library containing extension */
  88616. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  88617. char **pzErrMsg /* Put error message here if not 0 */
  88618. ){
  88619. sqlite3_vfs *pVfs = db->pVfs;
  88620. void *handle;
  88621. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  88622. char *zErrmsg = 0;
  88623. const char *zEntry;
  88624. char *zAltEntry = 0;
  88625. void **aHandle;
  88626. int nMsg = 300 + sqlite3Strlen30(zFile);
  88627. int ii;
  88628. /* Shared library endings to try if zFile cannot be loaded as written */
  88629. static const char *azEndings[] = {
  88630. #if SQLITE_OS_WIN
  88631. "dll"
  88632. #elif defined(__APPLE__)
  88633. "dylib"
  88634. #else
  88635. "so"
  88636. #endif
  88637. };
  88638. if( pzErrMsg ) *pzErrMsg = 0;
  88639. /* Ticket #1863. To avoid a creating security problems for older
  88640. ** applications that relink against newer versions of SQLite, the
  88641. ** ability to run load_extension is turned off by default. One
  88642. ** must call sqlite3_enable_load_extension() to turn on extension
  88643. ** loading. Otherwise you get the following error.
  88644. */
  88645. if( (db->flags & SQLITE_LoadExtension)==0 ){
  88646. if( pzErrMsg ){
  88647. *pzErrMsg = sqlite3_mprintf("not authorized");
  88648. }
  88649. return SQLITE_ERROR;
  88650. }
  88651. zEntry = zProc ? zProc : "sqlite3_extension_init";
  88652. handle = sqlite3OsDlOpen(pVfs, zFile);
  88653. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  88654. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  88655. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  88656. if( zAltFile==0 ) return SQLITE_NOMEM;
  88657. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  88658. sqlite3_free(zAltFile);
  88659. }
  88660. #endif
  88661. if( handle==0 ){
  88662. if( pzErrMsg ){
  88663. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  88664. if( zErrmsg ){
  88665. sqlite3_snprintf(nMsg, zErrmsg,
  88666. "unable to open shared library [%s]", zFile);
  88667. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  88668. }
  88669. }
  88670. return SQLITE_ERROR;
  88671. }
  88672. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  88673. sqlite3OsDlSym(pVfs, handle, zEntry);
  88674. /* If no entry point was specified and the default legacy
  88675. ** entry point name "sqlite3_extension_init" was not found, then
  88676. ** construct an entry point name "sqlite3_X_init" where the X is
  88677. ** replaced by the lowercase value of every ASCII alphabetic
  88678. ** character in the filename after the last "/" upto the first ".",
  88679. ** and eliding the first three characters if they are "lib".
  88680. ** Examples:
  88681. **
  88682. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  88683. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  88684. */
  88685. if( xInit==0 && zProc==0 ){
  88686. int iFile, iEntry, c;
  88687. int ncFile = sqlite3Strlen30(zFile);
  88688. zAltEntry = sqlite3_malloc(ncFile+30);
  88689. if( zAltEntry==0 ){
  88690. sqlite3OsDlClose(pVfs, handle);
  88691. return SQLITE_NOMEM;
  88692. }
  88693. memcpy(zAltEntry, "sqlite3_", 8);
  88694. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  88695. iFile++;
  88696. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  88697. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  88698. if( sqlite3Isalpha(c) ){
  88699. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  88700. }
  88701. }
  88702. memcpy(zAltEntry+iEntry, "_init", 6);
  88703. zEntry = zAltEntry;
  88704. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  88705. sqlite3OsDlSym(pVfs, handle, zEntry);
  88706. }
  88707. if( xInit==0 ){
  88708. if( pzErrMsg ){
  88709. nMsg += sqlite3Strlen30(zEntry);
  88710. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  88711. if( zErrmsg ){
  88712. sqlite3_snprintf(nMsg, zErrmsg,
  88713. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  88714. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  88715. }
  88716. }
  88717. sqlite3OsDlClose(pVfs, handle);
  88718. sqlite3_free(zAltEntry);
  88719. return SQLITE_ERROR;
  88720. }
  88721. sqlite3_free(zAltEntry);
  88722. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  88723. if( pzErrMsg ){
  88724. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  88725. }
  88726. sqlite3_free(zErrmsg);
  88727. sqlite3OsDlClose(pVfs, handle);
  88728. return SQLITE_ERROR;
  88729. }
  88730. /* Append the new shared library handle to the db->aExtension array. */
  88731. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  88732. if( aHandle==0 ){
  88733. return SQLITE_NOMEM;
  88734. }
  88735. if( db->nExtension>0 ){
  88736. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  88737. }
  88738. sqlite3DbFree(db, db->aExtension);
  88739. db->aExtension = aHandle;
  88740. db->aExtension[db->nExtension++] = handle;
  88741. return SQLITE_OK;
  88742. }
  88743. SQLITE_API int sqlite3_load_extension(
  88744. sqlite3 *db, /* Load the extension into this database connection */
  88745. const char *zFile, /* Name of the shared library containing extension */
  88746. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  88747. char **pzErrMsg /* Put error message here if not 0 */
  88748. ){
  88749. int rc;
  88750. sqlite3_mutex_enter(db->mutex);
  88751. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  88752. rc = sqlite3ApiExit(db, rc);
  88753. sqlite3_mutex_leave(db->mutex);
  88754. return rc;
  88755. }
  88756. /*
  88757. ** Call this routine when the database connection is closing in order
  88758. ** to clean up loaded extensions
  88759. */
  88760. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  88761. int i;
  88762. assert( sqlite3_mutex_held(db->mutex) );
  88763. for(i=0; i<db->nExtension; i++){
  88764. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  88765. }
  88766. sqlite3DbFree(db, db->aExtension);
  88767. }
  88768. /*
  88769. ** Enable or disable extension loading. Extension loading is disabled by
  88770. ** default so as not to open security holes in older applications.
  88771. */
  88772. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  88773. sqlite3_mutex_enter(db->mutex);
  88774. if( onoff ){
  88775. db->flags |= SQLITE_LoadExtension;
  88776. }else{
  88777. db->flags &= ~SQLITE_LoadExtension;
  88778. }
  88779. sqlite3_mutex_leave(db->mutex);
  88780. return SQLITE_OK;
  88781. }
  88782. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  88783. /*
  88784. ** The auto-extension code added regardless of whether or not extension
  88785. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  88786. ** code if regular extension loading is not available. This is that
  88787. ** dummy pointer.
  88788. */
  88789. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  88790. static const sqlite3_api_routines sqlite3Apis = { 0 };
  88791. #endif
  88792. /*
  88793. ** The following object holds the list of automatically loaded
  88794. ** extensions.
  88795. **
  88796. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  88797. ** mutex must be held while accessing this list.
  88798. */
  88799. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  88800. static SQLITE_WSD struct sqlite3AutoExtList {
  88801. int nExt; /* Number of entries in aExt[] */
  88802. void (**aExt)(void); /* Pointers to the extension init functions */
  88803. } sqlite3Autoext = { 0, 0 };
  88804. /* The "wsdAutoext" macro will resolve to the autoextension
  88805. ** state vector. If writable static data is unsupported on the target,
  88806. ** we have to locate the state vector at run-time. In the more common
  88807. ** case where writable static data is supported, wsdStat can refer directly
  88808. ** to the "sqlite3Autoext" state vector declared above.
  88809. */
  88810. #ifdef SQLITE_OMIT_WSD
  88811. # define wsdAutoextInit \
  88812. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  88813. # define wsdAutoext x[0]
  88814. #else
  88815. # define wsdAutoextInit
  88816. # define wsdAutoext sqlite3Autoext
  88817. #endif
  88818. /*
  88819. ** Register a statically linked extension that is automatically
  88820. ** loaded by every new database connection.
  88821. */
  88822. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  88823. int rc = SQLITE_OK;
  88824. #ifndef SQLITE_OMIT_AUTOINIT
  88825. rc = sqlite3_initialize();
  88826. if( rc ){
  88827. return rc;
  88828. }else
  88829. #endif
  88830. {
  88831. int i;
  88832. #if SQLITE_THREADSAFE
  88833. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  88834. #endif
  88835. wsdAutoextInit;
  88836. sqlite3_mutex_enter(mutex);
  88837. for(i=0; i<wsdAutoext.nExt; i++){
  88838. if( wsdAutoext.aExt[i]==xInit ) break;
  88839. }
  88840. if( i==wsdAutoext.nExt ){
  88841. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  88842. void (**aNew)(void);
  88843. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  88844. if( aNew==0 ){
  88845. rc = SQLITE_NOMEM;
  88846. }else{
  88847. wsdAutoext.aExt = aNew;
  88848. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  88849. wsdAutoext.nExt++;
  88850. }
  88851. }
  88852. sqlite3_mutex_leave(mutex);
  88853. assert( (rc&0xff)==rc );
  88854. return rc;
  88855. }
  88856. }
  88857. /*
  88858. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  88859. ** set of routines that is invoked for each new database connection, if it
  88860. ** is currently on the list. If xInit is not on the list, then this
  88861. ** routine is a no-op.
  88862. **
  88863. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  88864. ** was not on the list.
  88865. */
  88866. SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
  88867. #if SQLITE_THREADSAFE
  88868. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  88869. #endif
  88870. int i;
  88871. int n = 0;
  88872. wsdAutoextInit;
  88873. sqlite3_mutex_enter(mutex);
  88874. for(i=wsdAutoext.nExt-1; i>=0; i--){
  88875. if( wsdAutoext.aExt[i]==xInit ){
  88876. wsdAutoext.nExt--;
  88877. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  88878. n++;
  88879. break;
  88880. }
  88881. }
  88882. sqlite3_mutex_leave(mutex);
  88883. return n;
  88884. }
  88885. /*
  88886. ** Reset the automatic extension loading mechanism.
  88887. */
  88888. SQLITE_API void sqlite3_reset_auto_extension(void){
  88889. #ifndef SQLITE_OMIT_AUTOINIT
  88890. if( sqlite3_initialize()==SQLITE_OK )
  88891. #endif
  88892. {
  88893. #if SQLITE_THREADSAFE
  88894. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  88895. #endif
  88896. wsdAutoextInit;
  88897. sqlite3_mutex_enter(mutex);
  88898. sqlite3_free(wsdAutoext.aExt);
  88899. wsdAutoext.aExt = 0;
  88900. wsdAutoext.nExt = 0;
  88901. sqlite3_mutex_leave(mutex);
  88902. }
  88903. }
  88904. /*
  88905. ** Load all automatic extensions.
  88906. **
  88907. ** If anything goes wrong, set an error in the database connection.
  88908. */
  88909. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  88910. int i;
  88911. int go = 1;
  88912. int rc;
  88913. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  88914. wsdAutoextInit;
  88915. if( wsdAutoext.nExt==0 ){
  88916. /* Common case: early out without every having to acquire a mutex */
  88917. return;
  88918. }
  88919. for(i=0; go; i++){
  88920. char *zErrmsg;
  88921. #if SQLITE_THREADSAFE
  88922. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  88923. #endif
  88924. sqlite3_mutex_enter(mutex);
  88925. if( i>=wsdAutoext.nExt ){
  88926. xInit = 0;
  88927. go = 0;
  88928. }else{
  88929. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  88930. wsdAutoext.aExt[i];
  88931. }
  88932. sqlite3_mutex_leave(mutex);
  88933. zErrmsg = 0;
  88934. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  88935. sqlite3Error(db, rc,
  88936. "automatic extension loading failed: %s", zErrmsg);
  88937. go = 0;
  88938. }
  88939. sqlite3_free(zErrmsg);
  88940. }
  88941. }
  88942. /************** End of loadext.c *********************************************/
  88943. /************** Begin file pragma.c ******************************************/
  88944. /*
  88945. ** 2003 April 6
  88946. **
  88947. ** The author disclaims copyright to this source code. In place of
  88948. ** a legal notice, here is a blessing:
  88949. **
  88950. ** May you do good and not evil.
  88951. ** May you find forgiveness for yourself and forgive others.
  88952. ** May you share freely, never taking more than you give.
  88953. **
  88954. *************************************************************************
  88955. ** This file contains code used to implement the PRAGMA command.
  88956. */
  88957. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  88958. # if defined(__APPLE__)
  88959. # define SQLITE_ENABLE_LOCKING_STYLE 1
  88960. # else
  88961. # define SQLITE_ENABLE_LOCKING_STYLE 0
  88962. # endif
  88963. #endif
  88964. /***************************************************************************
  88965. ** The next block of code, including the PragTyp_XXXX macro definitions and
  88966. ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
  88967. **
  88968. ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
  88969. ** that script. Then copy/paste the output in place of the following:
  88970. */
  88971. #define PragTyp_HEADER_VALUE 0
  88972. #define PragTyp_AUTO_VACUUM 1
  88973. #define PragTyp_FLAG 2
  88974. #define PragTyp_BUSY_TIMEOUT 3
  88975. #define PragTyp_CACHE_SIZE 4
  88976. #define PragTyp_CASE_SENSITIVE_LIKE 5
  88977. #define PragTyp_COLLATION_LIST 6
  88978. #define PragTyp_COMPILE_OPTIONS 7
  88979. #define PragTyp_DATA_STORE_DIRECTORY 8
  88980. #define PragTyp_DATABASE_LIST 9
  88981. #define PragTyp_DEFAULT_CACHE_SIZE 10
  88982. #define PragTyp_ENCODING 11
  88983. #define PragTyp_FOREIGN_KEY_CHECK 12
  88984. #define PragTyp_FOREIGN_KEY_LIST 13
  88985. #define PragTyp_INCREMENTAL_VACUUM 14
  88986. #define PragTyp_INDEX_INFO 15
  88987. #define PragTyp_INDEX_LIST 16
  88988. #define PragTyp_INTEGRITY_CHECK 17
  88989. #define PragTyp_JOURNAL_MODE 18
  88990. #define PragTyp_JOURNAL_SIZE_LIMIT 19
  88991. #define PragTyp_LOCK_PROXY_FILE 20
  88992. #define PragTyp_LOCKING_MODE 21
  88993. #define PragTyp_PAGE_COUNT 22
  88994. #define PragTyp_MMAP_SIZE 23
  88995. #define PragTyp_PAGE_SIZE 24
  88996. #define PragTyp_SECURE_DELETE 25
  88997. #define PragTyp_SHRINK_MEMORY 26
  88998. #define PragTyp_SOFT_HEAP_LIMIT 27
  88999. #define PragTyp_STATS 28
  89000. #define PragTyp_SYNCHRONOUS 29
  89001. #define PragTyp_TABLE_INFO 30
  89002. #define PragTyp_TEMP_STORE 31
  89003. #define PragTyp_TEMP_STORE_DIRECTORY 32
  89004. #define PragTyp_WAL_AUTOCHECKPOINT 33
  89005. #define PragTyp_WAL_CHECKPOINT 34
  89006. #define PragTyp_ACTIVATE_EXTENSIONS 35
  89007. #define PragTyp_HEXKEY 36
  89008. #define PragTyp_KEY 37
  89009. #define PragTyp_REKEY 38
  89010. #define PragTyp_LOCK_STATUS 39
  89011. #define PragTyp_PARSER_TRACE 40
  89012. #define PragFlag_NeedSchema 0x01
  89013. static const struct sPragmaNames {
  89014. const char *const zName; /* Name of pragma */
  89015. u8 ePragTyp; /* PragTyp_XXX value */
  89016. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  89017. u32 iArg; /* Extra argument */
  89018. } aPragmaNames[] = {
  89019. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  89020. { /* zName: */ "activate_extensions",
  89021. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  89022. /* ePragFlag: */ 0,
  89023. /* iArg: */ 0 },
  89024. #endif
  89025. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  89026. { /* zName: */ "application_id",
  89027. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  89028. /* ePragFlag: */ 0,
  89029. /* iArg: */ 0 },
  89030. #endif
  89031. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  89032. { /* zName: */ "auto_vacuum",
  89033. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  89034. /* ePragFlag: */ PragFlag_NeedSchema,
  89035. /* iArg: */ 0 },
  89036. #endif
  89037. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  89038. { /* zName: */ "automatic_index",
  89039. /* ePragTyp: */ PragTyp_FLAG,
  89040. /* ePragFlag: */ 0,
  89041. /* iArg: */ SQLITE_AutoIndex },
  89042. #endif
  89043. { /* zName: */ "busy_timeout",
  89044. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  89045. /* ePragFlag: */ 0,
  89046. /* iArg: */ 0 },
  89047. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  89048. { /* zName: */ "cache_size",
  89049. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  89050. /* ePragFlag: */ PragFlag_NeedSchema,
  89051. /* iArg: */ 0 },
  89052. #endif
  89053. { /* zName: */ "cache_spill",
  89054. /* ePragTyp: */ PragTyp_FLAG,
  89055. /* ePragFlag: */ 0,
  89056. /* iArg: */ SQLITE_CacheSpill },
  89057. { /* zName: */ "case_sensitive_like",
  89058. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  89059. /* ePragFlag: */ 0,
  89060. /* iArg: */ 0 },
  89061. { /* zName: */ "checkpoint_fullfsync",
  89062. /* ePragTyp: */ PragTyp_FLAG,
  89063. /* ePragFlag: */ 0,
  89064. /* iArg: */ SQLITE_CkptFullFSync },
  89065. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  89066. { /* zName: */ "collation_list",
  89067. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  89068. /* ePragFlag: */ 0,
  89069. /* iArg: */ 0 },
  89070. #endif
  89071. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  89072. { /* zName: */ "compile_options",
  89073. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  89074. /* ePragFlag: */ 0,
  89075. /* iArg: */ 0 },
  89076. #endif
  89077. { /* zName: */ "count_changes",
  89078. /* ePragTyp: */ PragTyp_FLAG,
  89079. /* ePragFlag: */ 0,
  89080. /* iArg: */ SQLITE_CountRows },
  89081. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  89082. { /* zName: */ "data_store_directory",
  89083. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  89084. /* ePragFlag: */ 0,
  89085. /* iArg: */ 0 },
  89086. #endif
  89087. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  89088. { /* zName: */ "database_list",
  89089. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  89090. /* ePragFlag: */ PragFlag_NeedSchema,
  89091. /* iArg: */ 0 },
  89092. #endif
  89093. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  89094. { /* zName: */ "default_cache_size",
  89095. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  89096. /* ePragFlag: */ PragFlag_NeedSchema,
  89097. /* iArg: */ 0 },
  89098. #endif
  89099. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  89100. { /* zName: */ "defer_foreign_keys",
  89101. /* ePragTyp: */ PragTyp_FLAG,
  89102. /* ePragFlag: */ 0,
  89103. /* iArg: */ SQLITE_DeferFKs },
  89104. #endif
  89105. { /* zName: */ "empty_result_callbacks",
  89106. /* ePragTyp: */ PragTyp_FLAG,
  89107. /* ePragFlag: */ 0,
  89108. /* iArg: */ SQLITE_NullCallback },
  89109. #if !defined(SQLITE_OMIT_UTF16)
  89110. { /* zName: */ "encoding",
  89111. /* ePragTyp: */ PragTyp_ENCODING,
  89112. /* ePragFlag: */ 0,
  89113. /* iArg: */ 0 },
  89114. #endif
  89115. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  89116. { /* zName: */ "foreign_key_check",
  89117. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  89118. /* ePragFlag: */ PragFlag_NeedSchema,
  89119. /* iArg: */ 0 },
  89120. #endif
  89121. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  89122. { /* zName: */ "foreign_key_list",
  89123. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  89124. /* ePragFlag: */ PragFlag_NeedSchema,
  89125. /* iArg: */ 0 },
  89126. #endif
  89127. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  89128. { /* zName: */ "foreign_keys",
  89129. /* ePragTyp: */ PragTyp_FLAG,
  89130. /* ePragFlag: */ 0,
  89131. /* iArg: */ SQLITE_ForeignKeys },
  89132. #endif
  89133. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  89134. { /* zName: */ "freelist_count",
  89135. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  89136. /* ePragFlag: */ 0,
  89137. /* iArg: */ 0 },
  89138. #endif
  89139. { /* zName: */ "full_column_names",
  89140. /* ePragTyp: */ PragTyp_FLAG,
  89141. /* ePragFlag: */ 0,
  89142. /* iArg: */ SQLITE_FullColNames },
  89143. { /* zName: */ "fullfsync",
  89144. /* ePragTyp: */ PragTyp_FLAG,
  89145. /* ePragFlag: */ 0,
  89146. /* iArg: */ SQLITE_FullFSync },
  89147. #if defined(SQLITE_HAS_CODEC)
  89148. { /* zName: */ "hexkey",
  89149. /* ePragTyp: */ PragTyp_HEXKEY,
  89150. /* ePragFlag: */ 0,
  89151. /* iArg: */ 0 },
  89152. { /* zName: */ "hexrekey",
  89153. /* ePragTyp: */ PragTyp_HEXKEY,
  89154. /* ePragFlag: */ 0,
  89155. /* iArg: */ 0 },
  89156. #endif
  89157. #if !defined(SQLITE_OMIT_CHECK)
  89158. { /* zName: */ "ignore_check_constraints",
  89159. /* ePragTyp: */ PragTyp_FLAG,
  89160. /* ePragFlag: */ 0,
  89161. /* iArg: */ SQLITE_IgnoreChecks },
  89162. #endif
  89163. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  89164. { /* zName: */ "incremental_vacuum",
  89165. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  89166. /* ePragFlag: */ PragFlag_NeedSchema,
  89167. /* iArg: */ 0 },
  89168. #endif
  89169. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  89170. { /* zName: */ "index_info",
  89171. /* ePragTyp: */ PragTyp_INDEX_INFO,
  89172. /* ePragFlag: */ PragFlag_NeedSchema,
  89173. /* iArg: */ 0 },
  89174. { /* zName: */ "index_list",
  89175. /* ePragTyp: */ PragTyp_INDEX_LIST,
  89176. /* ePragFlag: */ PragFlag_NeedSchema,
  89177. /* iArg: */ 0 },
  89178. #endif
  89179. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  89180. { /* zName: */ "integrity_check",
  89181. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  89182. /* ePragFlag: */ PragFlag_NeedSchema,
  89183. /* iArg: */ 0 },
  89184. #endif
  89185. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  89186. { /* zName: */ "journal_mode",
  89187. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  89188. /* ePragFlag: */ PragFlag_NeedSchema,
  89189. /* iArg: */ 0 },
  89190. { /* zName: */ "journal_size_limit",
  89191. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  89192. /* ePragFlag: */ 0,
  89193. /* iArg: */ 0 },
  89194. #endif
  89195. #if defined(SQLITE_HAS_CODEC)
  89196. { /* zName: */ "key",
  89197. /* ePragTyp: */ PragTyp_KEY,
  89198. /* ePragFlag: */ 0,
  89199. /* iArg: */ 0 },
  89200. #endif
  89201. { /* zName: */ "legacy_file_format",
  89202. /* ePragTyp: */ PragTyp_FLAG,
  89203. /* ePragFlag: */ 0,
  89204. /* iArg: */ SQLITE_LegacyFileFmt },
  89205. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  89206. { /* zName: */ "lock_proxy_file",
  89207. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  89208. /* ePragFlag: */ 0,
  89209. /* iArg: */ 0 },
  89210. #endif
  89211. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  89212. { /* zName: */ "lock_status",
  89213. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  89214. /* ePragFlag: */ 0,
  89215. /* iArg: */ 0 },
  89216. #endif
  89217. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  89218. { /* zName: */ "locking_mode",
  89219. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  89220. /* ePragFlag: */ 0,
  89221. /* iArg: */ 0 },
  89222. { /* zName: */ "max_page_count",
  89223. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  89224. /* ePragFlag: */ PragFlag_NeedSchema,
  89225. /* iArg: */ 0 },
  89226. { /* zName: */ "mmap_size",
  89227. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  89228. /* ePragFlag: */ 0,
  89229. /* iArg: */ 0 },
  89230. { /* zName: */ "page_count",
  89231. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  89232. /* ePragFlag: */ PragFlag_NeedSchema,
  89233. /* iArg: */ 0 },
  89234. { /* zName: */ "page_size",
  89235. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  89236. /* ePragFlag: */ 0,
  89237. /* iArg: */ 0 },
  89238. #endif
  89239. #if defined(SQLITE_DEBUG)
  89240. { /* zName: */ "parser_trace",
  89241. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  89242. /* ePragFlag: */ 0,
  89243. /* iArg: */ 0 },
  89244. #endif
  89245. { /* zName: */ "query_only",
  89246. /* ePragTyp: */ PragTyp_FLAG,
  89247. /* ePragFlag: */ 0,
  89248. /* iArg: */ SQLITE_QueryOnly },
  89249. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  89250. { /* zName: */ "quick_check",
  89251. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  89252. /* ePragFlag: */ PragFlag_NeedSchema,
  89253. /* iArg: */ 0 },
  89254. #endif
  89255. { /* zName: */ "read_uncommitted",
  89256. /* ePragTyp: */ PragTyp_FLAG,
  89257. /* ePragFlag: */ 0,
  89258. /* iArg: */ SQLITE_ReadUncommitted },
  89259. { /* zName: */ "recursive_triggers",
  89260. /* ePragTyp: */ PragTyp_FLAG,
  89261. /* ePragFlag: */ 0,
  89262. /* iArg: */ SQLITE_RecTriggers },
  89263. #if defined(SQLITE_HAS_CODEC)
  89264. { /* zName: */ "rekey",
  89265. /* ePragTyp: */ PragTyp_REKEY,
  89266. /* ePragFlag: */ 0,
  89267. /* iArg: */ 0 },
  89268. #endif
  89269. { /* zName: */ "reverse_unordered_selects",
  89270. /* ePragTyp: */ PragTyp_FLAG,
  89271. /* ePragFlag: */ 0,
  89272. /* iArg: */ SQLITE_ReverseOrder },
  89273. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  89274. { /* zName: */ "schema_version",
  89275. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  89276. /* ePragFlag: */ 0,
  89277. /* iArg: */ 0 },
  89278. #endif
  89279. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  89280. { /* zName: */ "secure_delete",
  89281. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  89282. /* ePragFlag: */ 0,
  89283. /* iArg: */ 0 },
  89284. #endif
  89285. { /* zName: */ "short_column_names",
  89286. /* ePragTyp: */ PragTyp_FLAG,
  89287. /* ePragFlag: */ 0,
  89288. /* iArg: */ SQLITE_ShortColNames },
  89289. { /* zName: */ "shrink_memory",
  89290. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  89291. /* ePragFlag: */ 0,
  89292. /* iArg: */ 0 },
  89293. { /* zName: */ "soft_heap_limit",
  89294. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  89295. /* ePragFlag: */ 0,
  89296. /* iArg: */ 0 },
  89297. #if defined(SQLITE_DEBUG)
  89298. { /* zName: */ "sql_trace",
  89299. /* ePragTyp: */ PragTyp_FLAG,
  89300. /* ePragFlag: */ 0,
  89301. /* iArg: */ SQLITE_SqlTrace },
  89302. #endif
  89303. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  89304. { /* zName: */ "stats",
  89305. /* ePragTyp: */ PragTyp_STATS,
  89306. /* ePragFlag: */ PragFlag_NeedSchema,
  89307. /* iArg: */ 0 },
  89308. #endif
  89309. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  89310. { /* zName: */ "synchronous",
  89311. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  89312. /* ePragFlag: */ PragFlag_NeedSchema,
  89313. /* iArg: */ 0 },
  89314. #endif
  89315. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  89316. { /* zName: */ "table_info",
  89317. /* ePragTyp: */ PragTyp_TABLE_INFO,
  89318. /* ePragFlag: */ PragFlag_NeedSchema,
  89319. /* iArg: */ 0 },
  89320. #endif
  89321. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  89322. { /* zName: */ "temp_store",
  89323. /* ePragTyp: */ PragTyp_TEMP_STORE,
  89324. /* ePragFlag: */ 0,
  89325. /* iArg: */ 0 },
  89326. { /* zName: */ "temp_store_directory",
  89327. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  89328. /* ePragFlag: */ 0,
  89329. /* iArg: */ 0 },
  89330. #endif
  89331. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  89332. { /* zName: */ "user_version",
  89333. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  89334. /* ePragFlag: */ 0,
  89335. /* iArg: */ 0 },
  89336. #endif
  89337. #if defined(SQLITE_DEBUG)
  89338. { /* zName: */ "vdbe_addoptrace",
  89339. /* ePragTyp: */ PragTyp_FLAG,
  89340. /* ePragFlag: */ 0,
  89341. /* iArg: */ SQLITE_VdbeAddopTrace },
  89342. { /* zName: */ "vdbe_debug",
  89343. /* ePragTyp: */ PragTyp_FLAG,
  89344. /* ePragFlag: */ 0,
  89345. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  89346. { /* zName: */ "vdbe_listing",
  89347. /* ePragTyp: */ PragTyp_FLAG,
  89348. /* ePragFlag: */ 0,
  89349. /* iArg: */ SQLITE_VdbeListing },
  89350. { /* zName: */ "vdbe_trace",
  89351. /* ePragTyp: */ PragTyp_FLAG,
  89352. /* ePragFlag: */ 0,
  89353. /* iArg: */ SQLITE_VdbeTrace },
  89354. #endif
  89355. #if !defined(SQLITE_OMIT_WAL)
  89356. { /* zName: */ "wal_autocheckpoint",
  89357. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  89358. /* ePragFlag: */ 0,
  89359. /* iArg: */ 0 },
  89360. { /* zName: */ "wal_checkpoint",
  89361. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  89362. /* ePragFlag: */ PragFlag_NeedSchema,
  89363. /* iArg: */ 0 },
  89364. #endif
  89365. { /* zName: */ "writable_schema",
  89366. /* ePragTyp: */ PragTyp_FLAG,
  89367. /* ePragFlag: */ 0,
  89368. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  89369. };
  89370. /* Number of pragmas: 56 on by default, 68 total. */
  89371. /* End of the automatically generated pragma table.
  89372. ***************************************************************************/
  89373. /*
  89374. ** Interpret the given string as a safety level. Return 0 for OFF,
  89375. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  89376. ** unrecognized string argument. The FULL option is disallowed
  89377. ** if the omitFull parameter it 1.
  89378. **
  89379. ** Note that the values returned are one less that the values that
  89380. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  89381. ** to support legacy SQL code. The safety level used to be boolean
  89382. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  89383. */
  89384. static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
  89385. /* 123456789 123456789 */
  89386. static const char zText[] = "onoffalseyestruefull";
  89387. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  89388. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  89389. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  89390. int i, n;
  89391. if( sqlite3Isdigit(*z) ){
  89392. return (u8)sqlite3Atoi(z);
  89393. }
  89394. n = sqlite3Strlen30(z);
  89395. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  89396. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  89397. return iValue[i];
  89398. }
  89399. }
  89400. return dflt;
  89401. }
  89402. /*
  89403. ** Interpret the given string as a boolean value.
  89404. */
  89405. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
  89406. return getSafetyLevel(z,1,dflt)!=0;
  89407. }
  89408. /* The sqlite3GetBoolean() function is used by other modules but the
  89409. ** remainder of this file is specific to PRAGMA processing. So omit
  89410. ** the rest of the file if PRAGMAs are omitted from the build.
  89411. */
  89412. #if !defined(SQLITE_OMIT_PRAGMA)
  89413. /*
  89414. ** Interpret the given string as a locking mode value.
  89415. */
  89416. static int getLockingMode(const char *z){
  89417. if( z ){
  89418. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  89419. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  89420. }
  89421. return PAGER_LOCKINGMODE_QUERY;
  89422. }
  89423. #ifndef SQLITE_OMIT_AUTOVACUUM
  89424. /*
  89425. ** Interpret the given string as an auto-vacuum mode value.
  89426. **
  89427. ** The following strings, "none", "full" and "incremental" are
  89428. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  89429. */
  89430. static int getAutoVacuum(const char *z){
  89431. int i;
  89432. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  89433. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  89434. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  89435. i = sqlite3Atoi(z);
  89436. return (u8)((i>=0&&i<=2)?i:0);
  89437. }
  89438. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  89439. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  89440. /*
  89441. ** Interpret the given string as a temp db location. Return 1 for file
  89442. ** backed temporary databases, 2 for the Red-Black tree in memory database
  89443. ** and 0 to use the compile-time default.
  89444. */
  89445. static int getTempStore(const char *z){
  89446. if( z[0]>='0' && z[0]<='2' ){
  89447. return z[0] - '0';
  89448. }else if( sqlite3StrICmp(z, "file")==0 ){
  89449. return 1;
  89450. }else if( sqlite3StrICmp(z, "memory")==0 ){
  89451. return 2;
  89452. }else{
  89453. return 0;
  89454. }
  89455. }
  89456. #endif /* SQLITE_PAGER_PRAGMAS */
  89457. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  89458. /*
  89459. ** Invalidate temp storage, either when the temp storage is changed
  89460. ** from default, or when 'file' and the temp_store_directory has changed
  89461. */
  89462. static int invalidateTempStorage(Parse *pParse){
  89463. sqlite3 *db = pParse->db;
  89464. if( db->aDb[1].pBt!=0 ){
  89465. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  89466. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  89467. "from within a transaction");
  89468. return SQLITE_ERROR;
  89469. }
  89470. sqlite3BtreeClose(db->aDb[1].pBt);
  89471. db->aDb[1].pBt = 0;
  89472. sqlite3ResetAllSchemasOfConnection(db);
  89473. }
  89474. return SQLITE_OK;
  89475. }
  89476. #endif /* SQLITE_PAGER_PRAGMAS */
  89477. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  89478. /*
  89479. ** If the TEMP database is open, close it and mark the database schema
  89480. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  89481. ** or DEFAULT_TEMP_STORE pragmas.
  89482. */
  89483. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  89484. int ts = getTempStore(zStorageType);
  89485. sqlite3 *db = pParse->db;
  89486. if( db->temp_store==ts ) return SQLITE_OK;
  89487. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  89488. return SQLITE_ERROR;
  89489. }
  89490. db->temp_store = (u8)ts;
  89491. return SQLITE_OK;
  89492. }
  89493. #endif /* SQLITE_PAGER_PRAGMAS */
  89494. /*
  89495. ** Generate code to return a single integer value.
  89496. */
  89497. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  89498. Vdbe *v = sqlite3GetVdbe(pParse);
  89499. int mem = ++pParse->nMem;
  89500. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  89501. if( pI64 ){
  89502. memcpy(pI64, &value, sizeof(value));
  89503. }
  89504. sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  89505. sqlite3VdbeSetNumCols(v, 1);
  89506. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  89507. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  89508. }
  89509. /*
  89510. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  89511. ** set these values for all pagers.
  89512. */
  89513. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  89514. static void setAllPagerFlags(sqlite3 *db){
  89515. if( db->autoCommit ){
  89516. Db *pDb = db->aDb;
  89517. int n = db->nDb;
  89518. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  89519. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  89520. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  89521. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  89522. == PAGER_FLAGS_MASK );
  89523. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  89524. while( (n--) > 0 ){
  89525. if( pDb->pBt ){
  89526. sqlite3BtreeSetPagerFlags(pDb->pBt,
  89527. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  89528. }
  89529. pDb++;
  89530. }
  89531. }
  89532. }
  89533. #else
  89534. # define setAllPagerFlags(X) /* no-op */
  89535. #endif
  89536. /*
  89537. ** Return a human-readable name for a constraint resolution action.
  89538. */
  89539. #ifndef SQLITE_OMIT_FOREIGN_KEY
  89540. static const char *actionName(u8 action){
  89541. const char *zName;
  89542. switch( action ){
  89543. case OE_SetNull: zName = "SET NULL"; break;
  89544. case OE_SetDflt: zName = "SET DEFAULT"; break;
  89545. case OE_Cascade: zName = "CASCADE"; break;
  89546. case OE_Restrict: zName = "RESTRICT"; break;
  89547. default: zName = "NO ACTION";
  89548. assert( action==OE_None ); break;
  89549. }
  89550. return zName;
  89551. }
  89552. #endif
  89553. /*
  89554. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  89555. ** defined in pager.h. This function returns the associated lowercase
  89556. ** journal-mode name.
  89557. */
  89558. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  89559. static char * const azModeName[] = {
  89560. "delete", "persist", "off", "truncate", "memory"
  89561. #ifndef SQLITE_OMIT_WAL
  89562. , "wal"
  89563. #endif
  89564. };
  89565. assert( PAGER_JOURNALMODE_DELETE==0 );
  89566. assert( PAGER_JOURNALMODE_PERSIST==1 );
  89567. assert( PAGER_JOURNALMODE_OFF==2 );
  89568. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  89569. assert( PAGER_JOURNALMODE_MEMORY==4 );
  89570. assert( PAGER_JOURNALMODE_WAL==5 );
  89571. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  89572. if( eMode==ArraySize(azModeName) ) return 0;
  89573. return azModeName[eMode];
  89574. }
  89575. /*
  89576. ** Process a pragma statement.
  89577. **
  89578. ** Pragmas are of this form:
  89579. **
  89580. ** PRAGMA [database.]id [= value]
  89581. **
  89582. ** The identifier might also be a string. The value is a string, and
  89583. ** identifier, or a number. If minusFlag is true, then the value is
  89584. ** a number that was preceded by a minus sign.
  89585. **
  89586. ** If the left side is "database.id" then pId1 is the database name
  89587. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  89588. ** id and pId2 is any empty string.
  89589. */
  89590. SQLITE_PRIVATE void sqlite3Pragma(
  89591. Parse *pParse,
  89592. Token *pId1, /* First part of [database.]id field */
  89593. Token *pId2, /* Second part of [database.]id field, or NULL */
  89594. Token *pValue, /* Token for <value>, or NULL */
  89595. int minusFlag /* True if a '-' sign preceded <value> */
  89596. ){
  89597. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  89598. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  89599. const char *zDb = 0; /* The database name */
  89600. Token *pId; /* Pointer to <id> token */
  89601. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  89602. int iDb; /* Database index for <database> */
  89603. int lwr, upr, mid; /* Binary search bounds */
  89604. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  89605. sqlite3 *db = pParse->db; /* The database connection */
  89606. Db *pDb; /* The specific database being pragmaed */
  89607. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  89608. if( v==0 ) return;
  89609. sqlite3VdbeRunOnlyOnce(v);
  89610. pParse->nMem = 2;
  89611. /* Interpret the [database.] part of the pragma statement. iDb is the
  89612. ** index of the database this pragma is being applied to in db.aDb[]. */
  89613. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  89614. if( iDb<0 ) return;
  89615. pDb = &db->aDb[iDb];
  89616. /* If the temp database has been explicitly named as part of the
  89617. ** pragma, make sure it is open.
  89618. */
  89619. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  89620. return;
  89621. }
  89622. zLeft = sqlite3NameFromToken(db, pId);
  89623. if( !zLeft ) return;
  89624. if( minusFlag ){
  89625. zRight = sqlite3MPrintf(db, "-%T", pValue);
  89626. }else{
  89627. zRight = sqlite3NameFromToken(db, pValue);
  89628. }
  89629. assert( pId2 );
  89630. zDb = pId2->n>0 ? pDb->zName : 0;
  89631. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  89632. goto pragma_out;
  89633. }
  89634. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  89635. ** connection. If it returns SQLITE_OK, then assume that the VFS
  89636. ** handled the pragma and generate a no-op prepared statement.
  89637. */
  89638. aFcntl[0] = 0;
  89639. aFcntl[1] = zLeft;
  89640. aFcntl[2] = zRight;
  89641. aFcntl[3] = 0;
  89642. db->busyHandler.nBusy = 0;
  89643. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  89644. if( rc==SQLITE_OK ){
  89645. if( aFcntl[0] ){
  89646. int mem = ++pParse->nMem;
  89647. sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
  89648. sqlite3VdbeSetNumCols(v, 1);
  89649. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
  89650. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  89651. sqlite3_free(aFcntl[0]);
  89652. }
  89653. goto pragma_out;
  89654. }
  89655. if( rc!=SQLITE_NOTFOUND ){
  89656. if( aFcntl[0] ){
  89657. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  89658. sqlite3_free(aFcntl[0]);
  89659. }
  89660. pParse->nErr++;
  89661. pParse->rc = rc;
  89662. goto pragma_out;
  89663. }
  89664. /* Locate the pragma in the lookup table */
  89665. lwr = 0;
  89666. upr = ArraySize(aPragmaNames)-1;
  89667. while( lwr<=upr ){
  89668. mid = (lwr+upr)/2;
  89669. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  89670. if( rc==0 ) break;
  89671. if( rc<0 ){
  89672. upr = mid - 1;
  89673. }else{
  89674. lwr = mid + 1;
  89675. }
  89676. }
  89677. if( lwr>upr ) goto pragma_out;
  89678. /* Make sure the database schema is loaded if the pragma requires that */
  89679. if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
  89680. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  89681. }
  89682. /* Jump to the appropriate pragma handler */
  89683. switch( aPragmaNames[mid].ePragTyp ){
  89684. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  89685. /*
  89686. ** PRAGMA [database.]default_cache_size
  89687. ** PRAGMA [database.]default_cache_size=N
  89688. **
  89689. ** The first form reports the current persistent setting for the
  89690. ** page cache size. The value returned is the maximum number of
  89691. ** pages in the page cache. The second form sets both the current
  89692. ** page cache size value and the persistent page cache size value
  89693. ** stored in the database file.
  89694. **
  89695. ** Older versions of SQLite would set the default cache size to a
  89696. ** negative number to indicate synchronous=OFF. These days, synchronous
  89697. ** is always on by default regardless of the sign of the default cache
  89698. ** size. But continue to take the absolute value of the default cache
  89699. ** size of historical compatibility.
  89700. */
  89701. case PragTyp_DEFAULT_CACHE_SIZE: {
  89702. static const VdbeOpList getCacheSize[] = {
  89703. { OP_Transaction, 0, 0, 0}, /* 0 */
  89704. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  89705. { OP_IfPos, 1, 8, 0},
  89706. { OP_Integer, 0, 2, 0},
  89707. { OP_Subtract, 1, 2, 1},
  89708. { OP_IfPos, 1, 8, 0},
  89709. { OP_Integer, 0, 1, 0}, /* 6 */
  89710. { OP_Noop, 0, 0, 0},
  89711. { OP_ResultRow, 1, 1, 0},
  89712. };
  89713. int addr;
  89714. sqlite3VdbeUsesBtree(v, iDb);
  89715. if( !zRight ){
  89716. sqlite3VdbeSetNumCols(v, 1);
  89717. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  89718. pParse->nMem += 2;
  89719. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  89720. sqlite3VdbeChangeP1(v, addr, iDb);
  89721. sqlite3VdbeChangeP1(v, addr+1, iDb);
  89722. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  89723. }else{
  89724. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  89725. sqlite3BeginWriteOperation(pParse, 0, iDb);
  89726. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  89727. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  89728. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  89729. pDb->pSchema->cache_size = size;
  89730. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  89731. }
  89732. break;
  89733. }
  89734. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  89735. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  89736. /*
  89737. ** PRAGMA [database.]page_size
  89738. ** PRAGMA [database.]page_size=N
  89739. **
  89740. ** The first form reports the current setting for the
  89741. ** database page size in bytes. The second form sets the
  89742. ** database page size value. The value can only be set if
  89743. ** the database has not yet been created.
  89744. */
  89745. case PragTyp_PAGE_SIZE: {
  89746. Btree *pBt = pDb->pBt;
  89747. assert( pBt!=0 );
  89748. if( !zRight ){
  89749. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  89750. returnSingleInt(pParse, "page_size", size);
  89751. }else{
  89752. /* Malloc may fail when setting the page-size, as there is an internal
  89753. ** buffer that the pager module resizes using sqlite3_realloc().
  89754. */
  89755. db->nextPagesize = sqlite3Atoi(zRight);
  89756. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  89757. db->mallocFailed = 1;
  89758. }
  89759. }
  89760. break;
  89761. }
  89762. /*
  89763. ** PRAGMA [database.]secure_delete
  89764. ** PRAGMA [database.]secure_delete=ON/OFF
  89765. **
  89766. ** The first form reports the current setting for the
  89767. ** secure_delete flag. The second form changes the secure_delete
  89768. ** flag setting and reports thenew value.
  89769. */
  89770. case PragTyp_SECURE_DELETE: {
  89771. Btree *pBt = pDb->pBt;
  89772. int b = -1;
  89773. assert( pBt!=0 );
  89774. if( zRight ){
  89775. b = sqlite3GetBoolean(zRight, 0);
  89776. }
  89777. if( pId2->n==0 && b>=0 ){
  89778. int ii;
  89779. for(ii=0; ii<db->nDb; ii++){
  89780. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  89781. }
  89782. }
  89783. b = sqlite3BtreeSecureDelete(pBt, b);
  89784. returnSingleInt(pParse, "secure_delete", b);
  89785. break;
  89786. }
  89787. /*
  89788. ** PRAGMA [database.]max_page_count
  89789. ** PRAGMA [database.]max_page_count=N
  89790. **
  89791. ** The first form reports the current setting for the
  89792. ** maximum number of pages in the database file. The
  89793. ** second form attempts to change this setting. Both
  89794. ** forms return the current setting.
  89795. **
  89796. ** The absolute value of N is used. This is undocumented and might
  89797. ** change. The only purpose is to provide an easy way to test
  89798. ** the sqlite3AbsInt32() function.
  89799. **
  89800. ** PRAGMA [database.]page_count
  89801. **
  89802. ** Return the number of pages in the specified database.
  89803. */
  89804. case PragTyp_PAGE_COUNT: {
  89805. int iReg;
  89806. sqlite3CodeVerifySchema(pParse, iDb);
  89807. iReg = ++pParse->nMem;
  89808. if( sqlite3Tolower(zLeft[0])=='p' ){
  89809. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  89810. }else{
  89811. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  89812. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  89813. }
  89814. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  89815. sqlite3VdbeSetNumCols(v, 1);
  89816. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  89817. break;
  89818. }
  89819. /*
  89820. ** PRAGMA [database.]locking_mode
  89821. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  89822. */
  89823. case PragTyp_LOCKING_MODE: {
  89824. const char *zRet = "normal";
  89825. int eMode = getLockingMode(zRight);
  89826. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  89827. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  89828. ** the current default locking mode (which may be different to
  89829. ** the locking-mode of the main database).
  89830. */
  89831. eMode = db->dfltLockMode;
  89832. }else{
  89833. Pager *pPager;
  89834. if( pId2->n==0 ){
  89835. /* This indicates that no database name was specified as part
  89836. ** of the PRAGMA command. In this case the locking-mode must be
  89837. ** set on all attached databases, as well as the main db file.
  89838. **
  89839. ** Also, the sqlite3.dfltLockMode variable is set so that
  89840. ** any subsequently attached databases also use the specified
  89841. ** locking mode.
  89842. */
  89843. int ii;
  89844. assert(pDb==&db->aDb[0]);
  89845. for(ii=2; ii<db->nDb; ii++){
  89846. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  89847. sqlite3PagerLockingMode(pPager, eMode);
  89848. }
  89849. db->dfltLockMode = (u8)eMode;
  89850. }
  89851. pPager = sqlite3BtreePager(pDb->pBt);
  89852. eMode = sqlite3PagerLockingMode(pPager, eMode);
  89853. }
  89854. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  89855. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  89856. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  89857. zRet = "exclusive";
  89858. }
  89859. sqlite3VdbeSetNumCols(v, 1);
  89860. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  89861. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  89862. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  89863. break;
  89864. }
  89865. /*
  89866. ** PRAGMA [database.]journal_mode
  89867. ** PRAGMA [database.]journal_mode =
  89868. ** (delete|persist|off|truncate|memory|wal|off)
  89869. */
  89870. case PragTyp_JOURNAL_MODE: {
  89871. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  89872. int ii; /* Loop counter */
  89873. sqlite3VdbeSetNumCols(v, 1);
  89874. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  89875. if( zRight==0 ){
  89876. /* If there is no "=MODE" part of the pragma, do a query for the
  89877. ** current mode */
  89878. eMode = PAGER_JOURNALMODE_QUERY;
  89879. }else{
  89880. const char *zMode;
  89881. int n = sqlite3Strlen30(zRight);
  89882. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  89883. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  89884. }
  89885. if( !zMode ){
  89886. /* If the "=MODE" part does not match any known journal mode,
  89887. ** then do a query */
  89888. eMode = PAGER_JOURNALMODE_QUERY;
  89889. }
  89890. }
  89891. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  89892. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  89893. iDb = 0;
  89894. pId2->n = 1;
  89895. }
  89896. for(ii=db->nDb-1; ii>=0; ii--){
  89897. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  89898. sqlite3VdbeUsesBtree(v, ii);
  89899. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  89900. }
  89901. }
  89902. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  89903. break;
  89904. }
  89905. /*
  89906. ** PRAGMA [database.]journal_size_limit
  89907. ** PRAGMA [database.]journal_size_limit=N
  89908. **
  89909. ** Get or set the size limit on rollback journal files.
  89910. */
  89911. case PragTyp_JOURNAL_SIZE_LIMIT: {
  89912. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  89913. i64 iLimit = -2;
  89914. if( zRight ){
  89915. sqlite3Atoi64(zRight, &iLimit, sqlite3Strlen30(zRight), SQLITE_UTF8);
  89916. if( iLimit<-1 ) iLimit = -1;
  89917. }
  89918. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  89919. returnSingleInt(pParse, "journal_size_limit", iLimit);
  89920. break;
  89921. }
  89922. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  89923. /*
  89924. ** PRAGMA [database.]auto_vacuum
  89925. ** PRAGMA [database.]auto_vacuum=N
  89926. **
  89927. ** Get or set the value of the database 'auto-vacuum' parameter.
  89928. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  89929. */
  89930. #ifndef SQLITE_OMIT_AUTOVACUUM
  89931. case PragTyp_AUTO_VACUUM: {
  89932. Btree *pBt = pDb->pBt;
  89933. assert( pBt!=0 );
  89934. if( !zRight ){
  89935. returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  89936. }else{
  89937. int eAuto = getAutoVacuum(zRight);
  89938. assert( eAuto>=0 && eAuto<=2 );
  89939. db->nextAutovac = (u8)eAuto;
  89940. /* Call SetAutoVacuum() to set initialize the internal auto and
  89941. ** incr-vacuum flags. This is required in case this connection
  89942. ** creates the database file. It is important that it is created
  89943. ** as an auto-vacuum capable db.
  89944. */
  89945. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  89946. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  89947. /* When setting the auto_vacuum mode to either "full" or
  89948. ** "incremental", write the value of meta[6] in the database
  89949. ** file. Before writing to meta[6], check that meta[3] indicates
  89950. ** that this really is an auto-vacuum capable database.
  89951. */
  89952. static const VdbeOpList setMeta6[] = {
  89953. { OP_Transaction, 0, 1, 0}, /* 0 */
  89954. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  89955. { OP_If, 1, 0, 0}, /* 2 */
  89956. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  89957. { OP_Integer, 0, 1, 0}, /* 4 */
  89958. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  89959. };
  89960. int iAddr;
  89961. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
  89962. sqlite3VdbeChangeP1(v, iAddr, iDb);
  89963. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  89964. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  89965. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  89966. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  89967. sqlite3VdbeUsesBtree(v, iDb);
  89968. }
  89969. }
  89970. break;
  89971. }
  89972. #endif
  89973. /*
  89974. ** PRAGMA [database.]incremental_vacuum(N)
  89975. **
  89976. ** Do N steps of incremental vacuuming on a database.
  89977. */
  89978. #ifndef SQLITE_OMIT_AUTOVACUUM
  89979. case PragTyp_INCREMENTAL_VACUUM: {
  89980. int iLimit, addr;
  89981. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  89982. iLimit = 0x7fffffff;
  89983. }
  89984. sqlite3BeginWriteOperation(pParse, 0, iDb);
  89985. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  89986. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
  89987. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  89988. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  89989. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
  89990. sqlite3VdbeJumpHere(v, addr);
  89991. break;
  89992. }
  89993. #endif
  89994. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  89995. /*
  89996. ** PRAGMA [database.]cache_size
  89997. ** PRAGMA [database.]cache_size=N
  89998. **
  89999. ** The first form reports the current local setting for the
  90000. ** page cache size. The second form sets the local
  90001. ** page cache size value. If N is positive then that is the
  90002. ** number of pages in the cache. If N is negative, then the
  90003. ** number of pages is adjusted so that the cache uses -N kibibytes
  90004. ** of memory.
  90005. */
  90006. case PragTyp_CACHE_SIZE: {
  90007. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  90008. if( !zRight ){
  90009. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  90010. }else{
  90011. int size = sqlite3Atoi(zRight);
  90012. pDb->pSchema->cache_size = size;
  90013. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  90014. }
  90015. break;
  90016. }
  90017. /*
  90018. ** PRAGMA [database.]mmap_size(N)
  90019. **
  90020. ** Used to set mapping size limit. The mapping size limit is
  90021. ** used to limit the aggregate size of all memory mapped regions of the
  90022. ** database file. If this parameter is set to zero, then memory mapping
  90023. ** is not used at all. If N is negative, then the default memory map
  90024. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  90025. ** The parameter N is measured in bytes.
  90026. **
  90027. ** This value is advisory. The underlying VFS is free to memory map
  90028. ** as little or as much as it wants. Except, if N is set to 0 then the
  90029. ** upper layers will never invoke the xFetch interfaces to the VFS.
  90030. */
  90031. case PragTyp_MMAP_SIZE: {
  90032. sqlite3_int64 sz;
  90033. #if SQLITE_MAX_MMAP_SIZE>0
  90034. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  90035. if( zRight ){
  90036. int ii;
  90037. sqlite3Atoi64(zRight, &sz, sqlite3Strlen30(zRight), SQLITE_UTF8);
  90038. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  90039. if( pId2->n==0 ) db->szMmap = sz;
  90040. for(ii=db->nDb-1; ii>=0; ii--){
  90041. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  90042. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  90043. }
  90044. }
  90045. }
  90046. sz = -1;
  90047. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  90048. #else
  90049. sz = 0;
  90050. rc = SQLITE_OK;
  90051. #endif
  90052. if( rc==SQLITE_OK ){
  90053. returnSingleInt(pParse, "mmap_size", sz);
  90054. }else if( rc!=SQLITE_NOTFOUND ){
  90055. pParse->nErr++;
  90056. pParse->rc = rc;
  90057. }
  90058. break;
  90059. }
  90060. /*
  90061. ** PRAGMA temp_store
  90062. ** PRAGMA temp_store = "default"|"memory"|"file"
  90063. **
  90064. ** Return or set the local value of the temp_store flag. Changing
  90065. ** the local value does not make changes to the disk file and the default
  90066. ** value will be restored the next time the database is opened.
  90067. **
  90068. ** Note that it is possible for the library compile-time options to
  90069. ** override this setting
  90070. */
  90071. case PragTyp_TEMP_STORE: {
  90072. if( !zRight ){
  90073. returnSingleInt(pParse, "temp_store", db->temp_store);
  90074. }else{
  90075. changeTempStorage(pParse, zRight);
  90076. }
  90077. break;
  90078. }
  90079. /*
  90080. ** PRAGMA temp_store_directory
  90081. ** PRAGMA temp_store_directory = ""|"directory_name"
  90082. **
  90083. ** Return or set the local value of the temp_store_directory flag. Changing
  90084. ** the value sets a specific directory to be used for temporary files.
  90085. ** Setting to a null string reverts to the default temporary directory search.
  90086. ** If temporary directory is changed, then invalidateTempStorage.
  90087. **
  90088. */
  90089. case PragTyp_TEMP_STORE_DIRECTORY: {
  90090. if( !zRight ){
  90091. if( sqlite3_temp_directory ){
  90092. sqlite3VdbeSetNumCols(v, 1);
  90093. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  90094. "temp_store_directory", SQLITE_STATIC);
  90095. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  90096. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  90097. }
  90098. }else{
  90099. #ifndef SQLITE_OMIT_WSD
  90100. if( zRight[0] ){
  90101. int res;
  90102. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  90103. if( rc!=SQLITE_OK || res==0 ){
  90104. sqlite3ErrorMsg(pParse, "not a writable directory");
  90105. goto pragma_out;
  90106. }
  90107. }
  90108. if( SQLITE_TEMP_STORE==0
  90109. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  90110. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  90111. ){
  90112. invalidateTempStorage(pParse);
  90113. }
  90114. sqlite3_free(sqlite3_temp_directory);
  90115. if( zRight[0] ){
  90116. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  90117. }else{
  90118. sqlite3_temp_directory = 0;
  90119. }
  90120. #endif /* SQLITE_OMIT_WSD */
  90121. }
  90122. break;
  90123. }
  90124. #if SQLITE_OS_WIN
  90125. /*
  90126. ** PRAGMA data_store_directory
  90127. ** PRAGMA data_store_directory = ""|"directory_name"
  90128. **
  90129. ** Return or set the local value of the data_store_directory flag. Changing
  90130. ** the value sets a specific directory to be used for database files that
  90131. ** were specified with a relative pathname. Setting to a null string reverts
  90132. ** to the default database directory, which for database files specified with
  90133. ** a relative path will probably be based on the current directory for the
  90134. ** process. Database file specified with an absolute path are not impacted
  90135. ** by this setting, regardless of its value.
  90136. **
  90137. */
  90138. case PragTyp_DATA_STORE_DIRECTORY: {
  90139. if( !zRight ){
  90140. if( sqlite3_data_directory ){
  90141. sqlite3VdbeSetNumCols(v, 1);
  90142. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  90143. "data_store_directory", SQLITE_STATIC);
  90144. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
  90145. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  90146. }
  90147. }else{
  90148. #ifndef SQLITE_OMIT_WSD
  90149. if( zRight[0] ){
  90150. int res;
  90151. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  90152. if( rc!=SQLITE_OK || res==0 ){
  90153. sqlite3ErrorMsg(pParse, "not a writable directory");
  90154. goto pragma_out;
  90155. }
  90156. }
  90157. sqlite3_free(sqlite3_data_directory);
  90158. if( zRight[0] ){
  90159. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  90160. }else{
  90161. sqlite3_data_directory = 0;
  90162. }
  90163. #endif /* SQLITE_OMIT_WSD */
  90164. }
  90165. break;
  90166. }
  90167. #endif
  90168. #if SQLITE_ENABLE_LOCKING_STYLE
  90169. /*
  90170. ** PRAGMA [database.]lock_proxy_file
  90171. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  90172. **
  90173. ** Return or set the value of the lock_proxy_file flag. Changing
  90174. ** the value sets a specific file to be used for database access locks.
  90175. **
  90176. */
  90177. case PragTyp_LOCK_PROXY_FILE: {
  90178. if( !zRight ){
  90179. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  90180. char *proxy_file_path = NULL;
  90181. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  90182. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  90183. &proxy_file_path);
  90184. if( proxy_file_path ){
  90185. sqlite3VdbeSetNumCols(v, 1);
  90186. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  90187. "lock_proxy_file", SQLITE_STATIC);
  90188. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  90189. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  90190. }
  90191. }else{
  90192. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  90193. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  90194. int res;
  90195. if( zRight[0] ){
  90196. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  90197. zRight);
  90198. } else {
  90199. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  90200. NULL);
  90201. }
  90202. if( res!=SQLITE_OK ){
  90203. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  90204. goto pragma_out;
  90205. }
  90206. }
  90207. break;
  90208. }
  90209. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  90210. /*
  90211. ** PRAGMA [database.]synchronous
  90212. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  90213. **
  90214. ** Return or set the local value of the synchronous flag. Changing
  90215. ** the local value does not make changes to the disk file and the
  90216. ** default value will be restored the next time the database is
  90217. ** opened.
  90218. */
  90219. case PragTyp_SYNCHRONOUS: {
  90220. if( !zRight ){
  90221. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  90222. }else{
  90223. if( !db->autoCommit ){
  90224. sqlite3ErrorMsg(pParse,
  90225. "Safety level may not be changed inside a transaction");
  90226. }else{
  90227. pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
  90228. setAllPagerFlags(db);
  90229. }
  90230. }
  90231. break;
  90232. }
  90233. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  90234. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  90235. case PragTyp_FLAG: {
  90236. if( zRight==0 ){
  90237. returnSingleInt(pParse, aPragmaNames[mid].zName,
  90238. (db->flags & aPragmaNames[mid].iArg)!=0 );
  90239. }else{
  90240. int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */
  90241. if( db->autoCommit==0 ){
  90242. /* Foreign key support may not be enabled or disabled while not
  90243. ** in auto-commit mode. */
  90244. mask &= ~(SQLITE_ForeignKeys);
  90245. }
  90246. if( sqlite3GetBoolean(zRight, 0) ){
  90247. db->flags |= mask;
  90248. }else{
  90249. db->flags &= ~mask;
  90250. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  90251. }
  90252. /* Many of the flag-pragmas modify the code generated by the SQL
  90253. ** compiler (eg. count_changes). So add an opcode to expire all
  90254. ** compiled SQL statements after modifying a pragma value.
  90255. */
  90256. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  90257. setAllPagerFlags(db);
  90258. }
  90259. break;
  90260. }
  90261. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  90262. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  90263. /*
  90264. ** PRAGMA table_info(<table>)
  90265. **
  90266. ** Return a single row for each column of the named table. The columns of
  90267. ** the returned data set are:
  90268. **
  90269. ** cid: Column id (numbered from left to right, starting at 0)
  90270. ** name: Column name
  90271. ** type: Column declaration type.
  90272. ** notnull: True if 'NOT NULL' is part of column declaration
  90273. ** dflt_value: The default value for the column, if any.
  90274. */
  90275. case PragTyp_TABLE_INFO: if( zRight ){
  90276. Table *pTab;
  90277. pTab = sqlite3FindTable(db, zRight, zDb);
  90278. if( pTab ){
  90279. int i, k;
  90280. int nHidden = 0;
  90281. Column *pCol;
  90282. Index *pPk;
  90283. for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
  90284. sqlite3VdbeSetNumCols(v, 6);
  90285. pParse->nMem = 6;
  90286. sqlite3CodeVerifySchema(pParse, iDb);
  90287. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  90288. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  90289. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  90290. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  90291. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  90292. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  90293. sqlite3ViewGetColumnNames(pParse, pTab);
  90294. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  90295. if( IsHiddenColumn(pCol) ){
  90296. nHidden++;
  90297. continue;
  90298. }
  90299. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  90300. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  90301. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  90302. pCol->zType ? pCol->zType : "", 0);
  90303. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  90304. if( pCol->zDflt ){
  90305. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  90306. }else{
  90307. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  90308. }
  90309. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  90310. k = 0;
  90311. }else if( pPk==0 ){
  90312. k = 1;
  90313. }else{
  90314. for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
  90315. }
  90316. sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
  90317. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  90318. }
  90319. }
  90320. }
  90321. break;
  90322. case PragTyp_STATS: {
  90323. Index *pIdx;
  90324. HashElem *i;
  90325. v = sqlite3GetVdbe(pParse);
  90326. sqlite3VdbeSetNumCols(v, 4);
  90327. pParse->nMem = 4;
  90328. sqlite3CodeVerifySchema(pParse, iDb);
  90329. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  90330. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
  90331. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
  90332. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
  90333. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  90334. Table *pTab = sqliteHashData(i);
  90335. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
  90336. sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
  90337. sqlite3VdbeAddOp2(v, OP_Integer,
  90338. (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
  90339. sqlite3VdbeAddOp2(v, OP_Integer, (int)pTab->nRowEst, 4);
  90340. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  90341. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  90342. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  90343. sqlite3VdbeAddOp2(v, OP_Integer,
  90344. (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
  90345. sqlite3VdbeAddOp2(v, OP_Integer, (int)pIdx->aiRowEst[0], 4);
  90346. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  90347. }
  90348. }
  90349. }
  90350. break;
  90351. case PragTyp_INDEX_INFO: if( zRight ){
  90352. Index *pIdx;
  90353. Table *pTab;
  90354. pIdx = sqlite3FindIndex(db, zRight, zDb);
  90355. if( pIdx ){
  90356. int i;
  90357. pTab = pIdx->pTable;
  90358. sqlite3VdbeSetNumCols(v, 3);
  90359. pParse->nMem = 3;
  90360. sqlite3CodeVerifySchema(pParse, iDb);
  90361. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  90362. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  90363. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  90364. for(i=0; i<pIdx->nColumn; i++){
  90365. int cnum = pIdx->aiColumn[i];
  90366. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  90367. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  90368. assert( pTab->nCol>cnum );
  90369. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  90370. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  90371. }
  90372. }
  90373. }
  90374. break;
  90375. case PragTyp_INDEX_LIST: if( zRight ){
  90376. Index *pIdx;
  90377. Table *pTab;
  90378. int i;
  90379. pTab = sqlite3FindTable(db, zRight, zDb);
  90380. if( pTab ){
  90381. v = sqlite3GetVdbe(pParse);
  90382. sqlite3VdbeSetNumCols(v, 3);
  90383. pParse->nMem = 3;
  90384. sqlite3CodeVerifySchema(pParse, iDb);
  90385. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  90386. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  90387. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  90388. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  90389. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  90390. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  90391. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
  90392. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  90393. }
  90394. }
  90395. }
  90396. break;
  90397. case PragTyp_DATABASE_LIST: {
  90398. int i;
  90399. sqlite3VdbeSetNumCols(v, 3);
  90400. pParse->nMem = 3;
  90401. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  90402. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  90403. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  90404. for(i=0; i<db->nDb; i++){
  90405. if( db->aDb[i].pBt==0 ) continue;
  90406. assert( db->aDb[i].zName!=0 );
  90407. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  90408. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  90409. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  90410. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  90411. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  90412. }
  90413. }
  90414. break;
  90415. case PragTyp_COLLATION_LIST: {
  90416. int i = 0;
  90417. HashElem *p;
  90418. sqlite3VdbeSetNumCols(v, 2);
  90419. pParse->nMem = 2;
  90420. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  90421. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  90422. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  90423. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  90424. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  90425. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  90426. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  90427. }
  90428. }
  90429. break;
  90430. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  90431. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90432. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  90433. FKey *pFK;
  90434. Table *pTab;
  90435. pTab = sqlite3FindTable(db, zRight, zDb);
  90436. if( pTab ){
  90437. v = sqlite3GetVdbe(pParse);
  90438. pFK = pTab->pFKey;
  90439. if( pFK ){
  90440. int i = 0;
  90441. sqlite3VdbeSetNumCols(v, 8);
  90442. pParse->nMem = 8;
  90443. sqlite3CodeVerifySchema(pParse, iDb);
  90444. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  90445. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  90446. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  90447. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  90448. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  90449. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  90450. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  90451. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  90452. while(pFK){
  90453. int j;
  90454. for(j=0; j<pFK->nCol; j++){
  90455. char *zCol = pFK->aCol[j].zCol;
  90456. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  90457. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  90458. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  90459. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  90460. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  90461. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  90462. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  90463. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  90464. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  90465. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  90466. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  90467. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  90468. }
  90469. ++i;
  90470. pFK = pFK->pNextFrom;
  90471. }
  90472. }
  90473. }
  90474. }
  90475. break;
  90476. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  90477. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90478. #ifndef SQLITE_OMIT_TRIGGER
  90479. case PragTyp_FOREIGN_KEY_CHECK: {
  90480. FKey *pFK; /* A foreign key constraint */
  90481. Table *pTab; /* Child table contain "REFERENCES" keyword */
  90482. Table *pParent; /* Parent table that child points to */
  90483. Index *pIdx; /* Index in the parent table */
  90484. int i; /* Loop counter: Foreign key number for pTab */
  90485. int j; /* Loop counter: Field of the foreign key */
  90486. HashElem *k; /* Loop counter: Next table in schema */
  90487. int x; /* result variable */
  90488. int regResult; /* 3 registers to hold a result row */
  90489. int regKey; /* Register to hold key for checking the FK */
  90490. int regRow; /* Registers to hold a row from pTab */
  90491. int addrTop; /* Top of a loop checking foreign keys */
  90492. int addrOk; /* Jump here if the key is OK */
  90493. int *aiCols; /* child to parent column mapping */
  90494. regResult = pParse->nMem+1;
  90495. pParse->nMem += 4;
  90496. regKey = ++pParse->nMem;
  90497. regRow = ++pParse->nMem;
  90498. v = sqlite3GetVdbe(pParse);
  90499. sqlite3VdbeSetNumCols(v, 4);
  90500. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  90501. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
  90502. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
  90503. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
  90504. sqlite3CodeVerifySchema(pParse, iDb);
  90505. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  90506. while( k ){
  90507. if( zRight ){
  90508. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  90509. k = 0;
  90510. }else{
  90511. pTab = (Table*)sqliteHashData(k);
  90512. k = sqliteHashNext(k);
  90513. }
  90514. if( pTab==0 || pTab->pFKey==0 ) continue;
  90515. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  90516. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  90517. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  90518. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
  90519. P4_TRANSIENT);
  90520. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  90521. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  90522. if( pParent==0 ) continue;
  90523. pIdx = 0;
  90524. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  90525. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  90526. if( x==0 ){
  90527. if( pIdx==0 ){
  90528. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  90529. }else{
  90530. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  90531. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  90532. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  90533. }
  90534. }else{
  90535. k = 0;
  90536. break;
  90537. }
  90538. }
  90539. assert( pParse->nErr>0 || pFK==0 );
  90540. if( pFK ) break;
  90541. if( pParse->nTab<i ) pParse->nTab = i;
  90542. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
  90543. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  90544. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  90545. pIdx = 0;
  90546. aiCols = 0;
  90547. if( pParent ){
  90548. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  90549. assert( x==0 );
  90550. }
  90551. addrOk = sqlite3VdbeMakeLabel(v);
  90552. if( pParent && pIdx==0 ){
  90553. int iKey = pFK->aCol[0].iFrom;
  90554. assert( iKey>=0 && iKey<pTab->nCol );
  90555. if( iKey!=pTab->iPKey ){
  90556. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  90557. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  90558. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
  90559. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  90560. sqlite3VdbeCurrentAddr(v)+3);
  90561. }else{
  90562. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  90563. }
  90564. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
  90565. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
  90566. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  90567. }else{
  90568. for(j=0; j<pFK->nCol; j++){
  90569. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  90570. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  90571. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
  90572. }
  90573. if( pParent ){
  90574. sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
  90575. sqlite3VdbeChangeP4(v, -1,
  90576. sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  90577. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  90578. }
  90579. }
  90580. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  90581. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
  90582. pFK->zTo, P4_TRANSIENT);
  90583. sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
  90584. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  90585. sqlite3VdbeResolveLabel(v, addrOk);
  90586. sqlite3DbFree(db, aiCols);
  90587. }
  90588. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
  90589. sqlite3VdbeJumpHere(v, addrTop);
  90590. }
  90591. }
  90592. break;
  90593. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  90594. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  90595. #ifndef NDEBUG
  90596. case PragTyp_PARSER_TRACE: {
  90597. if( zRight ){
  90598. if( sqlite3GetBoolean(zRight, 0) ){
  90599. sqlite3ParserTrace(stderr, "parser: ");
  90600. }else{
  90601. sqlite3ParserTrace(0, 0);
  90602. }
  90603. }
  90604. }
  90605. break;
  90606. #endif
  90607. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  90608. ** used will be case sensitive or not depending on the RHS.
  90609. */
  90610. case PragTyp_CASE_SENSITIVE_LIKE: {
  90611. if( zRight ){
  90612. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  90613. }
  90614. }
  90615. break;
  90616. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  90617. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  90618. #endif
  90619. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  90620. /* Pragma "quick_check" is reduced version of
  90621. ** integrity_check designed to detect most database corruption
  90622. ** without most of the overhead of a full integrity-check.
  90623. */
  90624. case PragTyp_INTEGRITY_CHECK: {
  90625. int i, j, addr, mxErr;
  90626. /* Code that appears at the end of the integrity check. If no error
  90627. ** messages have been generated, output OK. Otherwise output the
  90628. ** error message
  90629. */
  90630. static const VdbeOpList endCode[] = {
  90631. { OP_AddImm, 1, 0, 0}, /* 0 */
  90632. { OP_IfNeg, 1, 0, 0}, /* 1 */
  90633. { OP_String8, 0, 3, 0}, /* 2 */
  90634. { OP_ResultRow, 3, 1, 0},
  90635. };
  90636. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  90637. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  90638. ** then iDb is set to the index of the database identified by <db>.
  90639. ** In this case, the integrity of database iDb only is verified by
  90640. ** the VDBE created below.
  90641. **
  90642. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  90643. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  90644. ** to -1 here, to indicate that the VDBE should verify the integrity
  90645. ** of all attached databases. */
  90646. assert( iDb>=0 );
  90647. assert( iDb==0 || pId2->z );
  90648. if( pId2->z==0 ) iDb = -1;
  90649. /* Initialize the VDBE program */
  90650. pParse->nMem = 6;
  90651. sqlite3VdbeSetNumCols(v, 1);
  90652. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  90653. /* Set the maximum error count */
  90654. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  90655. if( zRight ){
  90656. sqlite3GetInt32(zRight, &mxErr);
  90657. if( mxErr<=0 ){
  90658. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  90659. }
  90660. }
  90661. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  90662. /* Do an integrity check on each database file */
  90663. for(i=0; i<db->nDb; i++){
  90664. HashElem *x;
  90665. Hash *pTbls;
  90666. int cnt = 0;
  90667. if( OMIT_TEMPDB && i==1 ) continue;
  90668. if( iDb>=0 && i!=iDb ) continue;
  90669. sqlite3CodeVerifySchema(pParse, i);
  90670. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  90671. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  90672. sqlite3VdbeJumpHere(v, addr);
  90673. /* Do an integrity check of the B-Tree
  90674. **
  90675. ** Begin by filling registers 2, 3, ... with the root pages numbers
  90676. ** for all tables and indices in the database.
  90677. */
  90678. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  90679. pTbls = &db->aDb[i].pSchema->tblHash;
  90680. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  90681. Table *pTab = sqliteHashData(x);
  90682. Index *pIdx;
  90683. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  90684. cnt++;
  90685. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  90686. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  90687. cnt++;
  90688. }
  90689. }
  90690. /* Make sure sufficient number of registers have been allocated */
  90691. pParse->nMem = MAX( pParse->nMem, cnt+7 );
  90692. /* Do the b-tree integrity checks */
  90693. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  90694. sqlite3VdbeChangeP5(v, (u8)i);
  90695. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
  90696. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  90697. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  90698. P4_DYNAMIC);
  90699. sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
  90700. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  90701. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  90702. sqlite3VdbeJumpHere(v, addr);
  90703. /* Make sure all the indices are constructed correctly.
  90704. */
  90705. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  90706. Table *pTab = sqliteHashData(x);
  90707. Index *pIdx;
  90708. int loopTop;
  90709. if( pTab->pIndex==0 ) continue;
  90710. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  90711. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  90712. sqlite3VdbeJumpHere(v, addr);
  90713. sqlite3ExprCacheClear(pParse);
  90714. sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
  90715. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  90716. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7+j); /* index entries counter */
  90717. }
  90718. pParse->nMem = MAX(pParse->nMem, 7+j);
  90719. loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0) + 1;
  90720. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  90721. int jmp2, jmp3;
  90722. int r1;
  90723. static const VdbeOpList idxErr[] = {
  90724. { OP_AddImm, 1, -1, 0},
  90725. { OP_String8, 0, 3, 0}, /* 1 */
  90726. { OP_Rowid, 1, 4, 0},
  90727. { OP_String8, 0, 5, 0}, /* 3 */
  90728. { OP_String8, 0, 6, 0}, /* 4 */
  90729. { OP_Concat, 4, 3, 3},
  90730. { OP_Concat, 5, 3, 3},
  90731. { OP_Concat, 6, 3, 3},
  90732. { OP_ResultRow, 3, 1, 0},
  90733. { OP_IfPos, 1, 0, 0}, /* 9 */
  90734. { OP_Halt, 0, 0, 0},
  90735. };
  90736. r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0, &jmp3);
  90737. sqlite3VdbeAddOp2(v, OP_AddImm, 7+j, 1); /* increment entry count */
  90738. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
  90739. addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
  90740. sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
  90741. sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
  90742. sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
  90743. sqlite3VdbeJumpHere(v, addr+9);
  90744. sqlite3VdbeJumpHere(v, jmp2);
  90745. sqlite3VdbeResolveLabel(v, jmp3);
  90746. }
  90747. sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop);
  90748. sqlite3VdbeJumpHere(v, loopTop-1);
  90749. #ifndef SQLITE_OMIT_BTREECOUNT
  90750. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
  90751. "wrong # of entries in index ", P4_STATIC);
  90752. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  90753. addr = sqlite3VdbeCurrentAddr(v);
  90754. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2);
  90755. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  90756. sqlite3VdbeAddOp2(v, OP_Count, j+2, 3);
  90757. sqlite3VdbeAddOp3(v, OP_Eq, 7+j, addr+8, 3);
  90758. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  90759. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
  90760. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  90761. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  90762. }
  90763. #endif /* SQLITE_OMIT_BTREECOUNT */
  90764. }
  90765. }
  90766. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
  90767. sqlite3VdbeChangeP2(v, addr, -mxErr);
  90768. sqlite3VdbeJumpHere(v, addr+1);
  90769. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  90770. }
  90771. break;
  90772. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  90773. #ifndef SQLITE_OMIT_UTF16
  90774. /*
  90775. ** PRAGMA encoding
  90776. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  90777. **
  90778. ** In its first form, this pragma returns the encoding of the main
  90779. ** database. If the database is not initialized, it is initialized now.
  90780. **
  90781. ** The second form of this pragma is a no-op if the main database file
  90782. ** has not already been initialized. In this case it sets the default
  90783. ** encoding that will be used for the main database file if a new file
  90784. ** is created. If an existing main database file is opened, then the
  90785. ** default text encoding for the existing database is used.
  90786. **
  90787. ** In all cases new databases created using the ATTACH command are
  90788. ** created to use the same default text encoding as the main database. If
  90789. ** the main database has not been initialized and/or created when ATTACH
  90790. ** is executed, this is done before the ATTACH operation.
  90791. **
  90792. ** In the second form this pragma sets the text encoding to be used in
  90793. ** new database files created using this database handle. It is only
  90794. ** useful if invoked immediately after the main database i
  90795. */
  90796. case PragTyp_ENCODING: {
  90797. static const struct EncName {
  90798. char *zName;
  90799. u8 enc;
  90800. } encnames[] = {
  90801. { "UTF8", SQLITE_UTF8 },
  90802. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  90803. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  90804. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  90805. { "UTF16le", SQLITE_UTF16LE },
  90806. { "UTF16be", SQLITE_UTF16BE },
  90807. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  90808. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  90809. { 0, 0 }
  90810. };
  90811. const struct EncName *pEnc;
  90812. if( !zRight ){ /* "PRAGMA encoding" */
  90813. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  90814. sqlite3VdbeSetNumCols(v, 1);
  90815. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  90816. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  90817. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  90818. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  90819. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  90820. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  90821. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  90822. }else{ /* "PRAGMA encoding = XXX" */
  90823. /* Only change the value of sqlite.enc if the database handle is not
  90824. ** initialized. If the main database exists, the new sqlite.enc value
  90825. ** will be overwritten when the schema is next loaded. If it does not
  90826. ** already exists, it will be created to use the new encoding value.
  90827. */
  90828. if(
  90829. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  90830. DbHasProperty(db, 0, DB_Empty)
  90831. ){
  90832. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  90833. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  90834. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  90835. break;
  90836. }
  90837. }
  90838. if( !pEnc->zName ){
  90839. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  90840. }
  90841. }
  90842. }
  90843. }
  90844. break;
  90845. #endif /* SQLITE_OMIT_UTF16 */
  90846. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  90847. /*
  90848. ** PRAGMA [database.]schema_version
  90849. ** PRAGMA [database.]schema_version = <integer>
  90850. **
  90851. ** PRAGMA [database.]user_version
  90852. ** PRAGMA [database.]user_version = <integer>
  90853. **
  90854. ** PRAGMA [database.]freelist_count = <integer>
  90855. **
  90856. ** PRAGMA [database.]application_id
  90857. ** PRAGMA [database.]application_id = <integer>
  90858. **
  90859. ** The pragma's schema_version and user_version are used to set or get
  90860. ** the value of the schema-version and user-version, respectively. Both
  90861. ** the schema-version and the user-version are 32-bit signed integers
  90862. ** stored in the database header.
  90863. **
  90864. ** The schema-cookie is usually only manipulated internally by SQLite. It
  90865. ** is incremented by SQLite whenever the database schema is modified (by
  90866. ** creating or dropping a table or index). The schema version is used by
  90867. ** SQLite each time a query is executed to ensure that the internal cache
  90868. ** of the schema used when compiling the SQL query matches the schema of
  90869. ** the database against which the compiled query is actually executed.
  90870. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  90871. ** the schema-version is potentially dangerous and may lead to program
  90872. ** crashes or database corruption. Use with caution!
  90873. **
  90874. ** The user-version is not used internally by SQLite. It may be used by
  90875. ** applications for any purpose.
  90876. */
  90877. case PragTyp_HEADER_VALUE: {
  90878. int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
  90879. sqlite3VdbeUsesBtree(v, iDb);
  90880. switch( zLeft[0] ){
  90881. case 'a': case 'A':
  90882. iCookie = BTREE_APPLICATION_ID;
  90883. break;
  90884. case 'f': case 'F':
  90885. iCookie = BTREE_FREE_PAGE_COUNT;
  90886. break;
  90887. case 's': case 'S':
  90888. iCookie = BTREE_SCHEMA_VERSION;
  90889. break;
  90890. default:
  90891. iCookie = BTREE_USER_VERSION;
  90892. break;
  90893. }
  90894. if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
  90895. /* Write the specified cookie value */
  90896. static const VdbeOpList setCookie[] = {
  90897. { OP_Transaction, 0, 1, 0}, /* 0 */
  90898. { OP_Integer, 0, 1, 0}, /* 1 */
  90899. { OP_SetCookie, 0, 0, 1}, /* 2 */
  90900. };
  90901. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
  90902. sqlite3VdbeChangeP1(v, addr, iDb);
  90903. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  90904. sqlite3VdbeChangeP1(v, addr+2, iDb);
  90905. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  90906. }else{
  90907. /* Read the specified cookie value */
  90908. static const VdbeOpList readCookie[] = {
  90909. { OP_Transaction, 0, 0, 0}, /* 0 */
  90910. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  90911. { OP_ResultRow, 1, 1, 0}
  90912. };
  90913. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
  90914. sqlite3VdbeChangeP1(v, addr, iDb);
  90915. sqlite3VdbeChangeP1(v, addr+1, iDb);
  90916. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  90917. sqlite3VdbeSetNumCols(v, 1);
  90918. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  90919. }
  90920. }
  90921. break;
  90922. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  90923. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  90924. /*
  90925. ** PRAGMA compile_options
  90926. **
  90927. ** Return the names of all compile-time options used in this build,
  90928. ** one option per row.
  90929. */
  90930. case PragTyp_COMPILE_OPTIONS: {
  90931. int i = 0;
  90932. const char *zOpt;
  90933. sqlite3VdbeSetNumCols(v, 1);
  90934. pParse->nMem = 1;
  90935. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  90936. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  90937. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  90938. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  90939. }
  90940. }
  90941. break;
  90942. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  90943. #ifndef SQLITE_OMIT_WAL
  90944. /*
  90945. ** PRAGMA [database.]wal_checkpoint = passive|full|restart
  90946. **
  90947. ** Checkpoint the database.
  90948. */
  90949. case PragTyp_WAL_CHECKPOINT: {
  90950. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  90951. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  90952. if( zRight ){
  90953. if( sqlite3StrICmp(zRight, "full")==0 ){
  90954. eMode = SQLITE_CHECKPOINT_FULL;
  90955. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  90956. eMode = SQLITE_CHECKPOINT_RESTART;
  90957. }
  90958. }
  90959. sqlite3VdbeSetNumCols(v, 3);
  90960. pParse->nMem = 3;
  90961. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  90962. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  90963. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  90964. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  90965. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  90966. }
  90967. break;
  90968. /*
  90969. ** PRAGMA wal_autocheckpoint
  90970. ** PRAGMA wal_autocheckpoint = N
  90971. **
  90972. ** Configure a database connection to automatically checkpoint a database
  90973. ** after accumulating N frames in the log. Or query for the current value
  90974. ** of N.
  90975. */
  90976. case PragTyp_WAL_AUTOCHECKPOINT: {
  90977. if( zRight ){
  90978. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  90979. }
  90980. returnSingleInt(pParse, "wal_autocheckpoint",
  90981. db->xWalCallback==sqlite3WalDefaultHook ?
  90982. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  90983. }
  90984. break;
  90985. #endif
  90986. /*
  90987. ** PRAGMA shrink_memory
  90988. **
  90989. ** This pragma attempts to free as much memory as possible from the
  90990. ** current database connection.
  90991. */
  90992. case PragTyp_SHRINK_MEMORY: {
  90993. sqlite3_db_release_memory(db);
  90994. break;
  90995. }
  90996. /*
  90997. ** PRAGMA busy_timeout
  90998. ** PRAGMA busy_timeout = N
  90999. **
  91000. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  91001. ** if one is set. If no busy handler or a different busy handler is set
  91002. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  91003. ** disables the timeout.
  91004. */
  91005. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  91006. assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
  91007. if( zRight ){
  91008. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  91009. }
  91010. returnSingleInt(pParse, "timeout", db->busyTimeout);
  91011. break;
  91012. }
  91013. /*
  91014. ** PRAGMA soft_heap_limit
  91015. ** PRAGMA soft_heap_limit = N
  91016. **
  91017. ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted,
  91018. ** use -1.
  91019. */
  91020. case PragTyp_SOFT_HEAP_LIMIT: {
  91021. sqlite3_int64 N;
  91022. if( zRight && sqlite3Atoi64(zRight, &N, 1000000, SQLITE_UTF8)==SQLITE_OK ){
  91023. sqlite3_soft_heap_limit64(N);
  91024. }
  91025. returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  91026. break;
  91027. }
  91028. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  91029. /*
  91030. ** Report the current state of file logs for all databases
  91031. */
  91032. case PragTyp_LOCK_STATUS: {
  91033. static const char *const azLockName[] = {
  91034. "unlocked", "shared", "reserved", "pending", "exclusive"
  91035. };
  91036. int i;
  91037. sqlite3VdbeSetNumCols(v, 2);
  91038. pParse->nMem = 2;
  91039. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  91040. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  91041. for(i=0; i<db->nDb; i++){
  91042. Btree *pBt;
  91043. const char *zState = "unknown";
  91044. int j;
  91045. if( db->aDb[i].zName==0 ) continue;
  91046. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  91047. pBt = db->aDb[i].pBt;
  91048. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  91049. zState = "closed";
  91050. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  91051. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  91052. zState = azLockName[j];
  91053. }
  91054. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  91055. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  91056. }
  91057. break;
  91058. }
  91059. #endif
  91060. #ifdef SQLITE_HAS_CODEC
  91061. case PragTyp_KEY: {
  91062. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  91063. break;
  91064. }
  91065. case PragTyp_REKEY: {
  91066. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  91067. break;
  91068. }
  91069. case PragTyp_HEXKEY: {
  91070. if( zRight ){
  91071. u8 iByte;
  91072. int i;
  91073. char zKey[40];
  91074. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  91075. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  91076. if( (i&1)!=0 ) zKey[i/2] = iByte;
  91077. }
  91078. if( (zLeft[3] & 0xf)==0xb ){
  91079. sqlite3_key_v2(db, zDb, zKey, i/2);
  91080. }else{
  91081. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  91082. }
  91083. }
  91084. break;
  91085. }
  91086. #endif
  91087. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  91088. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  91089. #ifdef SQLITE_HAS_CODEC
  91090. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  91091. sqlite3_activate_see(&zRight[4]);
  91092. }
  91093. #endif
  91094. #ifdef SQLITE_ENABLE_CEROD
  91095. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  91096. sqlite3_activate_cerod(&zRight[6]);
  91097. }
  91098. #endif
  91099. }
  91100. break;
  91101. #endif
  91102. } /* End of the PRAGMA switch */
  91103. pragma_out:
  91104. sqlite3DbFree(db, zLeft);
  91105. sqlite3DbFree(db, zRight);
  91106. }
  91107. #endif /* SQLITE_OMIT_PRAGMA */
  91108. /************** End of pragma.c **********************************************/
  91109. /************** Begin file prepare.c *****************************************/
  91110. /*
  91111. ** 2005 May 25
  91112. **
  91113. ** The author disclaims copyright to this source code. In place of
  91114. ** a legal notice, here is a blessing:
  91115. **
  91116. ** May you do good and not evil.
  91117. ** May you find forgiveness for yourself and forgive others.
  91118. ** May you share freely, never taking more than you give.
  91119. **
  91120. *************************************************************************
  91121. ** This file contains the implementation of the sqlite3_prepare()
  91122. ** interface, and routines that contribute to loading the database schema
  91123. ** from disk.
  91124. */
  91125. /*
  91126. ** Fill the InitData structure with an error message that indicates
  91127. ** that the database is corrupt.
  91128. */
  91129. static void corruptSchema(
  91130. InitData *pData, /* Initialization context */
  91131. const char *zObj, /* Object being parsed at the point of error */
  91132. const char *zExtra /* Error information */
  91133. ){
  91134. sqlite3 *db = pData->db;
  91135. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  91136. if( zObj==0 ) zObj = "?";
  91137. sqlite3SetString(pData->pzErrMsg, db,
  91138. "malformed database schema (%s)", zObj);
  91139. if( zExtra ){
  91140. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  91141. "%s - %s", *pData->pzErrMsg, zExtra);
  91142. }
  91143. }
  91144. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  91145. }
  91146. /*
  91147. ** This is the callback routine for the code that initializes the
  91148. ** database. See sqlite3Init() below for additional information.
  91149. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  91150. **
  91151. ** Each callback contains the following information:
  91152. **
  91153. ** argv[0] = name of thing being created
  91154. ** argv[1] = root page number for table or index. 0 for trigger or view.
  91155. ** argv[2] = SQL text for the CREATE statement.
  91156. **
  91157. */
  91158. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  91159. InitData *pData = (InitData*)pInit;
  91160. sqlite3 *db = pData->db;
  91161. int iDb = pData->iDb;
  91162. assert( argc==3 );
  91163. UNUSED_PARAMETER2(NotUsed, argc);
  91164. assert( sqlite3_mutex_held(db->mutex) );
  91165. DbClearProperty(db, iDb, DB_Empty);
  91166. if( db->mallocFailed ){
  91167. corruptSchema(pData, argv[0], 0);
  91168. return 1;
  91169. }
  91170. assert( iDb>=0 && iDb<db->nDb );
  91171. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  91172. if( argv[1]==0 ){
  91173. corruptSchema(pData, argv[0], 0);
  91174. }else if( argv[2] && argv[2][0] ){
  91175. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  91176. ** But because db->init.busy is set to 1, no VDBE code is generated
  91177. ** or executed. All the parser does is build the internal data
  91178. ** structures that describe the table, index, or view.
  91179. */
  91180. int rc;
  91181. sqlite3_stmt *pStmt;
  91182. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  91183. assert( db->init.busy );
  91184. db->init.iDb = iDb;
  91185. db->init.newTnum = sqlite3Atoi(argv[1]);
  91186. db->init.orphanTrigger = 0;
  91187. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  91188. rc = db->errCode;
  91189. assert( (rc&0xFF)==(rcp&0xFF) );
  91190. db->init.iDb = 0;
  91191. if( SQLITE_OK!=rc ){
  91192. if( db->init.orphanTrigger ){
  91193. assert( iDb==1 );
  91194. }else{
  91195. pData->rc = rc;
  91196. if( rc==SQLITE_NOMEM ){
  91197. db->mallocFailed = 1;
  91198. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  91199. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  91200. }
  91201. }
  91202. }
  91203. sqlite3_finalize(pStmt);
  91204. }else if( argv[0]==0 ){
  91205. corruptSchema(pData, 0, 0);
  91206. }else{
  91207. /* If the SQL column is blank it means this is an index that
  91208. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  91209. ** constraint for a CREATE TABLE. The index should have already
  91210. ** been created when we processed the CREATE TABLE. All we have
  91211. ** to do here is record the root page number for that index.
  91212. */
  91213. Index *pIndex;
  91214. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  91215. if( pIndex==0 ){
  91216. /* This can occur if there exists an index on a TEMP table which
  91217. ** has the same name as another index on a permanent index. Since
  91218. ** the permanent table is hidden by the TEMP table, we can also
  91219. ** safely ignore the index on the permanent table.
  91220. */
  91221. /* Do Nothing */;
  91222. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  91223. corruptSchema(pData, argv[0], "invalid rootpage");
  91224. }
  91225. }
  91226. return 0;
  91227. }
  91228. /*
  91229. ** Attempt to read the database schema and initialize internal
  91230. ** data structures for a single database file. The index of the
  91231. ** database file is given by iDb. iDb==0 is used for the main
  91232. ** database. iDb==1 should never be used. iDb>=2 is used for
  91233. ** auxiliary databases. Return one of the SQLITE_ error codes to
  91234. ** indicate success or failure.
  91235. */
  91236. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  91237. int rc;
  91238. int i;
  91239. #ifndef SQLITE_OMIT_DEPRECATED
  91240. int size;
  91241. #endif
  91242. Table *pTab;
  91243. Db *pDb;
  91244. char const *azArg[4];
  91245. int meta[5];
  91246. InitData initData;
  91247. char const *zMasterSchema;
  91248. char const *zMasterName;
  91249. int openedTransaction = 0;
  91250. /*
  91251. ** The master database table has a structure like this
  91252. */
  91253. static const char master_schema[] =
  91254. "CREATE TABLE sqlite_master(\n"
  91255. " type text,\n"
  91256. " name text,\n"
  91257. " tbl_name text,\n"
  91258. " rootpage integer,\n"
  91259. " sql text\n"
  91260. ")"
  91261. ;
  91262. #ifndef SQLITE_OMIT_TEMPDB
  91263. static const char temp_master_schema[] =
  91264. "CREATE TEMP TABLE sqlite_temp_master(\n"
  91265. " type text,\n"
  91266. " name text,\n"
  91267. " tbl_name text,\n"
  91268. " rootpage integer,\n"
  91269. " sql text\n"
  91270. ")"
  91271. ;
  91272. #else
  91273. #define temp_master_schema 0
  91274. #endif
  91275. assert( iDb>=0 && iDb<db->nDb );
  91276. assert( db->aDb[iDb].pSchema );
  91277. assert( sqlite3_mutex_held(db->mutex) );
  91278. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  91279. /* zMasterSchema and zInitScript are set to point at the master schema
  91280. ** and initialisation script appropriate for the database being
  91281. ** initialized. zMasterName is the name of the master table.
  91282. */
  91283. if( !OMIT_TEMPDB && iDb==1 ){
  91284. zMasterSchema = temp_master_schema;
  91285. }else{
  91286. zMasterSchema = master_schema;
  91287. }
  91288. zMasterName = SCHEMA_TABLE(iDb);
  91289. /* Construct the schema tables. */
  91290. azArg[0] = zMasterName;
  91291. azArg[1] = "1";
  91292. azArg[2] = zMasterSchema;
  91293. azArg[3] = 0;
  91294. initData.db = db;
  91295. initData.iDb = iDb;
  91296. initData.rc = SQLITE_OK;
  91297. initData.pzErrMsg = pzErrMsg;
  91298. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  91299. if( initData.rc ){
  91300. rc = initData.rc;
  91301. goto error_out;
  91302. }
  91303. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  91304. if( ALWAYS(pTab) ){
  91305. pTab->tabFlags |= TF_Readonly;
  91306. }
  91307. /* Create a cursor to hold the database open
  91308. */
  91309. pDb = &db->aDb[iDb];
  91310. if( pDb->pBt==0 ){
  91311. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  91312. DbSetProperty(db, 1, DB_SchemaLoaded);
  91313. }
  91314. return SQLITE_OK;
  91315. }
  91316. /* If there is not already a read-only (or read-write) transaction opened
  91317. ** on the b-tree database, open one now. If a transaction is opened, it
  91318. ** will be closed before this function returns. */
  91319. sqlite3BtreeEnter(pDb->pBt);
  91320. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  91321. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  91322. if( rc!=SQLITE_OK ){
  91323. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  91324. goto initone_error_out;
  91325. }
  91326. openedTransaction = 1;
  91327. }
  91328. /* Get the database meta information.
  91329. **
  91330. ** Meta values are as follows:
  91331. ** meta[0] Schema cookie. Changes with each schema change.
  91332. ** meta[1] File format of schema layer.
  91333. ** meta[2] Size of the page cache.
  91334. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  91335. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  91336. ** meta[5] User version
  91337. ** meta[6] Incremental vacuum mode
  91338. ** meta[7] unused
  91339. ** meta[8] unused
  91340. ** meta[9] unused
  91341. **
  91342. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  91343. ** the possible values of meta[4].
  91344. */
  91345. for(i=0; i<ArraySize(meta); i++){
  91346. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  91347. }
  91348. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  91349. /* If opening a non-empty database, check the text encoding. For the
  91350. ** main database, set sqlite3.enc to the encoding of the main database.
  91351. ** For an attached db, it is an error if the encoding is not the same
  91352. ** as sqlite3.enc.
  91353. */
  91354. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  91355. if( iDb==0 ){
  91356. #ifndef SQLITE_OMIT_UTF16
  91357. u8 encoding;
  91358. /* If opening the main database, set ENC(db). */
  91359. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  91360. if( encoding==0 ) encoding = SQLITE_UTF8;
  91361. ENC(db) = encoding;
  91362. #else
  91363. ENC(db) = SQLITE_UTF8;
  91364. #endif
  91365. }else{
  91366. /* If opening an attached database, the encoding much match ENC(db) */
  91367. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  91368. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  91369. " text encoding as main database");
  91370. rc = SQLITE_ERROR;
  91371. goto initone_error_out;
  91372. }
  91373. }
  91374. }else{
  91375. DbSetProperty(db, iDb, DB_Empty);
  91376. }
  91377. pDb->pSchema->enc = ENC(db);
  91378. if( pDb->pSchema->cache_size==0 ){
  91379. #ifndef SQLITE_OMIT_DEPRECATED
  91380. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  91381. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  91382. pDb->pSchema->cache_size = size;
  91383. #else
  91384. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  91385. #endif
  91386. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  91387. }
  91388. /*
  91389. ** file_format==1 Version 3.0.0.
  91390. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  91391. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  91392. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  91393. */
  91394. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  91395. if( pDb->pSchema->file_format==0 ){
  91396. pDb->pSchema->file_format = 1;
  91397. }
  91398. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  91399. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  91400. rc = SQLITE_ERROR;
  91401. goto initone_error_out;
  91402. }
  91403. /* Ticket #2804: When we open a database in the newer file format,
  91404. ** clear the legacy_file_format pragma flag so that a VACUUM will
  91405. ** not downgrade the database and thus invalidate any descending
  91406. ** indices that the user might have created.
  91407. */
  91408. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  91409. db->flags &= ~SQLITE_LegacyFileFmt;
  91410. }
  91411. /* Read the schema information out of the schema tables
  91412. */
  91413. assert( db->init.busy );
  91414. {
  91415. char *zSql;
  91416. zSql = sqlite3MPrintf(db,
  91417. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  91418. db->aDb[iDb].zName, zMasterName);
  91419. #ifndef SQLITE_OMIT_AUTHORIZATION
  91420. {
  91421. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  91422. xAuth = db->xAuth;
  91423. db->xAuth = 0;
  91424. #endif
  91425. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  91426. #ifndef SQLITE_OMIT_AUTHORIZATION
  91427. db->xAuth = xAuth;
  91428. }
  91429. #endif
  91430. if( rc==SQLITE_OK ) rc = initData.rc;
  91431. sqlite3DbFree(db, zSql);
  91432. #ifndef SQLITE_OMIT_ANALYZE
  91433. if( rc==SQLITE_OK ){
  91434. sqlite3AnalysisLoad(db, iDb);
  91435. }
  91436. #endif
  91437. }
  91438. if( db->mallocFailed ){
  91439. rc = SQLITE_NOMEM;
  91440. sqlite3ResetAllSchemasOfConnection(db);
  91441. }
  91442. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  91443. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  91444. ** the schema loaded, even if errors occurred. In this situation the
  91445. ** current sqlite3_prepare() operation will fail, but the following one
  91446. ** will attempt to compile the supplied statement against whatever subset
  91447. ** of the schema was loaded before the error occurred. The primary
  91448. ** purpose of this is to allow access to the sqlite_master table
  91449. ** even when its contents have been corrupted.
  91450. */
  91451. DbSetProperty(db, iDb, DB_SchemaLoaded);
  91452. rc = SQLITE_OK;
  91453. }
  91454. /* Jump here for an error that occurs after successfully allocating
  91455. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  91456. ** before that point, jump to error_out.
  91457. */
  91458. initone_error_out:
  91459. if( openedTransaction ){
  91460. sqlite3BtreeCommit(pDb->pBt);
  91461. }
  91462. sqlite3BtreeLeave(pDb->pBt);
  91463. error_out:
  91464. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  91465. db->mallocFailed = 1;
  91466. }
  91467. return rc;
  91468. }
  91469. /*
  91470. ** Initialize all database files - the main database file, the file
  91471. ** used to store temporary tables, and any additional database files
  91472. ** created using ATTACH statements. Return a success code. If an
  91473. ** error occurs, write an error message into *pzErrMsg.
  91474. **
  91475. ** After a database is initialized, the DB_SchemaLoaded bit is set
  91476. ** bit is set in the flags field of the Db structure. If the database
  91477. ** file was of zero-length, then the DB_Empty flag is also set.
  91478. */
  91479. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  91480. int i, rc;
  91481. int commit_internal = !(db->flags&SQLITE_InternChanges);
  91482. assert( sqlite3_mutex_held(db->mutex) );
  91483. rc = SQLITE_OK;
  91484. db->init.busy = 1;
  91485. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  91486. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  91487. rc = sqlite3InitOne(db, i, pzErrMsg);
  91488. if( rc ){
  91489. sqlite3ResetOneSchema(db, i);
  91490. }
  91491. }
  91492. /* Once all the other databases have been initialized, load the schema
  91493. ** for the TEMP database. This is loaded last, as the TEMP database
  91494. ** schema may contain references to objects in other databases.
  91495. */
  91496. #ifndef SQLITE_OMIT_TEMPDB
  91497. if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
  91498. && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  91499. rc = sqlite3InitOne(db, 1, pzErrMsg);
  91500. if( rc ){
  91501. sqlite3ResetOneSchema(db, 1);
  91502. }
  91503. }
  91504. #endif
  91505. db->init.busy = 0;
  91506. if( rc==SQLITE_OK && commit_internal ){
  91507. sqlite3CommitInternalChanges(db);
  91508. }
  91509. return rc;
  91510. }
  91511. /*
  91512. ** This routine is a no-op if the database schema is already initialized.
  91513. ** Otherwise, the schema is loaded. An error code is returned.
  91514. */
  91515. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  91516. int rc = SQLITE_OK;
  91517. sqlite3 *db = pParse->db;
  91518. assert( sqlite3_mutex_held(db->mutex) );
  91519. if( !db->init.busy ){
  91520. rc = sqlite3Init(db, &pParse->zErrMsg);
  91521. }
  91522. if( rc!=SQLITE_OK ){
  91523. pParse->rc = rc;
  91524. pParse->nErr++;
  91525. }
  91526. return rc;
  91527. }
  91528. /*
  91529. ** Check schema cookies in all databases. If any cookie is out
  91530. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  91531. ** make no changes to pParse->rc.
  91532. */
  91533. static void schemaIsValid(Parse *pParse){
  91534. sqlite3 *db = pParse->db;
  91535. int iDb;
  91536. int rc;
  91537. int cookie;
  91538. assert( pParse->checkSchema );
  91539. assert( sqlite3_mutex_held(db->mutex) );
  91540. for(iDb=0; iDb<db->nDb; iDb++){
  91541. int openedTransaction = 0; /* True if a transaction is opened */
  91542. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  91543. if( pBt==0 ) continue;
  91544. /* If there is not already a read-only (or read-write) transaction opened
  91545. ** on the b-tree database, open one now. If a transaction is opened, it
  91546. ** will be closed immediately after reading the meta-value. */
  91547. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  91548. rc = sqlite3BtreeBeginTrans(pBt, 0);
  91549. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  91550. db->mallocFailed = 1;
  91551. }
  91552. if( rc!=SQLITE_OK ) return;
  91553. openedTransaction = 1;
  91554. }
  91555. /* Read the schema cookie from the database. If it does not match the
  91556. ** value stored as part of the in-memory schema representation,
  91557. ** set Parse.rc to SQLITE_SCHEMA. */
  91558. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  91559. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  91560. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  91561. sqlite3ResetOneSchema(db, iDb);
  91562. pParse->rc = SQLITE_SCHEMA;
  91563. }
  91564. /* Close the transaction, if one was opened. */
  91565. if( openedTransaction ){
  91566. sqlite3BtreeCommit(pBt);
  91567. }
  91568. }
  91569. }
  91570. /*
  91571. ** Convert a schema pointer into the iDb index that indicates
  91572. ** which database file in db->aDb[] the schema refers to.
  91573. **
  91574. ** If the same database is attached more than once, the first
  91575. ** attached database is returned.
  91576. */
  91577. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  91578. int i = -1000000;
  91579. /* If pSchema is NULL, then return -1000000. This happens when code in
  91580. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  91581. ** created by a sub-select). In this case the return value of this
  91582. ** function should never be used.
  91583. **
  91584. ** We return -1000000 instead of the more usual -1 simply because using
  91585. ** -1000000 as the incorrect index into db->aDb[] is much
  91586. ** more likely to cause a segfault than -1 (of course there are assert()
  91587. ** statements too, but it never hurts to play the odds).
  91588. */
  91589. assert( sqlite3_mutex_held(db->mutex) );
  91590. if( pSchema ){
  91591. for(i=0; ALWAYS(i<db->nDb); i++){
  91592. if( db->aDb[i].pSchema==pSchema ){
  91593. break;
  91594. }
  91595. }
  91596. assert( i>=0 && i<db->nDb );
  91597. }
  91598. return i;
  91599. }
  91600. /*
  91601. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  91602. */
  91603. static int sqlite3Prepare(
  91604. sqlite3 *db, /* Database handle. */
  91605. const char *zSql, /* UTF-8 encoded SQL statement. */
  91606. int nBytes, /* Length of zSql in bytes. */
  91607. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  91608. Vdbe *pReprepare, /* VM being reprepared */
  91609. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  91610. const char **pzTail /* OUT: End of parsed string */
  91611. ){
  91612. Parse *pParse; /* Parsing context */
  91613. char *zErrMsg = 0; /* Error message */
  91614. int rc = SQLITE_OK; /* Result code */
  91615. int i; /* Loop counter */
  91616. /* Allocate the parsing context */
  91617. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  91618. if( pParse==0 ){
  91619. rc = SQLITE_NOMEM;
  91620. goto end_prepare;
  91621. }
  91622. pParse->pReprepare = pReprepare;
  91623. assert( ppStmt && *ppStmt==0 );
  91624. assert( !db->mallocFailed );
  91625. assert( sqlite3_mutex_held(db->mutex) );
  91626. /* Check to verify that it is possible to get a read lock on all
  91627. ** database schemas. The inability to get a read lock indicates that
  91628. ** some other database connection is holding a write-lock, which in
  91629. ** turn means that the other connection has made uncommitted changes
  91630. ** to the schema.
  91631. **
  91632. ** Were we to proceed and prepare the statement against the uncommitted
  91633. ** schema changes and if those schema changes are subsequently rolled
  91634. ** back and different changes are made in their place, then when this
  91635. ** prepared statement goes to run the schema cookie would fail to detect
  91636. ** the schema change. Disaster would follow.
  91637. **
  91638. ** This thread is currently holding mutexes on all Btrees (because
  91639. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  91640. ** is not possible for another thread to start a new schema change
  91641. ** while this routine is running. Hence, we do not need to hold
  91642. ** locks on the schema, we just need to make sure nobody else is
  91643. ** holding them.
  91644. **
  91645. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  91646. ** but it does *not* override schema lock detection, so this all still
  91647. ** works even if READ_UNCOMMITTED is set.
  91648. */
  91649. for(i=0; i<db->nDb; i++) {
  91650. Btree *pBt = db->aDb[i].pBt;
  91651. if( pBt ){
  91652. assert( sqlite3BtreeHoldsMutex(pBt) );
  91653. rc = sqlite3BtreeSchemaLocked(pBt);
  91654. if( rc ){
  91655. const char *zDb = db->aDb[i].zName;
  91656. sqlite3Error(db, rc, "database schema is locked: %s", zDb);
  91657. testcase( db->flags & SQLITE_ReadUncommitted );
  91658. goto end_prepare;
  91659. }
  91660. }
  91661. }
  91662. sqlite3VtabUnlockList(db);
  91663. pParse->db = db;
  91664. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  91665. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  91666. char *zSqlCopy;
  91667. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  91668. testcase( nBytes==mxLen );
  91669. testcase( nBytes==mxLen+1 );
  91670. if( nBytes>mxLen ){
  91671. sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
  91672. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  91673. goto end_prepare;
  91674. }
  91675. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  91676. if( zSqlCopy ){
  91677. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  91678. sqlite3DbFree(db, zSqlCopy);
  91679. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  91680. }else{
  91681. pParse->zTail = &zSql[nBytes];
  91682. }
  91683. }else{
  91684. sqlite3RunParser(pParse, zSql, &zErrMsg);
  91685. }
  91686. assert( 0==pParse->nQueryLoop );
  91687. if( db->mallocFailed ){
  91688. pParse->rc = SQLITE_NOMEM;
  91689. }
  91690. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  91691. if( pParse->checkSchema ){
  91692. schemaIsValid(pParse);
  91693. }
  91694. if( db->mallocFailed ){
  91695. pParse->rc = SQLITE_NOMEM;
  91696. }
  91697. if( pzTail ){
  91698. *pzTail = pParse->zTail;
  91699. }
  91700. rc = pParse->rc;
  91701. #ifndef SQLITE_OMIT_EXPLAIN
  91702. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  91703. static const char * const azColName[] = {
  91704. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  91705. "selectid", "order", "from", "detail"
  91706. };
  91707. int iFirst, mx;
  91708. if( pParse->explain==2 ){
  91709. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  91710. iFirst = 8;
  91711. mx = 12;
  91712. }else{
  91713. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  91714. iFirst = 0;
  91715. mx = 8;
  91716. }
  91717. for(i=iFirst; i<mx; i++){
  91718. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  91719. azColName[i], SQLITE_STATIC);
  91720. }
  91721. }
  91722. #endif
  91723. if( db->init.busy==0 ){
  91724. Vdbe *pVdbe = pParse->pVdbe;
  91725. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  91726. }
  91727. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  91728. sqlite3VdbeFinalize(pParse->pVdbe);
  91729. assert(!(*ppStmt));
  91730. }else{
  91731. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  91732. }
  91733. if( zErrMsg ){
  91734. sqlite3Error(db, rc, "%s", zErrMsg);
  91735. sqlite3DbFree(db, zErrMsg);
  91736. }else{
  91737. sqlite3Error(db, rc, 0);
  91738. }
  91739. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  91740. while( pParse->pTriggerPrg ){
  91741. TriggerPrg *pT = pParse->pTriggerPrg;
  91742. pParse->pTriggerPrg = pT->pNext;
  91743. sqlite3DbFree(db, pT);
  91744. }
  91745. end_prepare:
  91746. sqlite3StackFree(db, pParse);
  91747. rc = sqlite3ApiExit(db, rc);
  91748. assert( (rc&db->errMask)==rc );
  91749. return rc;
  91750. }
  91751. static int sqlite3LockAndPrepare(
  91752. sqlite3 *db, /* Database handle. */
  91753. const char *zSql, /* UTF-8 encoded SQL statement. */
  91754. int nBytes, /* Length of zSql in bytes. */
  91755. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  91756. Vdbe *pOld, /* VM being reprepared */
  91757. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  91758. const char **pzTail /* OUT: End of parsed string */
  91759. ){
  91760. int rc;
  91761. assert( ppStmt!=0 );
  91762. *ppStmt = 0;
  91763. if( !sqlite3SafetyCheckOk(db) ){
  91764. return SQLITE_MISUSE_BKPT;
  91765. }
  91766. sqlite3_mutex_enter(db->mutex);
  91767. sqlite3BtreeEnterAll(db);
  91768. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  91769. if( rc==SQLITE_SCHEMA ){
  91770. sqlite3_finalize(*ppStmt);
  91771. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  91772. }
  91773. sqlite3BtreeLeaveAll(db);
  91774. sqlite3_mutex_leave(db->mutex);
  91775. assert( rc==SQLITE_OK || *ppStmt==0 );
  91776. return rc;
  91777. }
  91778. /*
  91779. ** Rerun the compilation of a statement after a schema change.
  91780. **
  91781. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  91782. ** if the statement cannot be recompiled because another connection has
  91783. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  91784. ** occurs, return SQLITE_SCHEMA.
  91785. */
  91786. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  91787. int rc;
  91788. sqlite3_stmt *pNew;
  91789. const char *zSql;
  91790. sqlite3 *db;
  91791. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  91792. zSql = sqlite3_sql((sqlite3_stmt *)p);
  91793. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  91794. db = sqlite3VdbeDb(p);
  91795. assert( sqlite3_mutex_held(db->mutex) );
  91796. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  91797. if( rc ){
  91798. if( rc==SQLITE_NOMEM ){
  91799. db->mallocFailed = 1;
  91800. }
  91801. assert( pNew==0 );
  91802. return rc;
  91803. }else{
  91804. assert( pNew!=0 );
  91805. }
  91806. sqlite3VdbeSwap((Vdbe*)pNew, p);
  91807. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  91808. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  91809. sqlite3VdbeFinalize((Vdbe*)pNew);
  91810. return SQLITE_OK;
  91811. }
  91812. /*
  91813. ** Two versions of the official API. Legacy and new use. In the legacy
  91814. ** version, the original SQL text is not saved in the prepared statement
  91815. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  91816. ** sqlite3_step(). In the new version, the original SQL text is retained
  91817. ** and the statement is automatically recompiled if an schema change
  91818. ** occurs.
  91819. */
  91820. SQLITE_API int sqlite3_prepare(
  91821. sqlite3 *db, /* Database handle. */
  91822. const char *zSql, /* UTF-8 encoded SQL statement. */
  91823. int nBytes, /* Length of zSql in bytes. */
  91824. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  91825. const char **pzTail /* OUT: End of parsed string */
  91826. ){
  91827. int rc;
  91828. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  91829. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  91830. return rc;
  91831. }
  91832. SQLITE_API int sqlite3_prepare_v2(
  91833. sqlite3 *db, /* Database handle. */
  91834. const char *zSql, /* UTF-8 encoded SQL statement. */
  91835. int nBytes, /* Length of zSql in bytes. */
  91836. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  91837. const char **pzTail /* OUT: End of parsed string */
  91838. ){
  91839. int rc;
  91840. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  91841. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  91842. return rc;
  91843. }
  91844. #ifndef SQLITE_OMIT_UTF16
  91845. /*
  91846. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  91847. */
  91848. static int sqlite3Prepare16(
  91849. sqlite3 *db, /* Database handle. */
  91850. const void *zSql, /* UTF-16 encoded SQL statement. */
  91851. int nBytes, /* Length of zSql in bytes. */
  91852. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  91853. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  91854. const void **pzTail /* OUT: End of parsed string */
  91855. ){
  91856. /* This function currently works by first transforming the UTF-16
  91857. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  91858. ** tricky bit is figuring out the pointer to return in *pzTail.
  91859. */
  91860. char *zSql8;
  91861. const char *zTail8 = 0;
  91862. int rc = SQLITE_OK;
  91863. assert( ppStmt );
  91864. *ppStmt = 0;
  91865. if( !sqlite3SafetyCheckOk(db) ){
  91866. return SQLITE_MISUSE_BKPT;
  91867. }
  91868. if( nBytes>=0 ){
  91869. int sz;
  91870. const char *z = (const char*)zSql;
  91871. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  91872. nBytes = sz;
  91873. }
  91874. sqlite3_mutex_enter(db->mutex);
  91875. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  91876. if( zSql8 ){
  91877. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  91878. }
  91879. if( zTail8 && pzTail ){
  91880. /* If sqlite3_prepare returns a tail pointer, we calculate the
  91881. ** equivalent pointer into the UTF-16 string by counting the unicode
  91882. ** characters between zSql8 and zTail8, and then returning a pointer
  91883. ** the same number of characters into the UTF-16 string.
  91884. */
  91885. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  91886. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  91887. }
  91888. sqlite3DbFree(db, zSql8);
  91889. rc = sqlite3ApiExit(db, rc);
  91890. sqlite3_mutex_leave(db->mutex);
  91891. return rc;
  91892. }
  91893. /*
  91894. ** Two versions of the official API. Legacy and new use. In the legacy
  91895. ** version, the original SQL text is not saved in the prepared statement
  91896. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  91897. ** sqlite3_step(). In the new version, the original SQL text is retained
  91898. ** and the statement is automatically recompiled if an schema change
  91899. ** occurs.
  91900. */
  91901. SQLITE_API int sqlite3_prepare16(
  91902. sqlite3 *db, /* Database handle. */
  91903. const void *zSql, /* UTF-16 encoded SQL statement. */
  91904. int nBytes, /* Length of zSql in bytes. */
  91905. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  91906. const void **pzTail /* OUT: End of parsed string */
  91907. ){
  91908. int rc;
  91909. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  91910. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  91911. return rc;
  91912. }
  91913. SQLITE_API int sqlite3_prepare16_v2(
  91914. sqlite3 *db, /* Database handle. */
  91915. const void *zSql, /* UTF-16 encoded SQL statement. */
  91916. int nBytes, /* Length of zSql in bytes. */
  91917. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  91918. const void **pzTail /* OUT: End of parsed string */
  91919. ){
  91920. int rc;
  91921. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  91922. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  91923. return rc;
  91924. }
  91925. #endif /* SQLITE_OMIT_UTF16 */
  91926. /************** End of prepare.c *********************************************/
  91927. /************** Begin file select.c ******************************************/
  91928. /*
  91929. ** 2001 September 15
  91930. **
  91931. ** The author disclaims copyright to this source code. In place of
  91932. ** a legal notice, here is a blessing:
  91933. **
  91934. ** May you do good and not evil.
  91935. ** May you find forgiveness for yourself and forgive others.
  91936. ** May you share freely, never taking more than you give.
  91937. **
  91938. *************************************************************************
  91939. ** This file contains C code routines that are called by the parser
  91940. ** to handle SELECT statements in SQLite.
  91941. */
  91942. /*
  91943. ** Delete all the content of a Select structure but do not deallocate
  91944. ** the select structure itself.
  91945. */
  91946. static void clearSelect(sqlite3 *db, Select *p){
  91947. sqlite3ExprListDelete(db, p->pEList);
  91948. sqlite3SrcListDelete(db, p->pSrc);
  91949. sqlite3ExprDelete(db, p->pWhere);
  91950. sqlite3ExprListDelete(db, p->pGroupBy);
  91951. sqlite3ExprDelete(db, p->pHaving);
  91952. sqlite3ExprListDelete(db, p->pOrderBy);
  91953. sqlite3SelectDelete(db, p->pPrior);
  91954. sqlite3ExprDelete(db, p->pLimit);
  91955. sqlite3ExprDelete(db, p->pOffset);
  91956. }
  91957. /*
  91958. ** Initialize a SelectDest structure.
  91959. */
  91960. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  91961. pDest->eDest = (u8)eDest;
  91962. pDest->iSDParm = iParm;
  91963. pDest->affSdst = 0;
  91964. pDest->iSdst = 0;
  91965. pDest->nSdst = 0;
  91966. }
  91967. /*
  91968. ** Allocate a new Select structure and return a pointer to that
  91969. ** structure.
  91970. */
  91971. SQLITE_PRIVATE Select *sqlite3SelectNew(
  91972. Parse *pParse, /* Parsing context */
  91973. ExprList *pEList, /* which columns to include in the result */
  91974. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  91975. Expr *pWhere, /* the WHERE clause */
  91976. ExprList *pGroupBy, /* the GROUP BY clause */
  91977. Expr *pHaving, /* the HAVING clause */
  91978. ExprList *pOrderBy, /* the ORDER BY clause */
  91979. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  91980. Expr *pLimit, /* LIMIT value. NULL means not used */
  91981. Expr *pOffset /* OFFSET value. NULL means no offset */
  91982. ){
  91983. Select *pNew;
  91984. Select standin;
  91985. sqlite3 *db = pParse->db;
  91986. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  91987. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  91988. if( pNew==0 ){
  91989. assert( db->mallocFailed );
  91990. pNew = &standin;
  91991. memset(pNew, 0, sizeof(*pNew));
  91992. }
  91993. if( pEList==0 ){
  91994. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  91995. }
  91996. pNew->pEList = pEList;
  91997. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  91998. pNew->pSrc = pSrc;
  91999. pNew->pWhere = pWhere;
  92000. pNew->pGroupBy = pGroupBy;
  92001. pNew->pHaving = pHaving;
  92002. pNew->pOrderBy = pOrderBy;
  92003. pNew->selFlags = selFlags;
  92004. pNew->op = TK_SELECT;
  92005. pNew->pLimit = pLimit;
  92006. pNew->pOffset = pOffset;
  92007. assert( pOffset==0 || pLimit!=0 );
  92008. pNew->addrOpenEphm[0] = -1;
  92009. pNew->addrOpenEphm[1] = -1;
  92010. pNew->addrOpenEphm[2] = -1;
  92011. if( db->mallocFailed ) {
  92012. clearSelect(db, pNew);
  92013. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  92014. pNew = 0;
  92015. }else{
  92016. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  92017. }
  92018. assert( pNew!=&standin );
  92019. return pNew;
  92020. }
  92021. /*
  92022. ** Delete the given Select structure and all of its substructures.
  92023. */
  92024. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  92025. if( p ){
  92026. clearSelect(db, p);
  92027. sqlite3DbFree(db, p);
  92028. }
  92029. }
  92030. /*
  92031. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  92032. ** type of join. Return an integer constant that expresses that type
  92033. ** in terms of the following bit values:
  92034. **
  92035. ** JT_INNER
  92036. ** JT_CROSS
  92037. ** JT_OUTER
  92038. ** JT_NATURAL
  92039. ** JT_LEFT
  92040. ** JT_RIGHT
  92041. **
  92042. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  92043. **
  92044. ** If an illegal or unsupported join type is seen, then still return
  92045. ** a join type, but put an error in the pParse structure.
  92046. */
  92047. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  92048. int jointype = 0;
  92049. Token *apAll[3];
  92050. Token *p;
  92051. /* 0123456789 123456789 123456789 123 */
  92052. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  92053. static const struct {
  92054. u8 i; /* Beginning of keyword text in zKeyText[] */
  92055. u8 nChar; /* Length of the keyword in characters */
  92056. u8 code; /* Join type mask */
  92057. } aKeyword[] = {
  92058. /* natural */ { 0, 7, JT_NATURAL },
  92059. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  92060. /* outer */ { 10, 5, JT_OUTER },
  92061. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  92062. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  92063. /* inner */ { 23, 5, JT_INNER },
  92064. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  92065. };
  92066. int i, j;
  92067. apAll[0] = pA;
  92068. apAll[1] = pB;
  92069. apAll[2] = pC;
  92070. for(i=0; i<3 && apAll[i]; i++){
  92071. p = apAll[i];
  92072. for(j=0; j<ArraySize(aKeyword); j++){
  92073. if( p->n==aKeyword[j].nChar
  92074. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  92075. jointype |= aKeyword[j].code;
  92076. break;
  92077. }
  92078. }
  92079. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  92080. if( j>=ArraySize(aKeyword) ){
  92081. jointype |= JT_ERROR;
  92082. break;
  92083. }
  92084. }
  92085. if(
  92086. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  92087. (jointype & JT_ERROR)!=0
  92088. ){
  92089. const char *zSp = " ";
  92090. assert( pB!=0 );
  92091. if( pC==0 ){ zSp++; }
  92092. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  92093. "%T %T%s%T", pA, pB, zSp, pC);
  92094. jointype = JT_INNER;
  92095. }else if( (jointype & JT_OUTER)!=0
  92096. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  92097. sqlite3ErrorMsg(pParse,
  92098. "RIGHT and FULL OUTER JOINs are not currently supported");
  92099. jointype = JT_INNER;
  92100. }
  92101. return jointype;
  92102. }
  92103. /*
  92104. ** Return the index of a column in a table. Return -1 if the column
  92105. ** is not contained in the table.
  92106. */
  92107. static int columnIndex(Table *pTab, const char *zCol){
  92108. int i;
  92109. for(i=0; i<pTab->nCol; i++){
  92110. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  92111. }
  92112. return -1;
  92113. }
  92114. /*
  92115. ** Search the first N tables in pSrc, from left to right, looking for a
  92116. ** table that has a column named zCol.
  92117. **
  92118. ** When found, set *piTab and *piCol to the table index and column index
  92119. ** of the matching column and return TRUE.
  92120. **
  92121. ** If not found, return FALSE.
  92122. */
  92123. static int tableAndColumnIndex(
  92124. SrcList *pSrc, /* Array of tables to search */
  92125. int N, /* Number of tables in pSrc->a[] to search */
  92126. const char *zCol, /* Name of the column we are looking for */
  92127. int *piTab, /* Write index of pSrc->a[] here */
  92128. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  92129. ){
  92130. int i; /* For looping over tables in pSrc */
  92131. int iCol; /* Index of column matching zCol */
  92132. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  92133. for(i=0; i<N; i++){
  92134. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  92135. if( iCol>=0 ){
  92136. if( piTab ){
  92137. *piTab = i;
  92138. *piCol = iCol;
  92139. }
  92140. return 1;
  92141. }
  92142. }
  92143. return 0;
  92144. }
  92145. /*
  92146. ** This function is used to add terms implied by JOIN syntax to the
  92147. ** WHERE clause expression of a SELECT statement. The new term, which
  92148. ** is ANDed with the existing WHERE clause, is of the form:
  92149. **
  92150. ** (tab1.col1 = tab2.col2)
  92151. **
  92152. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  92153. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  92154. ** column iColRight of tab2.
  92155. */
  92156. static void addWhereTerm(
  92157. Parse *pParse, /* Parsing context */
  92158. SrcList *pSrc, /* List of tables in FROM clause */
  92159. int iLeft, /* Index of first table to join in pSrc */
  92160. int iColLeft, /* Index of column in first table */
  92161. int iRight, /* Index of second table in pSrc */
  92162. int iColRight, /* Index of column in second table */
  92163. int isOuterJoin, /* True if this is an OUTER join */
  92164. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  92165. ){
  92166. sqlite3 *db = pParse->db;
  92167. Expr *pE1;
  92168. Expr *pE2;
  92169. Expr *pEq;
  92170. assert( iLeft<iRight );
  92171. assert( pSrc->nSrc>iRight );
  92172. assert( pSrc->a[iLeft].pTab );
  92173. assert( pSrc->a[iRight].pTab );
  92174. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  92175. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  92176. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  92177. if( pEq && isOuterJoin ){
  92178. ExprSetProperty(pEq, EP_FromJoin);
  92179. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  92180. ExprSetVVAProperty(pEq, EP_NoReduce);
  92181. pEq->iRightJoinTable = (i16)pE2->iTable;
  92182. }
  92183. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  92184. }
  92185. /*
  92186. ** Set the EP_FromJoin property on all terms of the given expression.
  92187. ** And set the Expr.iRightJoinTable to iTable for every term in the
  92188. ** expression.
  92189. **
  92190. ** The EP_FromJoin property is used on terms of an expression to tell
  92191. ** the LEFT OUTER JOIN processing logic that this term is part of the
  92192. ** join restriction specified in the ON or USING clause and not a part
  92193. ** of the more general WHERE clause. These terms are moved over to the
  92194. ** WHERE clause during join processing but we need to remember that they
  92195. ** originated in the ON or USING clause.
  92196. **
  92197. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  92198. ** expression depends on table iRightJoinTable even if that table is not
  92199. ** explicitly mentioned in the expression. That information is needed
  92200. ** for cases like this:
  92201. **
  92202. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  92203. **
  92204. ** The where clause needs to defer the handling of the t1.x=5
  92205. ** term until after the t2 loop of the join. In that way, a
  92206. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  92207. ** defer the handling of t1.x=5, it will be processed immediately
  92208. ** after the t1 loop and rows with t1.x!=5 will never appear in
  92209. ** the output, which is incorrect.
  92210. */
  92211. static void setJoinExpr(Expr *p, int iTable){
  92212. while( p ){
  92213. ExprSetProperty(p, EP_FromJoin);
  92214. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  92215. ExprSetVVAProperty(p, EP_NoReduce);
  92216. p->iRightJoinTable = (i16)iTable;
  92217. setJoinExpr(p->pLeft, iTable);
  92218. p = p->pRight;
  92219. }
  92220. }
  92221. /*
  92222. ** This routine processes the join information for a SELECT statement.
  92223. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  92224. ** NATURAL joins also create extra WHERE clause terms.
  92225. **
  92226. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  92227. ** The left most table is the first entry in Select.pSrc. The right-most
  92228. ** table is the last entry. The join operator is held in the entry to
  92229. ** the left. Thus entry 0 contains the join operator for the join between
  92230. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  92231. ** also attached to the left entry.
  92232. **
  92233. ** This routine returns the number of errors encountered.
  92234. */
  92235. static int sqliteProcessJoin(Parse *pParse, Select *p){
  92236. SrcList *pSrc; /* All tables in the FROM clause */
  92237. int i, j; /* Loop counters */
  92238. struct SrcList_item *pLeft; /* Left table being joined */
  92239. struct SrcList_item *pRight; /* Right table being joined */
  92240. pSrc = p->pSrc;
  92241. pLeft = &pSrc->a[0];
  92242. pRight = &pLeft[1];
  92243. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  92244. Table *pLeftTab = pLeft->pTab;
  92245. Table *pRightTab = pRight->pTab;
  92246. int isOuter;
  92247. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  92248. isOuter = (pRight->jointype & JT_OUTER)!=0;
  92249. /* When the NATURAL keyword is present, add WHERE clause terms for
  92250. ** every column that the two tables have in common.
  92251. */
  92252. if( pRight->jointype & JT_NATURAL ){
  92253. if( pRight->pOn || pRight->pUsing ){
  92254. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  92255. "an ON or USING clause", 0);
  92256. return 1;
  92257. }
  92258. for(j=0; j<pRightTab->nCol; j++){
  92259. char *zName; /* Name of column in the right table */
  92260. int iLeft; /* Matching left table */
  92261. int iLeftCol; /* Matching column in the left table */
  92262. zName = pRightTab->aCol[j].zName;
  92263. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  92264. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  92265. isOuter, &p->pWhere);
  92266. }
  92267. }
  92268. }
  92269. /* Disallow both ON and USING clauses in the same join
  92270. */
  92271. if( pRight->pOn && pRight->pUsing ){
  92272. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  92273. "clauses in the same join");
  92274. return 1;
  92275. }
  92276. /* Add the ON clause to the end of the WHERE clause, connected by
  92277. ** an AND operator.
  92278. */
  92279. if( pRight->pOn ){
  92280. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  92281. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  92282. pRight->pOn = 0;
  92283. }
  92284. /* Create extra terms on the WHERE clause for each column named
  92285. ** in the USING clause. Example: If the two tables to be joined are
  92286. ** A and B and the USING clause names X, Y, and Z, then add this
  92287. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  92288. ** Report an error if any column mentioned in the USING clause is
  92289. ** not contained in both tables to be joined.
  92290. */
  92291. if( pRight->pUsing ){
  92292. IdList *pList = pRight->pUsing;
  92293. for(j=0; j<pList->nId; j++){
  92294. char *zName; /* Name of the term in the USING clause */
  92295. int iLeft; /* Table on the left with matching column name */
  92296. int iLeftCol; /* Column number of matching column on the left */
  92297. int iRightCol; /* Column number of matching column on the right */
  92298. zName = pList->a[j].zName;
  92299. iRightCol = columnIndex(pRightTab, zName);
  92300. if( iRightCol<0
  92301. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  92302. ){
  92303. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  92304. "not present in both tables", zName);
  92305. return 1;
  92306. }
  92307. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  92308. isOuter, &p->pWhere);
  92309. }
  92310. }
  92311. }
  92312. return 0;
  92313. }
  92314. /*
  92315. ** Insert code into "v" that will push the record on the top of the
  92316. ** stack into the sorter.
  92317. */
  92318. static void pushOntoSorter(
  92319. Parse *pParse, /* Parser context */
  92320. ExprList *pOrderBy, /* The ORDER BY clause */
  92321. Select *pSelect, /* The whole SELECT statement */
  92322. int regData /* Register holding data to be sorted */
  92323. ){
  92324. Vdbe *v = pParse->pVdbe;
  92325. int nExpr = pOrderBy->nExpr;
  92326. int regBase = sqlite3GetTempRange(pParse, nExpr+2);
  92327. int regRecord = sqlite3GetTempReg(pParse);
  92328. int op;
  92329. sqlite3ExprCacheClear(pParse);
  92330. sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
  92331. sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
  92332. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
  92333. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
  92334. if( pSelect->selFlags & SF_UseSorter ){
  92335. op = OP_SorterInsert;
  92336. }else{
  92337. op = OP_IdxInsert;
  92338. }
  92339. sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
  92340. sqlite3ReleaseTempReg(pParse, regRecord);
  92341. sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
  92342. if( pSelect->iLimit ){
  92343. int addr1, addr2;
  92344. int iLimit;
  92345. if( pSelect->iOffset ){
  92346. iLimit = pSelect->iOffset+1;
  92347. }else{
  92348. iLimit = pSelect->iLimit;
  92349. }
  92350. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
  92351. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  92352. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  92353. sqlite3VdbeJumpHere(v, addr1);
  92354. sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
  92355. sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
  92356. sqlite3VdbeJumpHere(v, addr2);
  92357. }
  92358. }
  92359. /*
  92360. ** Add code to implement the OFFSET
  92361. */
  92362. static void codeOffset(
  92363. Vdbe *v, /* Generate code into this VM */
  92364. Select *p, /* The SELECT statement being coded */
  92365. int iContinue /* Jump here to skip the current record */
  92366. ){
  92367. if( p->iOffset && iContinue!=0 ){
  92368. int addr;
  92369. sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
  92370. addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
  92371. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  92372. VdbeComment((v, "skip OFFSET records"));
  92373. sqlite3VdbeJumpHere(v, addr);
  92374. }
  92375. }
  92376. /*
  92377. ** Add code that will check to make sure the N registers starting at iMem
  92378. ** form a distinct entry. iTab is a sorting index that holds previously
  92379. ** seen combinations of the N values. A new entry is made in iTab
  92380. ** if the current N values are new.
  92381. **
  92382. ** A jump to addrRepeat is made and the N+1 values are popped from the
  92383. ** stack if the top N elements are not distinct.
  92384. */
  92385. static void codeDistinct(
  92386. Parse *pParse, /* Parsing and code generating context */
  92387. int iTab, /* A sorting index used to test for distinctness */
  92388. int addrRepeat, /* Jump to here if not distinct */
  92389. int N, /* Number of elements */
  92390. int iMem /* First element */
  92391. ){
  92392. Vdbe *v;
  92393. int r1;
  92394. v = pParse->pVdbe;
  92395. r1 = sqlite3GetTempReg(pParse);
  92396. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
  92397. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  92398. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  92399. sqlite3ReleaseTempReg(pParse, r1);
  92400. }
  92401. #ifndef SQLITE_OMIT_SUBQUERY
  92402. /*
  92403. ** Generate an error message when a SELECT is used within a subexpression
  92404. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  92405. ** column. We do this in a subroutine because the error used to occur
  92406. ** in multiple places. (The error only occurs in one place now, but we
  92407. ** retain the subroutine to minimize code disruption.)
  92408. */
  92409. static int checkForMultiColumnSelectError(
  92410. Parse *pParse, /* Parse context. */
  92411. SelectDest *pDest, /* Destination of SELECT results */
  92412. int nExpr /* Number of result columns returned by SELECT */
  92413. ){
  92414. int eDest = pDest->eDest;
  92415. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  92416. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  92417. "a SELECT that is part of an expression");
  92418. return 1;
  92419. }else{
  92420. return 0;
  92421. }
  92422. }
  92423. #endif
  92424. /*
  92425. ** An instance of the following object is used to record information about
  92426. ** how to process the DISTINCT keyword, to simplify passing that information
  92427. ** into the selectInnerLoop() routine.
  92428. */
  92429. typedef struct DistinctCtx DistinctCtx;
  92430. struct DistinctCtx {
  92431. u8 isTnct; /* True if the DISTINCT keyword is present */
  92432. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  92433. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  92434. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  92435. };
  92436. /*
  92437. ** This routine generates the code for the inside of the inner loop
  92438. ** of a SELECT.
  92439. **
  92440. ** If srcTab and nColumn are both zero, then the pEList expressions
  92441. ** are evaluated in order to get the data for this row. If nColumn>0
  92442. ** then data is pulled from srcTab and pEList is used only to get the
  92443. ** datatypes for each column.
  92444. */
  92445. static void selectInnerLoop(
  92446. Parse *pParse, /* The parser context */
  92447. Select *p, /* The complete select statement being coded */
  92448. ExprList *pEList, /* List of values being extracted */
  92449. int srcTab, /* Pull data from this table */
  92450. int nColumn, /* Number of columns in the source table */
  92451. ExprList *pOrderBy, /* If not NULL, sort results using this key */
  92452. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  92453. SelectDest *pDest, /* How to dispose of the results */
  92454. int iContinue, /* Jump here to continue with next row */
  92455. int iBreak /* Jump here to break out of the inner loop */
  92456. ){
  92457. Vdbe *v = pParse->pVdbe;
  92458. int i;
  92459. int hasDistinct; /* True if the DISTINCT keyword is present */
  92460. int regResult; /* Start of memory holding result set */
  92461. int eDest = pDest->eDest; /* How to dispose of results */
  92462. int iParm = pDest->iSDParm; /* First argument to disposal method */
  92463. int nResultCol; /* Number of result columns */
  92464. assert( v );
  92465. if( NEVER(v==0) ) return;
  92466. assert( pEList!=0 );
  92467. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  92468. if( pOrderBy==0 && !hasDistinct ){
  92469. codeOffset(v, p, iContinue);
  92470. }
  92471. /* Pull the requested columns.
  92472. */
  92473. if( nColumn>0 ){
  92474. nResultCol = nColumn;
  92475. }else{
  92476. nResultCol = pEList->nExpr;
  92477. }
  92478. if( pDest->iSdst==0 ){
  92479. pDest->iSdst = pParse->nMem+1;
  92480. pDest->nSdst = nResultCol;
  92481. pParse->nMem += nResultCol;
  92482. }else{
  92483. assert( pDest->nSdst==nResultCol );
  92484. }
  92485. regResult = pDest->iSdst;
  92486. if( nColumn>0 ){
  92487. for(i=0; i<nColumn; i++){
  92488. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  92489. }
  92490. }else if( eDest!=SRT_Exists ){
  92491. /* If the destination is an EXISTS(...) expression, the actual
  92492. ** values returned by the SELECT are not required.
  92493. */
  92494. sqlite3ExprCacheClear(pParse);
  92495. sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
  92496. }
  92497. nColumn = nResultCol;
  92498. /* If the DISTINCT keyword was present on the SELECT statement
  92499. ** and this row has been seen before, then do not make this row
  92500. ** part of the result.
  92501. */
  92502. if( hasDistinct ){
  92503. assert( pEList!=0 );
  92504. assert( pEList->nExpr==nColumn );
  92505. switch( pDistinct->eTnctType ){
  92506. case WHERE_DISTINCT_ORDERED: {
  92507. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  92508. int iJump; /* Jump destination */
  92509. int regPrev; /* Previous row content */
  92510. /* Allocate space for the previous row */
  92511. regPrev = pParse->nMem+1;
  92512. pParse->nMem += nColumn;
  92513. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  92514. ** sets the MEM_Cleared bit on the first register of the
  92515. ** previous value. This will cause the OP_Ne below to always
  92516. ** fail on the first iteration of the loop even if the first
  92517. ** row is all NULLs.
  92518. */
  92519. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  92520. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  92521. pOp->opcode = OP_Null;
  92522. pOp->p1 = 1;
  92523. pOp->p2 = regPrev;
  92524. iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
  92525. for(i=0; i<nColumn; i++){
  92526. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  92527. if( i<nColumn-1 ){
  92528. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  92529. }else{
  92530. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  92531. }
  92532. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  92533. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  92534. }
  92535. assert( sqlite3VdbeCurrentAddr(v)==iJump );
  92536. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
  92537. break;
  92538. }
  92539. case WHERE_DISTINCT_UNIQUE: {
  92540. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  92541. break;
  92542. }
  92543. default: {
  92544. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  92545. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
  92546. break;
  92547. }
  92548. }
  92549. if( pOrderBy==0 ){
  92550. codeOffset(v, p, iContinue);
  92551. }
  92552. }
  92553. switch( eDest ){
  92554. /* In this mode, write each query result to the key of the temporary
  92555. ** table iParm.
  92556. */
  92557. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  92558. case SRT_Union: {
  92559. int r1;
  92560. r1 = sqlite3GetTempReg(pParse);
  92561. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  92562. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  92563. sqlite3ReleaseTempReg(pParse, r1);
  92564. break;
  92565. }
  92566. /* Construct a record from the query result, but instead of
  92567. ** saving that record, use it as a key to delete elements from
  92568. ** the temporary table iParm.
  92569. */
  92570. case SRT_Except: {
  92571. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
  92572. break;
  92573. }
  92574. #endif
  92575. /* Store the result as data using a unique key.
  92576. */
  92577. case SRT_Table:
  92578. case SRT_EphemTab: {
  92579. int r1 = sqlite3GetTempReg(pParse);
  92580. testcase( eDest==SRT_Table );
  92581. testcase( eDest==SRT_EphemTab );
  92582. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  92583. if( pOrderBy ){
  92584. pushOntoSorter(pParse, pOrderBy, p, r1);
  92585. }else{
  92586. int r2 = sqlite3GetTempReg(pParse);
  92587. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  92588. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  92589. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  92590. sqlite3ReleaseTempReg(pParse, r2);
  92591. }
  92592. sqlite3ReleaseTempReg(pParse, r1);
  92593. break;
  92594. }
  92595. #ifndef SQLITE_OMIT_SUBQUERY
  92596. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  92597. ** then there should be a single item on the stack. Write this
  92598. ** item into the set table with bogus data.
  92599. */
  92600. case SRT_Set: {
  92601. assert( nColumn==1 );
  92602. pDest->affSdst =
  92603. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  92604. if( pOrderBy ){
  92605. /* At first glance you would think we could optimize out the
  92606. ** ORDER BY in this case since the order of entries in the set
  92607. ** does not matter. But there might be a LIMIT clause, in which
  92608. ** case the order does matter */
  92609. pushOntoSorter(pParse, pOrderBy, p, regResult);
  92610. }else{
  92611. int r1 = sqlite3GetTempReg(pParse);
  92612. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  92613. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  92614. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  92615. sqlite3ReleaseTempReg(pParse, r1);
  92616. }
  92617. break;
  92618. }
  92619. /* If any row exist in the result set, record that fact and abort.
  92620. */
  92621. case SRT_Exists: {
  92622. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  92623. /* The LIMIT clause will terminate the loop for us */
  92624. break;
  92625. }
  92626. /* If this is a scalar select that is part of an expression, then
  92627. ** store the results in the appropriate memory cell and break out
  92628. ** of the scan loop.
  92629. */
  92630. case SRT_Mem: {
  92631. assert( nColumn==1 );
  92632. if( pOrderBy ){
  92633. pushOntoSorter(pParse, pOrderBy, p, regResult);
  92634. }else{
  92635. sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
  92636. /* The LIMIT clause will jump out of the loop for us */
  92637. }
  92638. break;
  92639. }
  92640. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  92641. /* Send the data to the callback function or to a subroutine. In the
  92642. ** case of a subroutine, the subroutine itself is responsible for
  92643. ** popping the data from the stack.
  92644. */
  92645. case SRT_Coroutine:
  92646. case SRT_Output: {
  92647. testcase( eDest==SRT_Coroutine );
  92648. testcase( eDest==SRT_Output );
  92649. if( pOrderBy ){
  92650. int r1 = sqlite3GetTempReg(pParse);
  92651. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  92652. pushOntoSorter(pParse, pOrderBy, p, r1);
  92653. sqlite3ReleaseTempReg(pParse, r1);
  92654. }else if( eDest==SRT_Coroutine ){
  92655. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  92656. }else{
  92657. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
  92658. sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
  92659. }
  92660. break;
  92661. }
  92662. #if !defined(SQLITE_OMIT_TRIGGER)
  92663. /* Discard the results. This is used for SELECT statements inside
  92664. ** the body of a TRIGGER. The purpose of such selects is to call
  92665. ** user-defined functions that have side effects. We do not care
  92666. ** about the actual results of the select.
  92667. */
  92668. default: {
  92669. assert( eDest==SRT_Discard );
  92670. break;
  92671. }
  92672. #endif
  92673. }
  92674. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  92675. ** there is a sorter, in which case the sorter has already limited
  92676. ** the output for us.
  92677. */
  92678. if( pOrderBy==0 && p->iLimit ){
  92679. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  92680. }
  92681. }
  92682. /*
  92683. ** Allocate a KeyInfo object sufficient for an index of N columns.
  92684. **
  92685. ** Actually, always allocate one extra column for the rowid at the end
  92686. ** of the index. So the KeyInfo returned will have space sufficient for
  92687. ** N+1 columns.
  92688. */
  92689. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N){
  92690. KeyInfo *p = sqlite3DbMallocZero(db,
  92691. sizeof(KeyInfo) + (N+1)*(sizeof(CollSeq*)+1));
  92692. if( p ){
  92693. p->aSortOrder = (u8*)&p->aColl[N+1];
  92694. p->nField = (u16)N;
  92695. p->enc = ENC(db);
  92696. p->db = db;
  92697. }
  92698. return p;
  92699. }
  92700. /*
  92701. ** Given an expression list, generate a KeyInfo structure that records
  92702. ** the collating sequence for each expression in that expression list.
  92703. **
  92704. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  92705. ** KeyInfo structure is appropriate for initializing a virtual index to
  92706. ** implement that clause. If the ExprList is the result set of a SELECT
  92707. ** then the KeyInfo structure is appropriate for initializing a virtual
  92708. ** index to implement a DISTINCT test.
  92709. **
  92710. ** Space to hold the KeyInfo structure is obtain from malloc. The calling
  92711. ** function is responsible for seeing that this structure is eventually
  92712. ** freed. Add the KeyInfo structure to the P4 field of an opcode using
  92713. ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
  92714. */
  92715. static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  92716. int nExpr;
  92717. KeyInfo *pInfo;
  92718. struct ExprList_item *pItem;
  92719. sqlite3 *db = pParse->db;
  92720. int i;
  92721. nExpr = pList->nExpr;
  92722. pInfo = sqlite3KeyInfoAlloc(db, nExpr);
  92723. if( pInfo ){
  92724. for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
  92725. CollSeq *pColl;
  92726. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  92727. if( !pColl ) pColl = db->pDfltColl;
  92728. pInfo->aColl[i] = pColl;
  92729. pInfo->aSortOrder[i] = pItem->sortOrder;
  92730. }
  92731. }
  92732. return pInfo;
  92733. }
  92734. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  92735. /*
  92736. ** Name of the connection operator, used for error messages.
  92737. */
  92738. static const char *selectOpName(int id){
  92739. char *z;
  92740. switch( id ){
  92741. case TK_ALL: z = "UNION ALL"; break;
  92742. case TK_INTERSECT: z = "INTERSECT"; break;
  92743. case TK_EXCEPT: z = "EXCEPT"; break;
  92744. default: z = "UNION"; break;
  92745. }
  92746. return z;
  92747. }
  92748. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  92749. #ifndef SQLITE_OMIT_EXPLAIN
  92750. /*
  92751. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  92752. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  92753. ** where the caption is of the form:
  92754. **
  92755. ** "USE TEMP B-TREE FOR xxx"
  92756. **
  92757. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  92758. ** is determined by the zUsage argument.
  92759. */
  92760. static void explainTempTable(Parse *pParse, const char *zUsage){
  92761. if( pParse->explain==2 ){
  92762. Vdbe *v = pParse->pVdbe;
  92763. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  92764. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  92765. }
  92766. }
  92767. /*
  92768. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  92769. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  92770. ** in sqlite3Select() to assign values to structure member variables that
  92771. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  92772. ** code with #ifndef directives.
  92773. */
  92774. # define explainSetInteger(a, b) a = b
  92775. #else
  92776. /* No-op versions of the explainXXX() functions and macros. */
  92777. # define explainTempTable(y,z)
  92778. # define explainSetInteger(y,z)
  92779. #endif
  92780. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  92781. /*
  92782. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  92783. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  92784. ** where the caption is of one of the two forms:
  92785. **
  92786. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  92787. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  92788. **
  92789. ** where iSub1 and iSub2 are the integers passed as the corresponding
  92790. ** function parameters, and op is the text representation of the parameter
  92791. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  92792. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  92793. ** false, or the second form if it is true.
  92794. */
  92795. static void explainComposite(
  92796. Parse *pParse, /* Parse context */
  92797. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  92798. int iSub1, /* Subquery id 1 */
  92799. int iSub2, /* Subquery id 2 */
  92800. int bUseTmp /* True if a temp table was used */
  92801. ){
  92802. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  92803. if( pParse->explain==2 ){
  92804. Vdbe *v = pParse->pVdbe;
  92805. char *zMsg = sqlite3MPrintf(
  92806. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  92807. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  92808. );
  92809. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  92810. }
  92811. }
  92812. #else
  92813. /* No-op versions of the explainXXX() functions and macros. */
  92814. # define explainComposite(v,w,x,y,z)
  92815. #endif
  92816. /*
  92817. ** If the inner loop was generated using a non-null pOrderBy argument,
  92818. ** then the results were placed in a sorter. After the loop is terminated
  92819. ** we need to run the sorter and output the results. The following
  92820. ** routine generates the code needed to do that.
  92821. */
  92822. static void generateSortTail(
  92823. Parse *pParse, /* Parsing context */
  92824. Select *p, /* The SELECT statement */
  92825. Vdbe *v, /* Generate code into this VDBE */
  92826. int nColumn, /* Number of columns of data */
  92827. SelectDest *pDest /* Write the sorted results here */
  92828. ){
  92829. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  92830. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  92831. int addr;
  92832. int iTab;
  92833. int pseudoTab = 0;
  92834. ExprList *pOrderBy = p->pOrderBy;
  92835. int eDest = pDest->eDest;
  92836. int iParm = pDest->iSDParm;
  92837. int regRow;
  92838. int regRowid;
  92839. iTab = pOrderBy->iECursor;
  92840. regRow = sqlite3GetTempReg(pParse);
  92841. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  92842. pseudoTab = pParse->nTab++;
  92843. sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
  92844. regRowid = 0;
  92845. }else{
  92846. regRowid = sqlite3GetTempReg(pParse);
  92847. }
  92848. if( p->selFlags & SF_UseSorter ){
  92849. int regSortOut = ++pParse->nMem;
  92850. int ptab2 = pParse->nTab++;
  92851. sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
  92852. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  92853. codeOffset(v, p, addrContinue);
  92854. sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
  92855. sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
  92856. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  92857. }else{
  92858. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
  92859. codeOffset(v, p, addrContinue);
  92860. sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
  92861. }
  92862. switch( eDest ){
  92863. case SRT_Table:
  92864. case SRT_EphemTab: {
  92865. testcase( eDest==SRT_Table );
  92866. testcase( eDest==SRT_EphemTab );
  92867. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  92868. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  92869. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  92870. break;
  92871. }
  92872. #ifndef SQLITE_OMIT_SUBQUERY
  92873. case SRT_Set: {
  92874. assert( nColumn==1 );
  92875. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  92876. &pDest->affSdst, 1);
  92877. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  92878. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  92879. break;
  92880. }
  92881. case SRT_Mem: {
  92882. assert( nColumn==1 );
  92883. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  92884. /* The LIMIT clause will terminate the loop for us */
  92885. break;
  92886. }
  92887. #endif
  92888. default: {
  92889. int i;
  92890. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  92891. testcase( eDest==SRT_Output );
  92892. testcase( eDest==SRT_Coroutine );
  92893. for(i=0; i<nColumn; i++){
  92894. assert( regRow!=pDest->iSdst+i );
  92895. sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
  92896. if( i==0 ){
  92897. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  92898. }
  92899. }
  92900. if( eDest==SRT_Output ){
  92901. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  92902. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  92903. }else{
  92904. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  92905. }
  92906. break;
  92907. }
  92908. }
  92909. sqlite3ReleaseTempReg(pParse, regRow);
  92910. sqlite3ReleaseTempReg(pParse, regRowid);
  92911. /* The bottom of the loop
  92912. */
  92913. sqlite3VdbeResolveLabel(v, addrContinue);
  92914. if( p->selFlags & SF_UseSorter ){
  92915. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
  92916. }else{
  92917. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
  92918. }
  92919. sqlite3VdbeResolveLabel(v, addrBreak);
  92920. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  92921. sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  92922. }
  92923. }
  92924. /*
  92925. ** Return a pointer to a string containing the 'declaration type' of the
  92926. ** expression pExpr. The string may be treated as static by the caller.
  92927. **
  92928. ** Also try to estimate the size of the returned value and return that
  92929. ** result in *pEstWidth.
  92930. **
  92931. ** The declaration type is the exact datatype definition extracted from the
  92932. ** original CREATE TABLE statement if the expression is a column. The
  92933. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  92934. ** is considered a column can be complex in the presence of subqueries. The
  92935. ** result-set expression in all of the following SELECT statements is
  92936. ** considered a column by this function.
  92937. **
  92938. ** SELECT col FROM tbl;
  92939. ** SELECT (SELECT col FROM tbl;
  92940. ** SELECT (SELECT col FROM tbl);
  92941. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  92942. **
  92943. ** The declaration type for any expression other than a column is NULL.
  92944. **
  92945. ** This routine has either 3 or 6 parameters depending on whether or not
  92946. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  92947. */
  92948. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  92949. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  92950. static const char *columnTypeImpl(
  92951. NameContext *pNC,
  92952. Expr *pExpr,
  92953. const char **pzOrigDb,
  92954. const char **pzOrigTab,
  92955. const char **pzOrigCol,
  92956. u8 *pEstWidth
  92957. ){
  92958. char const *zOrigDb = 0;
  92959. char const *zOrigTab = 0;
  92960. char const *zOrigCol = 0;
  92961. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  92962. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  92963. static const char *columnTypeImpl(
  92964. NameContext *pNC,
  92965. Expr *pExpr,
  92966. u8 *pEstWidth
  92967. ){
  92968. #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  92969. char const *zType = 0;
  92970. int j;
  92971. u8 estWidth = 1;
  92972. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  92973. switch( pExpr->op ){
  92974. case TK_AGG_COLUMN:
  92975. case TK_COLUMN: {
  92976. /* The expression is a column. Locate the table the column is being
  92977. ** extracted from in NameContext.pSrcList. This table may be real
  92978. ** database table or a subquery.
  92979. */
  92980. Table *pTab = 0; /* Table structure column is extracted from */
  92981. Select *pS = 0; /* Select the column is extracted from */
  92982. int iCol = pExpr->iColumn; /* Index of column in pTab */
  92983. testcase( pExpr->op==TK_AGG_COLUMN );
  92984. testcase( pExpr->op==TK_COLUMN );
  92985. while( pNC && !pTab ){
  92986. SrcList *pTabList = pNC->pSrcList;
  92987. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  92988. if( j<pTabList->nSrc ){
  92989. pTab = pTabList->a[j].pTab;
  92990. pS = pTabList->a[j].pSelect;
  92991. }else{
  92992. pNC = pNC->pNext;
  92993. }
  92994. }
  92995. if( pTab==0 ){
  92996. /* At one time, code such as "SELECT new.x" within a trigger would
  92997. ** cause this condition to run. Since then, we have restructured how
  92998. ** trigger code is generated and so this condition is no longer
  92999. ** possible. However, it can still be true for statements like
  93000. ** the following:
  93001. **
  93002. ** CREATE TABLE t1(col INTEGER);
  93003. ** SELECT (SELECT t1.col) FROM FROM t1;
  93004. **
  93005. ** when columnType() is called on the expression "t1.col" in the
  93006. ** sub-select. In this case, set the column type to NULL, even
  93007. ** though it should really be "INTEGER".
  93008. **
  93009. ** This is not a problem, as the column type of "t1.col" is never
  93010. ** used. When columnType() is called on the expression
  93011. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  93012. ** branch below. */
  93013. break;
  93014. }
  93015. assert( pTab && pExpr->pTab==pTab );
  93016. if( pS ){
  93017. /* The "table" is actually a sub-select or a view in the FROM clause
  93018. ** of the SELECT statement. Return the declaration type and origin
  93019. ** data for the result-set column of the sub-select.
  93020. */
  93021. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  93022. /* If iCol is less than zero, then the expression requests the
  93023. ** rowid of the sub-select or view. This expression is legal (see
  93024. ** test case misc2.2.2) - it always evaluates to NULL.
  93025. */
  93026. NameContext sNC;
  93027. Expr *p = pS->pEList->a[iCol].pExpr;
  93028. sNC.pSrcList = pS->pSrc;
  93029. sNC.pNext = pNC;
  93030. sNC.pParse = pNC->pParse;
  93031. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  93032. }
  93033. }else if( ALWAYS(pTab->pSchema) ){
  93034. /* A real table */
  93035. assert( !pS );
  93036. if( iCol<0 ) iCol = pTab->iPKey;
  93037. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  93038. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  93039. if( iCol<0 ){
  93040. zType = "INTEGER";
  93041. zOrigCol = "rowid";
  93042. }else{
  93043. zType = pTab->aCol[iCol].zType;
  93044. zOrigCol = pTab->aCol[iCol].zName;
  93045. estWidth = pTab->aCol[iCol].szEst;
  93046. }
  93047. zOrigTab = pTab->zName;
  93048. if( pNC->pParse ){
  93049. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  93050. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  93051. }
  93052. #else
  93053. if( iCol<0 ){
  93054. zType = "INTEGER";
  93055. }else{
  93056. zType = pTab->aCol[iCol].zType;
  93057. estWidth = pTab->aCol[iCol].szEst;
  93058. }
  93059. #endif
  93060. }
  93061. break;
  93062. }
  93063. #ifndef SQLITE_OMIT_SUBQUERY
  93064. case TK_SELECT: {
  93065. /* The expression is a sub-select. Return the declaration type and
  93066. ** origin info for the single column in the result set of the SELECT
  93067. ** statement.
  93068. */
  93069. NameContext sNC;
  93070. Select *pS = pExpr->x.pSelect;
  93071. Expr *p = pS->pEList->a[0].pExpr;
  93072. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  93073. sNC.pSrcList = pS->pSrc;
  93074. sNC.pNext = pNC;
  93075. sNC.pParse = pNC->pParse;
  93076. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  93077. break;
  93078. }
  93079. #endif
  93080. }
  93081. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  93082. if( pzOrigDb ){
  93083. assert( pzOrigTab && pzOrigCol );
  93084. *pzOrigDb = zOrigDb;
  93085. *pzOrigTab = zOrigTab;
  93086. *pzOrigCol = zOrigCol;
  93087. }
  93088. #endif
  93089. if( pEstWidth ) *pEstWidth = estWidth;
  93090. return zType;
  93091. }
  93092. /*
  93093. ** Generate code that will tell the VDBE the declaration types of columns
  93094. ** in the result set.
  93095. */
  93096. static void generateColumnTypes(
  93097. Parse *pParse, /* Parser context */
  93098. SrcList *pTabList, /* List of tables */
  93099. ExprList *pEList /* Expressions defining the result set */
  93100. ){
  93101. #ifndef SQLITE_OMIT_DECLTYPE
  93102. Vdbe *v = pParse->pVdbe;
  93103. int i;
  93104. NameContext sNC;
  93105. sNC.pSrcList = pTabList;
  93106. sNC.pParse = pParse;
  93107. for(i=0; i<pEList->nExpr; i++){
  93108. Expr *p = pEList->a[i].pExpr;
  93109. const char *zType;
  93110. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  93111. const char *zOrigDb = 0;
  93112. const char *zOrigTab = 0;
  93113. const char *zOrigCol = 0;
  93114. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  93115. /* The vdbe must make its own copy of the column-type and other
  93116. ** column specific strings, in case the schema is reset before this
  93117. ** virtual machine is deleted.
  93118. */
  93119. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  93120. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  93121. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  93122. #else
  93123. zType = columnType(&sNC, p, 0, 0, 0, 0);
  93124. #endif
  93125. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  93126. }
  93127. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  93128. }
  93129. /*
  93130. ** Generate code that will tell the VDBE the names of columns
  93131. ** in the result set. This information is used to provide the
  93132. ** azCol[] values in the callback.
  93133. */
  93134. static void generateColumnNames(
  93135. Parse *pParse, /* Parser context */
  93136. SrcList *pTabList, /* List of tables */
  93137. ExprList *pEList /* Expressions defining the result set */
  93138. ){
  93139. Vdbe *v = pParse->pVdbe;
  93140. int i, j;
  93141. sqlite3 *db = pParse->db;
  93142. int fullNames, shortNames;
  93143. #ifndef SQLITE_OMIT_EXPLAIN
  93144. /* If this is an EXPLAIN, skip this step */
  93145. if( pParse->explain ){
  93146. return;
  93147. }
  93148. #endif
  93149. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  93150. pParse->colNamesSet = 1;
  93151. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  93152. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  93153. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  93154. for(i=0; i<pEList->nExpr; i++){
  93155. Expr *p;
  93156. p = pEList->a[i].pExpr;
  93157. if( NEVER(p==0) ) continue;
  93158. if( pEList->a[i].zName ){
  93159. char *zName = pEList->a[i].zName;
  93160. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  93161. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  93162. Table *pTab;
  93163. char *zCol;
  93164. int iCol = p->iColumn;
  93165. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  93166. if( pTabList->a[j].iCursor==p->iTable ) break;
  93167. }
  93168. assert( j<pTabList->nSrc );
  93169. pTab = pTabList->a[j].pTab;
  93170. if( iCol<0 ) iCol = pTab->iPKey;
  93171. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  93172. if( iCol<0 ){
  93173. zCol = "rowid";
  93174. }else{
  93175. zCol = pTab->aCol[iCol].zName;
  93176. }
  93177. if( !shortNames && !fullNames ){
  93178. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  93179. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  93180. }else if( fullNames ){
  93181. char *zName = 0;
  93182. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  93183. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  93184. }else{
  93185. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  93186. }
  93187. }else{
  93188. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  93189. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  93190. }
  93191. }
  93192. generateColumnTypes(pParse, pTabList, pEList);
  93193. }
  93194. /*
  93195. ** Given a an expression list (which is really the list of expressions
  93196. ** that form the result set of a SELECT statement) compute appropriate
  93197. ** column names for a table that would hold the expression list.
  93198. **
  93199. ** All column names will be unique.
  93200. **
  93201. ** Only the column names are computed. Column.zType, Column.zColl,
  93202. ** and other fields of Column are zeroed.
  93203. **
  93204. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  93205. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  93206. */
  93207. static int selectColumnsFromExprList(
  93208. Parse *pParse, /* Parsing context */
  93209. ExprList *pEList, /* Expr list from which to derive column names */
  93210. i16 *pnCol, /* Write the number of columns here */
  93211. Column **paCol /* Write the new column list here */
  93212. ){
  93213. sqlite3 *db = pParse->db; /* Database connection */
  93214. int i, j; /* Loop counters */
  93215. int cnt; /* Index added to make the name unique */
  93216. Column *aCol, *pCol; /* For looping over result columns */
  93217. int nCol; /* Number of columns in the result set */
  93218. Expr *p; /* Expression for a single result column */
  93219. char *zName; /* Column name */
  93220. int nName; /* Size of name in zName[] */
  93221. if( pEList ){
  93222. nCol = pEList->nExpr;
  93223. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  93224. testcase( aCol==0 );
  93225. }else{
  93226. nCol = 0;
  93227. aCol = 0;
  93228. }
  93229. *pnCol = nCol;
  93230. *paCol = aCol;
  93231. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  93232. /* Get an appropriate name for the column
  93233. */
  93234. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  93235. if( (zName = pEList->a[i].zName)!=0 ){
  93236. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  93237. zName = sqlite3DbStrDup(db, zName);
  93238. }else{
  93239. Expr *pColExpr = p; /* The expression that is the result column name */
  93240. Table *pTab; /* Table associated with this expression */
  93241. while( pColExpr->op==TK_DOT ){
  93242. pColExpr = pColExpr->pRight;
  93243. assert( pColExpr!=0 );
  93244. }
  93245. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  93246. /* For columns use the column name name */
  93247. int iCol = pColExpr->iColumn;
  93248. pTab = pColExpr->pTab;
  93249. if( iCol<0 ) iCol = pTab->iPKey;
  93250. zName = sqlite3MPrintf(db, "%s",
  93251. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  93252. }else if( pColExpr->op==TK_ID ){
  93253. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  93254. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  93255. }else{
  93256. /* Use the original text of the column expression as its name */
  93257. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  93258. }
  93259. }
  93260. if( db->mallocFailed ){
  93261. sqlite3DbFree(db, zName);
  93262. break;
  93263. }
  93264. /* Make sure the column name is unique. If the name is not unique,
  93265. ** append a integer to the name so that it becomes unique.
  93266. */
  93267. nName = sqlite3Strlen30(zName);
  93268. for(j=cnt=0; j<i; j++){
  93269. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  93270. char *zNewName;
  93271. int k;
  93272. for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
  93273. if( zName[k]==':' ) nName = k;
  93274. zName[nName] = 0;
  93275. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  93276. sqlite3DbFree(db, zName);
  93277. zName = zNewName;
  93278. j = -1;
  93279. if( zName==0 ) break;
  93280. }
  93281. }
  93282. pCol->zName = zName;
  93283. }
  93284. if( db->mallocFailed ){
  93285. for(j=0; j<i; j++){
  93286. sqlite3DbFree(db, aCol[j].zName);
  93287. }
  93288. sqlite3DbFree(db, aCol);
  93289. *paCol = 0;
  93290. *pnCol = 0;
  93291. return SQLITE_NOMEM;
  93292. }
  93293. return SQLITE_OK;
  93294. }
  93295. /*
  93296. ** Add type and collation information to a column list based on
  93297. ** a SELECT statement.
  93298. **
  93299. ** The column list presumably came from selectColumnNamesFromExprList().
  93300. ** The column list has only names, not types or collations. This
  93301. ** routine goes through and adds the types and collations.
  93302. **
  93303. ** This routine requires that all identifiers in the SELECT
  93304. ** statement be resolved.
  93305. */
  93306. static void selectAddColumnTypeAndCollation(
  93307. Parse *pParse, /* Parsing contexts */
  93308. Table *pTab, /* Add column type information to this table */
  93309. Select *pSelect /* SELECT used to determine types and collations */
  93310. ){
  93311. sqlite3 *db = pParse->db;
  93312. NameContext sNC;
  93313. Column *pCol;
  93314. CollSeq *pColl;
  93315. int i;
  93316. Expr *p;
  93317. struct ExprList_item *a;
  93318. u64 szAll = 0;
  93319. assert( pSelect!=0 );
  93320. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  93321. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  93322. if( db->mallocFailed ) return;
  93323. memset(&sNC, 0, sizeof(sNC));
  93324. sNC.pSrcList = pSelect->pSrc;
  93325. a = pSelect->pEList->a;
  93326. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  93327. p = a[i].pExpr;
  93328. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
  93329. szAll += pCol->szEst;
  93330. pCol->affinity = sqlite3ExprAffinity(p);
  93331. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
  93332. pColl = sqlite3ExprCollSeq(pParse, p);
  93333. if( pColl ){
  93334. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  93335. }
  93336. }
  93337. pTab->szTabRow = sqlite3LogEst(szAll*4);
  93338. }
  93339. /*
  93340. ** Given a SELECT statement, generate a Table structure that describes
  93341. ** the result set of that SELECT.
  93342. */
  93343. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  93344. Table *pTab;
  93345. sqlite3 *db = pParse->db;
  93346. int savedFlags;
  93347. savedFlags = db->flags;
  93348. db->flags &= ~SQLITE_FullColNames;
  93349. db->flags |= SQLITE_ShortColNames;
  93350. sqlite3SelectPrep(pParse, pSelect, 0);
  93351. if( pParse->nErr ) return 0;
  93352. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  93353. db->flags = savedFlags;
  93354. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  93355. if( pTab==0 ){
  93356. return 0;
  93357. }
  93358. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  93359. ** is disabled */
  93360. assert( db->lookaside.bEnabled==0 );
  93361. pTab->nRef = 1;
  93362. pTab->zName = 0;
  93363. pTab->nRowEst = 1048576;
  93364. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  93365. selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  93366. pTab->iPKey = -1;
  93367. if( db->mallocFailed ){
  93368. sqlite3DeleteTable(db, pTab);
  93369. return 0;
  93370. }
  93371. return pTab;
  93372. }
  93373. /*
  93374. ** Get a VDBE for the given parser context. Create a new one if necessary.
  93375. ** If an error occurs, return NULL and leave a message in pParse.
  93376. */
  93377. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  93378. Vdbe *v = pParse->pVdbe;
  93379. if( v==0 ){
  93380. v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  93381. #ifndef SQLITE_OMIT_TRACE
  93382. if( v ){
  93383. sqlite3VdbeAddOp0(v, OP_Trace);
  93384. }
  93385. #endif
  93386. }
  93387. return v;
  93388. }
  93389. /*
  93390. ** Compute the iLimit and iOffset fields of the SELECT based on the
  93391. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  93392. ** that appear in the original SQL statement after the LIMIT and OFFSET
  93393. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  93394. ** are the integer memory register numbers for counters used to compute
  93395. ** the limit and offset. If there is no limit and/or offset, then
  93396. ** iLimit and iOffset are negative.
  93397. **
  93398. ** This routine changes the values of iLimit and iOffset only if
  93399. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  93400. ** iOffset should have been preset to appropriate default values
  93401. ** (usually but not always -1) prior to calling this routine.
  93402. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  93403. ** redefined. The UNION ALL operator uses this property to force
  93404. ** the reuse of the same limit and offset registers across multiple
  93405. ** SELECT statements.
  93406. */
  93407. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  93408. Vdbe *v = 0;
  93409. int iLimit = 0;
  93410. int iOffset;
  93411. int addr1, n;
  93412. if( p->iLimit ) return;
  93413. /*
  93414. ** "LIMIT -1" always shows all rows. There is some
  93415. ** controversy about what the correct behavior should be.
  93416. ** The current implementation interprets "LIMIT 0" to mean
  93417. ** no rows.
  93418. */
  93419. sqlite3ExprCacheClear(pParse);
  93420. assert( p->pOffset==0 || p->pLimit!=0 );
  93421. if( p->pLimit ){
  93422. p->iLimit = iLimit = ++pParse->nMem;
  93423. v = sqlite3GetVdbe(pParse);
  93424. if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
  93425. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  93426. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  93427. VdbeComment((v, "LIMIT counter"));
  93428. if( n==0 ){
  93429. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  93430. }else if( n>=0 && p->nSelectRow>(u64)n ){
  93431. p->nSelectRow = n;
  93432. }
  93433. }else{
  93434. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  93435. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
  93436. VdbeComment((v, "LIMIT counter"));
  93437. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
  93438. }
  93439. if( p->pOffset ){
  93440. p->iOffset = iOffset = ++pParse->nMem;
  93441. pParse->nMem++; /* Allocate an extra register for limit+offset */
  93442. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  93443. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
  93444. VdbeComment((v, "OFFSET counter"));
  93445. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
  93446. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  93447. sqlite3VdbeJumpHere(v, addr1);
  93448. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  93449. VdbeComment((v, "LIMIT+OFFSET"));
  93450. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
  93451. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  93452. sqlite3VdbeJumpHere(v, addr1);
  93453. }
  93454. }
  93455. }
  93456. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  93457. /*
  93458. ** Return the appropriate collating sequence for the iCol-th column of
  93459. ** the result set for the compound-select statement "p". Return NULL if
  93460. ** the column has no default collating sequence.
  93461. **
  93462. ** The collating sequence for the compound select is taken from the
  93463. ** left-most term of the select that has a collating sequence.
  93464. */
  93465. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  93466. CollSeq *pRet;
  93467. if( p->pPrior ){
  93468. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  93469. }else{
  93470. pRet = 0;
  93471. }
  93472. assert( iCol>=0 );
  93473. if( pRet==0 && iCol<p->pEList->nExpr ){
  93474. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  93475. }
  93476. return pRet;
  93477. }
  93478. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  93479. /* Forward reference */
  93480. static int multiSelectOrderBy(
  93481. Parse *pParse, /* Parsing context */
  93482. Select *p, /* The right-most of SELECTs to be coded */
  93483. SelectDest *pDest /* What to do with query results */
  93484. );
  93485. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  93486. /*
  93487. ** This routine is called to process a compound query form from
  93488. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  93489. ** INTERSECT
  93490. **
  93491. ** "p" points to the right-most of the two queries. the query on the
  93492. ** left is p->pPrior. The left query could also be a compound query
  93493. ** in which case this routine will be called recursively.
  93494. **
  93495. ** The results of the total query are to be written into a destination
  93496. ** of type eDest with parameter iParm.
  93497. **
  93498. ** Example 1: Consider a three-way compound SQL statement.
  93499. **
  93500. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  93501. **
  93502. ** This statement is parsed up as follows:
  93503. **
  93504. ** SELECT c FROM t3
  93505. ** |
  93506. ** `-----> SELECT b FROM t2
  93507. ** |
  93508. ** `------> SELECT a FROM t1
  93509. **
  93510. ** The arrows in the diagram above represent the Select.pPrior pointer.
  93511. ** So if this routine is called with p equal to the t3 query, then
  93512. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  93513. **
  93514. ** Notice that because of the way SQLite parses compound SELECTs, the
  93515. ** individual selects always group from left to right.
  93516. */
  93517. static int multiSelect(
  93518. Parse *pParse, /* Parsing context */
  93519. Select *p, /* The right-most of SELECTs to be coded */
  93520. SelectDest *pDest /* What to do with query results */
  93521. ){
  93522. int rc = SQLITE_OK; /* Success code from a subroutine */
  93523. Select *pPrior; /* Another SELECT immediately to our left */
  93524. Vdbe *v; /* Generate code to this VDBE */
  93525. SelectDest dest; /* Alternative data destination */
  93526. Select *pDelete = 0; /* Chain of simple selects to delete */
  93527. sqlite3 *db; /* Database connection */
  93528. #ifndef SQLITE_OMIT_EXPLAIN
  93529. int iSub1; /* EQP id of left-hand query */
  93530. int iSub2; /* EQP id of right-hand query */
  93531. #endif
  93532. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  93533. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  93534. */
  93535. assert( p && p->pPrior ); /* Calling function guarantees this much */
  93536. db = pParse->db;
  93537. pPrior = p->pPrior;
  93538. assert( pPrior->pRightmost!=pPrior );
  93539. assert( pPrior->pRightmost==p->pRightmost );
  93540. dest = *pDest;
  93541. if( pPrior->pOrderBy ){
  93542. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  93543. selectOpName(p->op));
  93544. rc = 1;
  93545. goto multi_select_end;
  93546. }
  93547. if( pPrior->pLimit ){
  93548. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  93549. selectOpName(p->op));
  93550. rc = 1;
  93551. goto multi_select_end;
  93552. }
  93553. v = sqlite3GetVdbe(pParse);
  93554. assert( v!=0 ); /* The VDBE already created by calling function */
  93555. /* Create the destination temporary table if necessary
  93556. */
  93557. if( dest.eDest==SRT_EphemTab ){
  93558. assert( p->pEList );
  93559. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  93560. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  93561. dest.eDest = SRT_Table;
  93562. }
  93563. /* Make sure all SELECTs in the statement have the same number of elements
  93564. ** in their result sets.
  93565. */
  93566. assert( p->pEList && pPrior->pEList );
  93567. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  93568. if( p->selFlags & SF_Values ){
  93569. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  93570. }else{
  93571. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  93572. " do not have the same number of result columns", selectOpName(p->op));
  93573. }
  93574. rc = 1;
  93575. goto multi_select_end;
  93576. }
  93577. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  93578. */
  93579. if( p->pOrderBy ){
  93580. return multiSelectOrderBy(pParse, p, pDest);
  93581. }
  93582. /* Generate code for the left and right SELECT statements.
  93583. */
  93584. switch( p->op ){
  93585. case TK_ALL: {
  93586. int addr = 0;
  93587. int nLimit;
  93588. assert( !pPrior->pLimit );
  93589. pPrior->iLimit = p->iLimit;
  93590. pPrior->iOffset = p->iOffset;
  93591. pPrior->pLimit = p->pLimit;
  93592. pPrior->pOffset = p->pOffset;
  93593. explainSetInteger(iSub1, pParse->iNextSelectId);
  93594. rc = sqlite3Select(pParse, pPrior, &dest);
  93595. p->pLimit = 0;
  93596. p->pOffset = 0;
  93597. if( rc ){
  93598. goto multi_select_end;
  93599. }
  93600. p->pPrior = 0;
  93601. p->iLimit = pPrior->iLimit;
  93602. p->iOffset = pPrior->iOffset;
  93603. if( p->iLimit ){
  93604. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
  93605. VdbeComment((v, "Jump ahead if LIMIT reached"));
  93606. }
  93607. explainSetInteger(iSub2, pParse->iNextSelectId);
  93608. rc = sqlite3Select(pParse, p, &dest);
  93609. testcase( rc!=SQLITE_OK );
  93610. pDelete = p->pPrior;
  93611. p->pPrior = pPrior;
  93612. p->nSelectRow += pPrior->nSelectRow;
  93613. if( pPrior->pLimit
  93614. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  93615. && nLimit>0 && p->nSelectRow > (u64)nLimit
  93616. ){
  93617. p->nSelectRow = nLimit;
  93618. }
  93619. if( addr ){
  93620. sqlite3VdbeJumpHere(v, addr);
  93621. }
  93622. break;
  93623. }
  93624. case TK_EXCEPT:
  93625. case TK_UNION: {
  93626. int unionTab; /* Cursor number of the temporary table holding result */
  93627. u8 op = 0; /* One of the SRT_ operations to apply to self */
  93628. int priorOp; /* The SRT_ operation to apply to prior selects */
  93629. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  93630. int addr;
  93631. SelectDest uniondest;
  93632. testcase( p->op==TK_EXCEPT );
  93633. testcase( p->op==TK_UNION );
  93634. priorOp = SRT_Union;
  93635. if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
  93636. /* We can reuse a temporary table generated by a SELECT to our
  93637. ** right.
  93638. */
  93639. assert( p->pRightmost!=p ); /* Can only happen for leftward elements
  93640. ** of a 3-way or more compound */
  93641. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  93642. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  93643. unionTab = dest.iSDParm;
  93644. }else{
  93645. /* We will need to create our own temporary table to hold the
  93646. ** intermediate results.
  93647. */
  93648. unionTab = pParse->nTab++;
  93649. assert( p->pOrderBy==0 );
  93650. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  93651. assert( p->addrOpenEphm[0] == -1 );
  93652. p->addrOpenEphm[0] = addr;
  93653. p->pRightmost->selFlags |= SF_UsesEphemeral;
  93654. assert( p->pEList );
  93655. }
  93656. /* Code the SELECT statements to our left
  93657. */
  93658. assert( !pPrior->pOrderBy );
  93659. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  93660. explainSetInteger(iSub1, pParse->iNextSelectId);
  93661. rc = sqlite3Select(pParse, pPrior, &uniondest);
  93662. if( rc ){
  93663. goto multi_select_end;
  93664. }
  93665. /* Code the current SELECT statement
  93666. */
  93667. if( p->op==TK_EXCEPT ){
  93668. op = SRT_Except;
  93669. }else{
  93670. assert( p->op==TK_UNION );
  93671. op = SRT_Union;
  93672. }
  93673. p->pPrior = 0;
  93674. pLimit = p->pLimit;
  93675. p->pLimit = 0;
  93676. pOffset = p->pOffset;
  93677. p->pOffset = 0;
  93678. uniondest.eDest = op;
  93679. explainSetInteger(iSub2, pParse->iNextSelectId);
  93680. rc = sqlite3Select(pParse, p, &uniondest);
  93681. testcase( rc!=SQLITE_OK );
  93682. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  93683. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  93684. sqlite3ExprListDelete(db, p->pOrderBy);
  93685. pDelete = p->pPrior;
  93686. p->pPrior = pPrior;
  93687. p->pOrderBy = 0;
  93688. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  93689. sqlite3ExprDelete(db, p->pLimit);
  93690. p->pLimit = pLimit;
  93691. p->pOffset = pOffset;
  93692. p->iLimit = 0;
  93693. p->iOffset = 0;
  93694. /* Convert the data in the temporary table into whatever form
  93695. ** it is that we currently need.
  93696. */
  93697. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  93698. if( dest.eDest!=priorOp ){
  93699. int iCont, iBreak, iStart;
  93700. assert( p->pEList );
  93701. if( dest.eDest==SRT_Output ){
  93702. Select *pFirst = p;
  93703. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  93704. generateColumnNames(pParse, 0, pFirst->pEList);
  93705. }
  93706. iBreak = sqlite3VdbeMakeLabel(v);
  93707. iCont = sqlite3VdbeMakeLabel(v);
  93708. computeLimitRegisters(pParse, p, iBreak);
  93709. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
  93710. iStart = sqlite3VdbeCurrentAddr(v);
  93711. selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  93712. 0, 0, &dest, iCont, iBreak);
  93713. sqlite3VdbeResolveLabel(v, iCont);
  93714. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
  93715. sqlite3VdbeResolveLabel(v, iBreak);
  93716. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  93717. }
  93718. break;
  93719. }
  93720. default: assert( p->op==TK_INTERSECT ); {
  93721. int tab1, tab2;
  93722. int iCont, iBreak, iStart;
  93723. Expr *pLimit, *pOffset;
  93724. int addr;
  93725. SelectDest intersectdest;
  93726. int r1;
  93727. /* INTERSECT is different from the others since it requires
  93728. ** two temporary tables. Hence it has its own case. Begin
  93729. ** by allocating the tables we will need.
  93730. */
  93731. tab1 = pParse->nTab++;
  93732. tab2 = pParse->nTab++;
  93733. assert( p->pOrderBy==0 );
  93734. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  93735. assert( p->addrOpenEphm[0] == -1 );
  93736. p->addrOpenEphm[0] = addr;
  93737. p->pRightmost->selFlags |= SF_UsesEphemeral;
  93738. assert( p->pEList );
  93739. /* Code the SELECTs to our left into temporary table "tab1".
  93740. */
  93741. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  93742. explainSetInteger(iSub1, pParse->iNextSelectId);
  93743. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  93744. if( rc ){
  93745. goto multi_select_end;
  93746. }
  93747. /* Code the current SELECT into temporary table "tab2"
  93748. */
  93749. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  93750. assert( p->addrOpenEphm[1] == -1 );
  93751. p->addrOpenEphm[1] = addr;
  93752. p->pPrior = 0;
  93753. pLimit = p->pLimit;
  93754. p->pLimit = 0;
  93755. pOffset = p->pOffset;
  93756. p->pOffset = 0;
  93757. intersectdest.iSDParm = tab2;
  93758. explainSetInteger(iSub2, pParse->iNextSelectId);
  93759. rc = sqlite3Select(pParse, p, &intersectdest);
  93760. testcase( rc!=SQLITE_OK );
  93761. pDelete = p->pPrior;
  93762. p->pPrior = pPrior;
  93763. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  93764. sqlite3ExprDelete(db, p->pLimit);
  93765. p->pLimit = pLimit;
  93766. p->pOffset = pOffset;
  93767. /* Generate code to take the intersection of the two temporary
  93768. ** tables.
  93769. */
  93770. assert( p->pEList );
  93771. if( dest.eDest==SRT_Output ){
  93772. Select *pFirst = p;
  93773. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  93774. generateColumnNames(pParse, 0, pFirst->pEList);
  93775. }
  93776. iBreak = sqlite3VdbeMakeLabel(v);
  93777. iCont = sqlite3VdbeMakeLabel(v);
  93778. computeLimitRegisters(pParse, p, iBreak);
  93779. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
  93780. r1 = sqlite3GetTempReg(pParse);
  93781. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  93782. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  93783. sqlite3ReleaseTempReg(pParse, r1);
  93784. selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  93785. 0, 0, &dest, iCont, iBreak);
  93786. sqlite3VdbeResolveLabel(v, iCont);
  93787. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
  93788. sqlite3VdbeResolveLabel(v, iBreak);
  93789. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  93790. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  93791. break;
  93792. }
  93793. }
  93794. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  93795. /* Compute collating sequences used by
  93796. ** temporary tables needed to implement the compound select.
  93797. ** Attach the KeyInfo structure to all temporary tables.
  93798. **
  93799. ** This section is run by the right-most SELECT statement only.
  93800. ** SELECT statements to the left always skip this part. The right-most
  93801. ** SELECT might also skip this part if it has no ORDER BY clause and
  93802. ** no temp tables are required.
  93803. */
  93804. if( p->selFlags & SF_UsesEphemeral ){
  93805. int i; /* Loop counter */
  93806. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  93807. Select *pLoop; /* For looping through SELECT statements */
  93808. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  93809. int nCol; /* Number of columns in result set */
  93810. assert( p->pRightmost==p );
  93811. nCol = p->pEList->nExpr;
  93812. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol);
  93813. if( !pKeyInfo ){
  93814. rc = SQLITE_NOMEM;
  93815. goto multi_select_end;
  93816. }
  93817. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  93818. *apColl = multiSelectCollSeq(pParse, p, i);
  93819. if( 0==*apColl ){
  93820. *apColl = db->pDfltColl;
  93821. }
  93822. }
  93823. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  93824. for(i=0; i<2; i++){
  93825. int addr = pLoop->addrOpenEphm[i];
  93826. if( addr<0 ){
  93827. /* If [0] is unused then [1] is also unused. So we can
  93828. ** always safely abort as soon as the first unused slot is found */
  93829. assert( pLoop->addrOpenEphm[1]<0 );
  93830. break;
  93831. }
  93832. sqlite3VdbeChangeP2(v, addr, nCol);
  93833. sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
  93834. pLoop->addrOpenEphm[i] = -1;
  93835. }
  93836. }
  93837. sqlite3DbFree(db, pKeyInfo);
  93838. }
  93839. multi_select_end:
  93840. pDest->iSdst = dest.iSdst;
  93841. pDest->nSdst = dest.nSdst;
  93842. sqlite3SelectDelete(db, pDelete);
  93843. return rc;
  93844. }
  93845. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  93846. /*
  93847. ** Code an output subroutine for a coroutine implementation of a
  93848. ** SELECT statment.
  93849. **
  93850. ** The data to be output is contained in pIn->iSdst. There are
  93851. ** pIn->nSdst columns to be output. pDest is where the output should
  93852. ** be sent.
  93853. **
  93854. ** regReturn is the number of the register holding the subroutine
  93855. ** return address.
  93856. **
  93857. ** If regPrev>0 then it is the first register in a vector that
  93858. ** records the previous output. mem[regPrev] is a flag that is false
  93859. ** if there has been no previous output. If regPrev>0 then code is
  93860. ** generated to suppress duplicates. pKeyInfo is used for comparing
  93861. ** keys.
  93862. **
  93863. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  93864. ** iBreak.
  93865. */
  93866. static int generateOutputSubroutine(
  93867. Parse *pParse, /* Parsing context */
  93868. Select *p, /* The SELECT statement */
  93869. SelectDest *pIn, /* Coroutine supplying data */
  93870. SelectDest *pDest, /* Where to send the data */
  93871. int regReturn, /* The return address register */
  93872. int regPrev, /* Previous result register. No uniqueness if 0 */
  93873. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  93874. int p4type, /* The p4 type for pKeyInfo */
  93875. int iBreak /* Jump here if we hit the LIMIT */
  93876. ){
  93877. Vdbe *v = pParse->pVdbe;
  93878. int iContinue;
  93879. int addr;
  93880. addr = sqlite3VdbeCurrentAddr(v);
  93881. iContinue = sqlite3VdbeMakeLabel(v);
  93882. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  93883. */
  93884. if( regPrev ){
  93885. int j1, j2;
  93886. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
  93887. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  93888. (char*)pKeyInfo, p4type);
  93889. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
  93890. sqlite3VdbeJumpHere(v, j1);
  93891. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  93892. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  93893. }
  93894. if( pParse->db->mallocFailed ) return 0;
  93895. /* Suppress the first OFFSET entries if there is an OFFSET clause
  93896. */
  93897. codeOffset(v, p, iContinue);
  93898. switch( pDest->eDest ){
  93899. /* Store the result as data using a unique key.
  93900. */
  93901. case SRT_Table:
  93902. case SRT_EphemTab: {
  93903. int r1 = sqlite3GetTempReg(pParse);
  93904. int r2 = sqlite3GetTempReg(pParse);
  93905. testcase( pDest->eDest==SRT_Table );
  93906. testcase( pDest->eDest==SRT_EphemTab );
  93907. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  93908. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  93909. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  93910. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  93911. sqlite3ReleaseTempReg(pParse, r2);
  93912. sqlite3ReleaseTempReg(pParse, r1);
  93913. break;
  93914. }
  93915. #ifndef SQLITE_OMIT_SUBQUERY
  93916. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  93917. ** then there should be a single item on the stack. Write this
  93918. ** item into the set table with bogus data.
  93919. */
  93920. case SRT_Set: {
  93921. int r1;
  93922. assert( pIn->nSdst==1 );
  93923. pDest->affSdst =
  93924. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  93925. r1 = sqlite3GetTempReg(pParse);
  93926. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  93927. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  93928. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  93929. sqlite3ReleaseTempReg(pParse, r1);
  93930. break;
  93931. }
  93932. #if 0 /* Never occurs on an ORDER BY query */
  93933. /* If any row exist in the result set, record that fact and abort.
  93934. */
  93935. case SRT_Exists: {
  93936. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
  93937. /* The LIMIT clause will terminate the loop for us */
  93938. break;
  93939. }
  93940. #endif
  93941. /* If this is a scalar select that is part of an expression, then
  93942. ** store the results in the appropriate memory cell and break out
  93943. ** of the scan loop.
  93944. */
  93945. case SRT_Mem: {
  93946. assert( pIn->nSdst==1 );
  93947. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  93948. /* The LIMIT clause will jump out of the loop for us */
  93949. break;
  93950. }
  93951. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  93952. /* The results are stored in a sequence of registers
  93953. ** starting at pDest->iSdst. Then the co-routine yields.
  93954. */
  93955. case SRT_Coroutine: {
  93956. if( pDest->iSdst==0 ){
  93957. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  93958. pDest->nSdst = pIn->nSdst;
  93959. }
  93960. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
  93961. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  93962. break;
  93963. }
  93964. /* If none of the above, then the result destination must be
  93965. ** SRT_Output. This routine is never called with any other
  93966. ** destination other than the ones handled above or SRT_Output.
  93967. **
  93968. ** For SRT_Output, results are stored in a sequence of registers.
  93969. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  93970. ** return the next row of result.
  93971. */
  93972. default: {
  93973. assert( pDest->eDest==SRT_Output );
  93974. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  93975. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  93976. break;
  93977. }
  93978. }
  93979. /* Jump to the end of the loop if the LIMIT is reached.
  93980. */
  93981. if( p->iLimit ){
  93982. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  93983. }
  93984. /* Generate the subroutine return
  93985. */
  93986. sqlite3VdbeResolveLabel(v, iContinue);
  93987. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  93988. return addr;
  93989. }
  93990. /*
  93991. ** Alternative compound select code generator for cases when there
  93992. ** is an ORDER BY clause.
  93993. **
  93994. ** We assume a query of the following form:
  93995. **
  93996. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  93997. **
  93998. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  93999. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  94000. ** co-routines. Then run the co-routines in parallel and merge the results
  94001. ** into the output. In addition to the two coroutines (called selectA and
  94002. ** selectB) there are 7 subroutines:
  94003. **
  94004. ** outA: Move the output of the selectA coroutine into the output
  94005. ** of the compound query.
  94006. **
  94007. ** outB: Move the output of the selectB coroutine into the output
  94008. ** of the compound query. (Only generated for UNION and
  94009. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  94010. ** appears only in B.)
  94011. **
  94012. ** AltB: Called when there is data from both coroutines and A<B.
  94013. **
  94014. ** AeqB: Called when there is data from both coroutines and A==B.
  94015. **
  94016. ** AgtB: Called when there is data from both coroutines and A>B.
  94017. **
  94018. ** EofA: Called when data is exhausted from selectA.
  94019. **
  94020. ** EofB: Called when data is exhausted from selectB.
  94021. **
  94022. ** The implementation of the latter five subroutines depend on which
  94023. ** <operator> is used:
  94024. **
  94025. **
  94026. ** UNION ALL UNION EXCEPT INTERSECT
  94027. ** ------------- ----------------- -------------- -----------------
  94028. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  94029. **
  94030. ** AeqB: outA, nextA nextA nextA outA, nextA
  94031. **
  94032. ** AgtB: outB, nextB outB, nextB nextB nextB
  94033. **
  94034. ** EofA: outB, nextB outB, nextB halt halt
  94035. **
  94036. ** EofB: outA, nextA outA, nextA outA, nextA halt
  94037. **
  94038. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  94039. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  94040. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  94041. ** following nextX causes a jump to the end of the select processing.
  94042. **
  94043. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  94044. ** within the output subroutine. The regPrev register set holds the previously
  94045. ** output value. A comparison is made against this value and the output
  94046. ** is skipped if the next results would be the same as the previous.
  94047. **
  94048. ** The implementation plan is to implement the two coroutines and seven
  94049. ** subroutines first, then put the control logic at the bottom. Like this:
  94050. **
  94051. ** goto Init
  94052. ** coA: coroutine for left query (A)
  94053. ** coB: coroutine for right query (B)
  94054. ** outA: output one row of A
  94055. ** outB: output one row of B (UNION and UNION ALL only)
  94056. ** EofA: ...
  94057. ** EofB: ...
  94058. ** AltB: ...
  94059. ** AeqB: ...
  94060. ** AgtB: ...
  94061. ** Init: initialize coroutine registers
  94062. ** yield coA
  94063. ** if eof(A) goto EofA
  94064. ** yield coB
  94065. ** if eof(B) goto EofB
  94066. ** Cmpr: Compare A, B
  94067. ** Jump AltB, AeqB, AgtB
  94068. ** End: ...
  94069. **
  94070. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  94071. ** actually called using Gosub and they do not Return. EofA and EofB loop
  94072. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  94073. ** and AgtB jump to either L2 or to one of EofA or EofB.
  94074. */
  94075. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  94076. static int multiSelectOrderBy(
  94077. Parse *pParse, /* Parsing context */
  94078. Select *p, /* The right-most of SELECTs to be coded */
  94079. SelectDest *pDest /* What to do with query results */
  94080. ){
  94081. int i, j; /* Loop counters */
  94082. Select *pPrior; /* Another SELECT immediately to our left */
  94083. Vdbe *v; /* Generate code to this VDBE */
  94084. SelectDest destA; /* Destination for coroutine A */
  94085. SelectDest destB; /* Destination for coroutine B */
  94086. int regAddrA; /* Address register for select-A coroutine */
  94087. int regEofA; /* Flag to indicate when select-A is complete */
  94088. int regAddrB; /* Address register for select-B coroutine */
  94089. int regEofB; /* Flag to indicate when select-B is complete */
  94090. int addrSelectA; /* Address of the select-A coroutine */
  94091. int addrSelectB; /* Address of the select-B coroutine */
  94092. int regOutA; /* Address register for the output-A subroutine */
  94093. int regOutB; /* Address register for the output-B subroutine */
  94094. int addrOutA; /* Address of the output-A subroutine */
  94095. int addrOutB = 0; /* Address of the output-B subroutine */
  94096. int addrEofA; /* Address of the select-A-exhausted subroutine */
  94097. int addrEofB; /* Address of the select-B-exhausted subroutine */
  94098. int addrAltB; /* Address of the A<B subroutine */
  94099. int addrAeqB; /* Address of the A==B subroutine */
  94100. int addrAgtB; /* Address of the A>B subroutine */
  94101. int regLimitA; /* Limit register for select-A */
  94102. int regLimitB; /* Limit register for select-A */
  94103. int regPrev; /* A range of registers to hold previous output */
  94104. int savedLimit; /* Saved value of p->iLimit */
  94105. int savedOffset; /* Saved value of p->iOffset */
  94106. int labelCmpr; /* Label for the start of the merge algorithm */
  94107. int labelEnd; /* Label for the end of the overall SELECT stmt */
  94108. int j1; /* Jump instructions that get retargetted */
  94109. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  94110. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  94111. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  94112. sqlite3 *db; /* Database connection */
  94113. ExprList *pOrderBy; /* The ORDER BY clause */
  94114. int nOrderBy; /* Number of terms in the ORDER BY clause */
  94115. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  94116. #ifndef SQLITE_OMIT_EXPLAIN
  94117. int iSub1; /* EQP id of left-hand query */
  94118. int iSub2; /* EQP id of right-hand query */
  94119. #endif
  94120. assert( p->pOrderBy!=0 );
  94121. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  94122. db = pParse->db;
  94123. v = pParse->pVdbe;
  94124. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  94125. labelEnd = sqlite3VdbeMakeLabel(v);
  94126. labelCmpr = sqlite3VdbeMakeLabel(v);
  94127. /* Patch up the ORDER BY clause
  94128. */
  94129. op = p->op;
  94130. pPrior = p->pPrior;
  94131. assert( pPrior->pOrderBy==0 );
  94132. pOrderBy = p->pOrderBy;
  94133. assert( pOrderBy );
  94134. nOrderBy = pOrderBy->nExpr;
  94135. /* For operators other than UNION ALL we have to make sure that
  94136. ** the ORDER BY clause covers every term of the result set. Add
  94137. ** terms to the ORDER BY clause as necessary.
  94138. */
  94139. if( op!=TK_ALL ){
  94140. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  94141. struct ExprList_item *pItem;
  94142. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  94143. assert( pItem->iOrderByCol>0 );
  94144. if( pItem->iOrderByCol==i ) break;
  94145. }
  94146. if( j==nOrderBy ){
  94147. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  94148. if( pNew==0 ) return SQLITE_NOMEM;
  94149. pNew->flags |= EP_IntValue;
  94150. pNew->u.iValue = i;
  94151. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  94152. if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
  94153. }
  94154. }
  94155. }
  94156. /* Compute the comparison permutation and keyinfo that is used with
  94157. ** the permutation used to determine if the next
  94158. ** row of results comes from selectA or selectB. Also add explicit
  94159. ** collations to the ORDER BY clause terms so that when the subqueries
  94160. ** to the right and the left are evaluated, they use the correct
  94161. ** collation.
  94162. */
  94163. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  94164. if( aPermute ){
  94165. struct ExprList_item *pItem;
  94166. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  94167. assert( pItem->iOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr );
  94168. aPermute[i] = pItem->iOrderByCol - 1;
  94169. }
  94170. pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy);
  94171. if( pKeyMerge ){
  94172. for(i=0; i<nOrderBy; i++){
  94173. CollSeq *pColl;
  94174. Expr *pTerm = pOrderBy->a[i].pExpr;
  94175. if( pTerm->flags & EP_Collate ){
  94176. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  94177. }else{
  94178. pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
  94179. if( pColl==0 ) pColl = db->pDfltColl;
  94180. pOrderBy->a[i].pExpr =
  94181. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  94182. }
  94183. pKeyMerge->aColl[i] = pColl;
  94184. pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  94185. }
  94186. }
  94187. }else{
  94188. pKeyMerge = 0;
  94189. }
  94190. /* Reattach the ORDER BY clause to the query.
  94191. */
  94192. p->pOrderBy = pOrderBy;
  94193. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  94194. /* Allocate a range of temporary registers and the KeyInfo needed
  94195. ** for the logic that removes duplicate result rows when the
  94196. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  94197. */
  94198. if( op==TK_ALL ){
  94199. regPrev = 0;
  94200. }else{
  94201. int nExpr = p->pEList->nExpr;
  94202. assert( nOrderBy>=nExpr || db->mallocFailed );
  94203. regPrev = pParse->nMem+1;
  94204. pParse->nMem += nExpr+1;
  94205. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  94206. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr);
  94207. if( pKeyDup ){
  94208. for(i=0; i<nExpr; i++){
  94209. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  94210. pKeyDup->aSortOrder[i] = 0;
  94211. }
  94212. }
  94213. }
  94214. /* Separate the left and the right query from one another
  94215. */
  94216. p->pPrior = 0;
  94217. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  94218. if( pPrior->pPrior==0 ){
  94219. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  94220. }
  94221. /* Compute the limit registers */
  94222. computeLimitRegisters(pParse, p, labelEnd);
  94223. if( p->iLimit && op==TK_ALL ){
  94224. regLimitA = ++pParse->nMem;
  94225. regLimitB = ++pParse->nMem;
  94226. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  94227. regLimitA);
  94228. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  94229. }else{
  94230. regLimitA = regLimitB = 0;
  94231. }
  94232. sqlite3ExprDelete(db, p->pLimit);
  94233. p->pLimit = 0;
  94234. sqlite3ExprDelete(db, p->pOffset);
  94235. p->pOffset = 0;
  94236. regAddrA = ++pParse->nMem;
  94237. regEofA = ++pParse->nMem;
  94238. regAddrB = ++pParse->nMem;
  94239. regEofB = ++pParse->nMem;
  94240. regOutA = ++pParse->nMem;
  94241. regOutB = ++pParse->nMem;
  94242. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  94243. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  94244. /* Jump past the various subroutines and coroutines to the main
  94245. ** merge loop
  94246. */
  94247. j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  94248. addrSelectA = sqlite3VdbeCurrentAddr(v);
  94249. /* Generate a coroutine to evaluate the SELECT statement to the
  94250. ** left of the compound operator - the "A" select.
  94251. */
  94252. VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  94253. pPrior->iLimit = regLimitA;
  94254. explainSetInteger(iSub1, pParse->iNextSelectId);
  94255. sqlite3Select(pParse, pPrior, &destA);
  94256. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  94257. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  94258. VdbeNoopComment((v, "End coroutine for left SELECT"));
  94259. /* Generate a coroutine to evaluate the SELECT statement on
  94260. ** the right - the "B" select
  94261. */
  94262. addrSelectB = sqlite3VdbeCurrentAddr(v);
  94263. VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  94264. savedLimit = p->iLimit;
  94265. savedOffset = p->iOffset;
  94266. p->iLimit = regLimitB;
  94267. p->iOffset = 0;
  94268. explainSetInteger(iSub2, pParse->iNextSelectId);
  94269. sqlite3Select(pParse, p, &destB);
  94270. p->iLimit = savedLimit;
  94271. p->iOffset = savedOffset;
  94272. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  94273. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  94274. VdbeNoopComment((v, "End coroutine for right SELECT"));
  94275. /* Generate a subroutine that outputs the current row of the A
  94276. ** select as the next output row of the compound select.
  94277. */
  94278. VdbeNoopComment((v, "Output routine for A"));
  94279. addrOutA = generateOutputSubroutine(pParse,
  94280. p, &destA, pDest, regOutA,
  94281. regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  94282. /* Generate a subroutine that outputs the current row of the B
  94283. ** select as the next output row of the compound select.
  94284. */
  94285. if( op==TK_ALL || op==TK_UNION ){
  94286. VdbeNoopComment((v, "Output routine for B"));
  94287. addrOutB = generateOutputSubroutine(pParse,
  94288. p, &destB, pDest, regOutB,
  94289. regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  94290. }
  94291. /* Generate a subroutine to run when the results from select A
  94292. ** are exhausted and only data in select B remains.
  94293. */
  94294. VdbeNoopComment((v, "eof-A subroutine"));
  94295. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  94296. addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  94297. }else{
  94298. addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
  94299. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  94300. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  94301. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  94302. p->nSelectRow += pPrior->nSelectRow;
  94303. }
  94304. /* Generate a subroutine to run when the results from select B
  94305. ** are exhausted and only data in select A remains.
  94306. */
  94307. if( op==TK_INTERSECT ){
  94308. addrEofB = addrEofA;
  94309. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  94310. }else{
  94311. VdbeNoopComment((v, "eof-B subroutine"));
  94312. addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
  94313. sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  94314. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  94315. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  94316. }
  94317. /* Generate code to handle the case of A<B
  94318. */
  94319. VdbeNoopComment((v, "A-lt-B subroutine"));
  94320. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  94321. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  94322. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  94323. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  94324. /* Generate code to handle the case of A==B
  94325. */
  94326. if( op==TK_ALL ){
  94327. addrAeqB = addrAltB;
  94328. }else if( op==TK_INTERSECT ){
  94329. addrAeqB = addrAltB;
  94330. addrAltB++;
  94331. }else{
  94332. VdbeNoopComment((v, "A-eq-B subroutine"));
  94333. addrAeqB =
  94334. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  94335. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  94336. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  94337. }
  94338. /* Generate code to handle the case of A>B
  94339. */
  94340. VdbeNoopComment((v, "A-gt-B subroutine"));
  94341. addrAgtB = sqlite3VdbeCurrentAddr(v);
  94342. if( op==TK_ALL || op==TK_UNION ){
  94343. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  94344. }
  94345. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  94346. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  94347. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  94348. /* This code runs once to initialize everything.
  94349. */
  94350. sqlite3VdbeJumpHere(v, j1);
  94351. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  94352. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  94353. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  94354. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  94355. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  94356. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  94357. /* Implement the main merge loop
  94358. */
  94359. sqlite3VdbeResolveLabel(v, labelCmpr);
  94360. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  94361. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  94362. (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  94363. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  94364. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
  94365. /* Jump to the this point in order to terminate the query.
  94366. */
  94367. sqlite3VdbeResolveLabel(v, labelEnd);
  94368. /* Set the number of output columns
  94369. */
  94370. if( pDest->eDest==SRT_Output ){
  94371. Select *pFirst = pPrior;
  94372. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  94373. generateColumnNames(pParse, 0, pFirst->pEList);
  94374. }
  94375. /* Reassembly the compound query so that it will be freed correctly
  94376. ** by the calling function */
  94377. if( p->pPrior ){
  94378. sqlite3SelectDelete(db, p->pPrior);
  94379. }
  94380. p->pPrior = pPrior;
  94381. /*** TBD: Insert subroutine calls to close cursors on incomplete
  94382. **** subqueries ****/
  94383. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  94384. return SQLITE_OK;
  94385. }
  94386. #endif
  94387. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  94388. /* Forward Declarations */
  94389. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  94390. static void substSelect(sqlite3*, Select *, int, ExprList *);
  94391. /*
  94392. ** Scan through the expression pExpr. Replace every reference to
  94393. ** a column in table number iTable with a copy of the iColumn-th
  94394. ** entry in pEList. (But leave references to the ROWID column
  94395. ** unchanged.)
  94396. **
  94397. ** This routine is part of the flattening procedure. A subquery
  94398. ** whose result set is defined by pEList appears as entry in the
  94399. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  94400. ** FORM clause entry is iTable. This routine make the necessary
  94401. ** changes to pExpr so that it refers directly to the source table
  94402. ** of the subquery rather the result set of the subquery.
  94403. */
  94404. static Expr *substExpr(
  94405. sqlite3 *db, /* Report malloc errors to this connection */
  94406. Expr *pExpr, /* Expr in which substitution occurs */
  94407. int iTable, /* Table to be substituted */
  94408. ExprList *pEList /* Substitute expressions */
  94409. ){
  94410. if( pExpr==0 ) return 0;
  94411. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  94412. if( pExpr->iColumn<0 ){
  94413. pExpr->op = TK_NULL;
  94414. }else{
  94415. Expr *pNew;
  94416. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  94417. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  94418. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  94419. sqlite3ExprDelete(db, pExpr);
  94420. pExpr = pNew;
  94421. }
  94422. }else{
  94423. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  94424. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  94425. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  94426. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  94427. }else{
  94428. substExprList(db, pExpr->x.pList, iTable, pEList);
  94429. }
  94430. }
  94431. return pExpr;
  94432. }
  94433. static void substExprList(
  94434. sqlite3 *db, /* Report malloc errors here */
  94435. ExprList *pList, /* List to scan and in which to make substitutes */
  94436. int iTable, /* Table to be substituted */
  94437. ExprList *pEList /* Substitute values */
  94438. ){
  94439. int i;
  94440. if( pList==0 ) return;
  94441. for(i=0; i<pList->nExpr; i++){
  94442. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  94443. }
  94444. }
  94445. static void substSelect(
  94446. sqlite3 *db, /* Report malloc errors here */
  94447. Select *p, /* SELECT statement in which to make substitutions */
  94448. int iTable, /* Table to be replaced */
  94449. ExprList *pEList /* Substitute values */
  94450. ){
  94451. SrcList *pSrc;
  94452. struct SrcList_item *pItem;
  94453. int i;
  94454. if( !p ) return;
  94455. substExprList(db, p->pEList, iTable, pEList);
  94456. substExprList(db, p->pGroupBy, iTable, pEList);
  94457. substExprList(db, p->pOrderBy, iTable, pEList);
  94458. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  94459. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  94460. substSelect(db, p->pPrior, iTable, pEList);
  94461. pSrc = p->pSrc;
  94462. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  94463. if( ALWAYS(pSrc) ){
  94464. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  94465. substSelect(db, pItem->pSelect, iTable, pEList);
  94466. }
  94467. }
  94468. }
  94469. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  94470. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  94471. /*
  94472. ** This routine attempts to flatten subqueries as a performance optimization.
  94473. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  94474. **
  94475. ** To understand the concept of flattening, consider the following
  94476. ** query:
  94477. **
  94478. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  94479. **
  94480. ** The default way of implementing this query is to execute the
  94481. ** subquery first and store the results in a temporary table, then
  94482. ** run the outer query on that temporary table. This requires two
  94483. ** passes over the data. Furthermore, because the temporary table
  94484. ** has no indices, the WHERE clause on the outer query cannot be
  94485. ** optimized.
  94486. **
  94487. ** This routine attempts to rewrite queries such as the above into
  94488. ** a single flat select, like this:
  94489. **
  94490. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  94491. **
  94492. ** The code generated for this simpification gives the same result
  94493. ** but only has to scan the data once. And because indices might
  94494. ** exist on the table t1, a complete scan of the data might be
  94495. ** avoided.
  94496. **
  94497. ** Flattening is only attempted if all of the following are true:
  94498. **
  94499. ** (1) The subquery and the outer query do not both use aggregates.
  94500. **
  94501. ** (2) The subquery is not an aggregate or the outer query is not a join.
  94502. **
  94503. ** (3) The subquery is not the right operand of a left outer join
  94504. ** (Originally ticket #306. Strengthened by ticket #3300)
  94505. **
  94506. ** (4) The subquery is not DISTINCT.
  94507. **
  94508. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  94509. ** sub-queries that were excluded from this optimization. Restriction
  94510. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  94511. **
  94512. ** (6) The subquery does not use aggregates or the outer query is not
  94513. ** DISTINCT.
  94514. **
  94515. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  94516. ** A FROM clause, consider adding a FROM close with the special
  94517. ** table sqlite_once that consists of a single row containing a
  94518. ** single NULL.
  94519. **
  94520. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  94521. **
  94522. ** (9) The subquery does not use LIMIT or the outer query does not use
  94523. ** aggregates.
  94524. **
  94525. ** (10) The subquery does not use aggregates or the outer query does not
  94526. ** use LIMIT.
  94527. **
  94528. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  94529. **
  94530. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  94531. ** a separate restriction deriving from ticket #350.
  94532. **
  94533. ** (13) The subquery and outer query do not both use LIMIT.
  94534. **
  94535. ** (14) The subquery does not use OFFSET.
  94536. **
  94537. ** (15) The outer query is not part of a compound select or the
  94538. ** subquery does not have a LIMIT clause.
  94539. ** (See ticket #2339 and ticket [02a8e81d44]).
  94540. **
  94541. ** (16) The outer query is not an aggregate or the subquery does
  94542. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  94543. ** until we introduced the group_concat() function.
  94544. **
  94545. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  94546. ** compound clause made up entirely of non-aggregate queries, and
  94547. ** the parent query:
  94548. **
  94549. ** * is not itself part of a compound select,
  94550. ** * is not an aggregate or DISTINCT query, and
  94551. ** * is not a join
  94552. **
  94553. ** The parent and sub-query may contain WHERE clauses. Subject to
  94554. ** rules (11), (13) and (14), they may also contain ORDER BY,
  94555. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  94556. ** operator other than UNION ALL because all the other compound
  94557. ** operators have an implied DISTINCT which is disallowed by
  94558. ** restriction (4).
  94559. **
  94560. ** Also, each component of the sub-query must return the same number
  94561. ** of result columns. This is actually a requirement for any compound
  94562. ** SELECT statement, but all the code here does is make sure that no
  94563. ** such (illegal) sub-query is flattened. The caller will detect the
  94564. ** syntax error and return a detailed message.
  94565. **
  94566. ** (18) If the sub-query is a compound select, then all terms of the
  94567. ** ORDER by clause of the parent must be simple references to
  94568. ** columns of the sub-query.
  94569. **
  94570. ** (19) The subquery does not use LIMIT or the outer query does not
  94571. ** have a WHERE clause.
  94572. **
  94573. ** (20) If the sub-query is a compound select, then it must not use
  94574. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  94575. ** somewhat by saying that the terms of the ORDER BY clause must
  94576. ** appear as unmodified result columns in the outer query. But we
  94577. ** have other optimizations in mind to deal with that case.
  94578. **
  94579. ** (21) The subquery does not use LIMIT or the outer query is not
  94580. ** DISTINCT. (See ticket [752e1646fc]).
  94581. **
  94582. ** In this routine, the "p" parameter is a pointer to the outer query.
  94583. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  94584. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  94585. **
  94586. ** If flattening is not attempted, this routine is a no-op and returns 0.
  94587. ** If flattening is attempted this routine returns 1.
  94588. **
  94589. ** All of the expression analysis must occur on both the outer query and
  94590. ** the subquery before this routine runs.
  94591. */
  94592. static int flattenSubquery(
  94593. Parse *pParse, /* Parsing context */
  94594. Select *p, /* The parent or outer SELECT statement */
  94595. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  94596. int isAgg, /* True if outer SELECT uses aggregate functions */
  94597. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  94598. ){
  94599. const char *zSavedAuthContext = pParse->zAuthContext;
  94600. Select *pParent;
  94601. Select *pSub; /* The inner query or "subquery" */
  94602. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  94603. SrcList *pSrc; /* The FROM clause of the outer query */
  94604. SrcList *pSubSrc; /* The FROM clause of the subquery */
  94605. ExprList *pList; /* The result set of the outer query */
  94606. int iParent; /* VDBE cursor number of the pSub result set temp table */
  94607. int i; /* Loop counter */
  94608. Expr *pWhere; /* The WHERE clause */
  94609. struct SrcList_item *pSubitem; /* The subquery */
  94610. sqlite3 *db = pParse->db;
  94611. /* Check to see if flattening is permitted. Return 0 if not.
  94612. */
  94613. assert( p!=0 );
  94614. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  94615. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  94616. pSrc = p->pSrc;
  94617. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  94618. pSubitem = &pSrc->a[iFrom];
  94619. iParent = pSubitem->iCursor;
  94620. pSub = pSubitem->pSelect;
  94621. assert( pSub!=0 );
  94622. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  94623. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  94624. pSubSrc = pSub->pSrc;
  94625. assert( pSubSrc );
  94626. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  94627. ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  94628. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  94629. ** became arbitrary expressions, we were forced to add restrictions (13)
  94630. ** and (14). */
  94631. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  94632. if( pSub->pOffset ) return 0; /* Restriction (14) */
  94633. if( p->pRightmost && pSub->pLimit ){
  94634. return 0; /* Restriction (15) */
  94635. }
  94636. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  94637. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  94638. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  94639. return 0; /* Restrictions (8)(9) */
  94640. }
  94641. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  94642. return 0; /* Restriction (6) */
  94643. }
  94644. if( p->pOrderBy && pSub->pOrderBy ){
  94645. return 0; /* Restriction (11) */
  94646. }
  94647. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  94648. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  94649. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  94650. return 0; /* Restriction (21) */
  94651. }
  94652. /* OBSOLETE COMMENT 1:
  94653. ** Restriction 3: If the subquery is a join, make sure the subquery is
  94654. ** not used as the right operand of an outer join. Examples of why this
  94655. ** is not allowed:
  94656. **
  94657. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  94658. **
  94659. ** If we flatten the above, we would get
  94660. **
  94661. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  94662. **
  94663. ** which is not at all the same thing.
  94664. **
  94665. ** OBSOLETE COMMENT 2:
  94666. ** Restriction 12: If the subquery is the right operand of a left outer
  94667. ** join, make sure the subquery has no WHERE clause.
  94668. ** An examples of why this is not allowed:
  94669. **
  94670. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  94671. **
  94672. ** If we flatten the above, we would get
  94673. **
  94674. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  94675. **
  94676. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  94677. ** effectively converts the OUTER JOIN into an INNER JOIN.
  94678. **
  94679. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  94680. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  94681. ** is fraught with danger. Best to avoid the whole thing. If the
  94682. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  94683. */
  94684. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  94685. return 0;
  94686. }
  94687. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  94688. ** use only the UNION ALL operator. And none of the simple select queries
  94689. ** that make up the compound SELECT are allowed to be aggregate or distinct
  94690. ** queries.
  94691. */
  94692. if( pSub->pPrior ){
  94693. if( pSub->pOrderBy ){
  94694. return 0; /* Restriction 20 */
  94695. }
  94696. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  94697. return 0;
  94698. }
  94699. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  94700. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  94701. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  94702. assert( pSub->pSrc!=0 );
  94703. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  94704. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  94705. || pSub1->pSrc->nSrc<1
  94706. || pSub->pEList->nExpr!=pSub1->pEList->nExpr
  94707. ){
  94708. return 0;
  94709. }
  94710. testcase( pSub1->pSrc->nSrc>1 );
  94711. }
  94712. /* Restriction 18. */
  94713. if( p->pOrderBy ){
  94714. int ii;
  94715. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  94716. if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
  94717. }
  94718. }
  94719. }
  94720. /***** If we reach this point, flattening is permitted. *****/
  94721. /* Authorize the subquery */
  94722. pParse->zAuthContext = pSubitem->zName;
  94723. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  94724. testcase( i==SQLITE_DENY );
  94725. pParse->zAuthContext = zSavedAuthContext;
  94726. /* If the sub-query is a compound SELECT statement, then (by restrictions
  94727. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  94728. ** be of the form:
  94729. **
  94730. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  94731. **
  94732. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  94733. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  94734. ** OFFSET clauses and joins them to the left-hand-side of the original
  94735. ** using UNION ALL operators. In this case N is the number of simple
  94736. ** select statements in the compound sub-query.
  94737. **
  94738. ** Example:
  94739. **
  94740. ** SELECT a+1 FROM (
  94741. ** SELECT x FROM tab
  94742. ** UNION ALL
  94743. ** SELECT y FROM tab
  94744. ** UNION ALL
  94745. ** SELECT abs(z*2) FROM tab2
  94746. ** ) WHERE a!=5 ORDER BY 1
  94747. **
  94748. ** Transformed into:
  94749. **
  94750. ** SELECT x+1 FROM tab WHERE x+1!=5
  94751. ** UNION ALL
  94752. ** SELECT y+1 FROM tab WHERE y+1!=5
  94753. ** UNION ALL
  94754. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  94755. ** ORDER BY 1
  94756. **
  94757. ** We call this the "compound-subquery flattening".
  94758. */
  94759. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  94760. Select *pNew;
  94761. ExprList *pOrderBy = p->pOrderBy;
  94762. Expr *pLimit = p->pLimit;
  94763. Expr *pOffset = p->pOffset;
  94764. Select *pPrior = p->pPrior;
  94765. p->pOrderBy = 0;
  94766. p->pSrc = 0;
  94767. p->pPrior = 0;
  94768. p->pLimit = 0;
  94769. p->pOffset = 0;
  94770. pNew = sqlite3SelectDup(db, p, 0);
  94771. p->pOffset = pOffset;
  94772. p->pLimit = pLimit;
  94773. p->pOrderBy = pOrderBy;
  94774. p->pSrc = pSrc;
  94775. p->op = TK_ALL;
  94776. p->pRightmost = 0;
  94777. if( pNew==0 ){
  94778. pNew = pPrior;
  94779. }else{
  94780. pNew->pPrior = pPrior;
  94781. pNew->pRightmost = 0;
  94782. }
  94783. p->pPrior = pNew;
  94784. if( db->mallocFailed ) return 1;
  94785. }
  94786. /* Begin flattening the iFrom-th entry of the FROM clause
  94787. ** in the outer query.
  94788. */
  94789. pSub = pSub1 = pSubitem->pSelect;
  94790. /* Delete the transient table structure associated with the
  94791. ** subquery
  94792. */
  94793. sqlite3DbFree(db, pSubitem->zDatabase);
  94794. sqlite3DbFree(db, pSubitem->zName);
  94795. sqlite3DbFree(db, pSubitem->zAlias);
  94796. pSubitem->zDatabase = 0;
  94797. pSubitem->zName = 0;
  94798. pSubitem->zAlias = 0;
  94799. pSubitem->pSelect = 0;
  94800. /* Defer deleting the Table object associated with the
  94801. ** subquery until code generation is
  94802. ** complete, since there may still exist Expr.pTab entries that
  94803. ** refer to the subquery even after flattening. Ticket #3346.
  94804. **
  94805. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  94806. */
  94807. if( ALWAYS(pSubitem->pTab!=0) ){
  94808. Table *pTabToDel = pSubitem->pTab;
  94809. if( pTabToDel->nRef==1 ){
  94810. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  94811. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  94812. pToplevel->pZombieTab = pTabToDel;
  94813. }else{
  94814. pTabToDel->nRef--;
  94815. }
  94816. pSubitem->pTab = 0;
  94817. }
  94818. /* The following loop runs once for each term in a compound-subquery
  94819. ** flattening (as described above). If we are doing a different kind
  94820. ** of flattening - a flattening other than a compound-subquery flattening -
  94821. ** then this loop only runs once.
  94822. **
  94823. ** This loop moves all of the FROM elements of the subquery into the
  94824. ** the FROM clause of the outer query. Before doing this, remember
  94825. ** the cursor number for the original outer query FROM element in
  94826. ** iParent. The iParent cursor will never be used. Subsequent code
  94827. ** will scan expressions looking for iParent references and replace
  94828. ** those references with expressions that resolve to the subquery FROM
  94829. ** elements we are now copying in.
  94830. */
  94831. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  94832. int nSubSrc;
  94833. u8 jointype = 0;
  94834. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  94835. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  94836. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  94837. if( pSrc ){
  94838. assert( pParent==p ); /* First time through the loop */
  94839. jointype = pSubitem->jointype;
  94840. }else{
  94841. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  94842. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  94843. if( pSrc==0 ){
  94844. assert( db->mallocFailed );
  94845. break;
  94846. }
  94847. }
  94848. /* The subquery uses a single slot of the FROM clause of the outer
  94849. ** query. If the subquery has more than one element in its FROM clause,
  94850. ** then expand the outer query to make space for it to hold all elements
  94851. ** of the subquery.
  94852. **
  94853. ** Example:
  94854. **
  94855. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  94856. **
  94857. ** The outer query has 3 slots in its FROM clause. One slot of the
  94858. ** outer query (the middle slot) is used by the subquery. The next
  94859. ** block of code will expand the out query to 4 slots. The middle
  94860. ** slot is expanded to two slots in order to make space for the
  94861. ** two elements in the FROM clause of the subquery.
  94862. */
  94863. if( nSubSrc>1 ){
  94864. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  94865. if( db->mallocFailed ){
  94866. break;
  94867. }
  94868. }
  94869. /* Transfer the FROM clause terms from the subquery into the
  94870. ** outer query.
  94871. */
  94872. for(i=0; i<nSubSrc; i++){
  94873. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  94874. pSrc->a[i+iFrom] = pSubSrc->a[i];
  94875. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  94876. }
  94877. pSrc->a[iFrom].jointype = jointype;
  94878. /* Now begin substituting subquery result set expressions for
  94879. ** references to the iParent in the outer query.
  94880. **
  94881. ** Example:
  94882. **
  94883. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  94884. ** \ \_____________ subquery __________/ /
  94885. ** \_____________________ outer query ______________________________/
  94886. **
  94887. ** We look at every expression in the outer query and every place we see
  94888. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  94889. */
  94890. pList = pParent->pEList;
  94891. for(i=0; i<pList->nExpr; i++){
  94892. if( pList->a[i].zName==0 ){
  94893. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  94894. sqlite3Dequote(zName);
  94895. pList->a[i].zName = zName;
  94896. }
  94897. }
  94898. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  94899. if( isAgg ){
  94900. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  94901. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  94902. }
  94903. if( pSub->pOrderBy ){
  94904. assert( pParent->pOrderBy==0 );
  94905. pParent->pOrderBy = pSub->pOrderBy;
  94906. pSub->pOrderBy = 0;
  94907. }else if( pParent->pOrderBy ){
  94908. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  94909. }
  94910. if( pSub->pWhere ){
  94911. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  94912. }else{
  94913. pWhere = 0;
  94914. }
  94915. if( subqueryIsAgg ){
  94916. assert( pParent->pHaving==0 );
  94917. pParent->pHaving = pParent->pWhere;
  94918. pParent->pWhere = pWhere;
  94919. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  94920. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  94921. sqlite3ExprDup(db, pSub->pHaving, 0));
  94922. assert( pParent->pGroupBy==0 );
  94923. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  94924. }else{
  94925. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  94926. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  94927. }
  94928. /* The flattened query is distinct if either the inner or the
  94929. ** outer query is distinct.
  94930. */
  94931. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  94932. /*
  94933. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  94934. **
  94935. ** One is tempted to try to add a and b to combine the limits. But this
  94936. ** does not work if either limit is negative.
  94937. */
  94938. if( pSub->pLimit ){
  94939. pParent->pLimit = pSub->pLimit;
  94940. pSub->pLimit = 0;
  94941. }
  94942. }
  94943. /* Finially, delete what is left of the subquery and return
  94944. ** success.
  94945. */
  94946. sqlite3SelectDelete(db, pSub1);
  94947. return 1;
  94948. }
  94949. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  94950. /*
  94951. ** Based on the contents of the AggInfo structure indicated by the first
  94952. ** argument, this function checks if the following are true:
  94953. **
  94954. ** * the query contains just a single aggregate function,
  94955. ** * the aggregate function is either min() or max(), and
  94956. ** * the argument to the aggregate function is a column value.
  94957. **
  94958. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  94959. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  94960. ** list of arguments passed to the aggregate before returning.
  94961. **
  94962. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  94963. ** WHERE_ORDERBY_NORMAL is returned.
  94964. */
  94965. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  94966. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  94967. *ppMinMax = 0;
  94968. if( pAggInfo->nFunc==1 ){
  94969. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  94970. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  94971. assert( pExpr->op==TK_AGG_FUNCTION );
  94972. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  94973. const char *zFunc = pExpr->u.zToken;
  94974. if( sqlite3StrICmp(zFunc, "min")==0 ){
  94975. eRet = WHERE_ORDERBY_MIN;
  94976. *ppMinMax = pEList;
  94977. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  94978. eRet = WHERE_ORDERBY_MAX;
  94979. *ppMinMax = pEList;
  94980. }
  94981. }
  94982. }
  94983. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  94984. return eRet;
  94985. }
  94986. /*
  94987. ** The select statement passed as the first argument is an aggregate query.
  94988. ** The second argment is the associated aggregate-info object. This
  94989. ** function tests if the SELECT is of the form:
  94990. **
  94991. ** SELECT count(*) FROM <tbl>
  94992. **
  94993. ** where table is a database table, not a sub-select or view. If the query
  94994. ** does match this pattern, then a pointer to the Table object representing
  94995. ** <tbl> is returned. Otherwise, 0 is returned.
  94996. */
  94997. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  94998. Table *pTab;
  94999. Expr *pExpr;
  95000. assert( !p->pGroupBy );
  95001. if( p->pWhere || p->pEList->nExpr!=1
  95002. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  95003. ){
  95004. return 0;
  95005. }
  95006. pTab = p->pSrc->a[0].pTab;
  95007. pExpr = p->pEList->a[0].pExpr;
  95008. assert( pTab && !pTab->pSelect && pExpr );
  95009. if( IsVirtual(pTab) ) return 0;
  95010. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  95011. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  95012. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  95013. if( pExpr->flags&EP_Distinct ) return 0;
  95014. return pTab;
  95015. }
  95016. /*
  95017. ** If the source-list item passed as an argument was augmented with an
  95018. ** INDEXED BY clause, then try to locate the specified index. If there
  95019. ** was such a clause and the named index cannot be found, return
  95020. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  95021. ** pFrom->pIndex and return SQLITE_OK.
  95022. */
  95023. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  95024. if( pFrom->pTab && pFrom->zIndex ){
  95025. Table *pTab = pFrom->pTab;
  95026. char *zIndex = pFrom->zIndex;
  95027. Index *pIdx;
  95028. for(pIdx=pTab->pIndex;
  95029. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  95030. pIdx=pIdx->pNext
  95031. );
  95032. if( !pIdx ){
  95033. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  95034. pParse->checkSchema = 1;
  95035. return SQLITE_ERROR;
  95036. }
  95037. pFrom->pIndex = pIdx;
  95038. }
  95039. return SQLITE_OK;
  95040. }
  95041. /*
  95042. ** Detect compound SELECT statements that use an ORDER BY clause with
  95043. ** an alternative collating sequence.
  95044. **
  95045. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  95046. **
  95047. ** These are rewritten as a subquery:
  95048. **
  95049. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  95050. ** ORDER BY ... COLLATE ...
  95051. **
  95052. ** This transformation is necessary because the multiSelectOrderBy() routine
  95053. ** above that generates the code for a compound SELECT with an ORDER BY clause
  95054. ** uses a merge algorithm that requires the same collating sequence on the
  95055. ** result columns as on the ORDER BY clause. See ticket
  95056. ** http://www.sqlite.org/src/info/6709574d2a
  95057. **
  95058. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  95059. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  95060. ** there are COLLATE terms in the ORDER BY.
  95061. */
  95062. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  95063. int i;
  95064. Select *pNew;
  95065. Select *pX;
  95066. sqlite3 *db;
  95067. struct ExprList_item *a;
  95068. SrcList *pNewSrc;
  95069. Parse *pParse;
  95070. Token dummy;
  95071. if( p->pPrior==0 ) return WRC_Continue;
  95072. if( p->pOrderBy==0 ) return WRC_Continue;
  95073. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  95074. if( pX==0 ) return WRC_Continue;
  95075. a = p->pOrderBy->a;
  95076. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  95077. if( a[i].pExpr->flags & EP_Collate ) break;
  95078. }
  95079. if( i<0 ) return WRC_Continue;
  95080. /* If we reach this point, that means the transformation is required. */
  95081. pParse = pWalker->pParse;
  95082. db = pParse->db;
  95083. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  95084. if( pNew==0 ) return WRC_Abort;
  95085. memset(&dummy, 0, sizeof(dummy));
  95086. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  95087. if( pNewSrc==0 ) return WRC_Abort;
  95088. *pNew = *p;
  95089. p->pSrc = pNewSrc;
  95090. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
  95091. p->op = TK_SELECT;
  95092. p->pWhere = 0;
  95093. pNew->pGroupBy = 0;
  95094. pNew->pHaving = 0;
  95095. pNew->pOrderBy = 0;
  95096. p->pPrior = 0;
  95097. pNew->pLimit = 0;
  95098. pNew->pOffset = 0;
  95099. return WRC_Continue;
  95100. }
  95101. /*
  95102. ** This routine is a Walker callback for "expanding" a SELECT statement.
  95103. ** "Expanding" means to do the following:
  95104. **
  95105. ** (1) Make sure VDBE cursor numbers have been assigned to every
  95106. ** element of the FROM clause.
  95107. **
  95108. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  95109. ** defines FROM clause. When views appear in the FROM clause,
  95110. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  95111. ** that implements the view. A copy is made of the view's SELECT
  95112. ** statement so that we can freely modify or delete that statement
  95113. ** without worrying about messing up the presistent representation
  95114. ** of the view.
  95115. **
  95116. ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
  95117. ** on joins and the ON and USING clause of joins.
  95118. **
  95119. ** (4) Scan the list of columns in the result set (pEList) looking
  95120. ** for instances of the "*" operator or the TABLE.* operator.
  95121. ** If found, expand each "*" to be every column in every table
  95122. ** and TABLE.* to be every column in TABLE.
  95123. **
  95124. */
  95125. static int selectExpander(Walker *pWalker, Select *p){
  95126. Parse *pParse = pWalker->pParse;
  95127. int i, j, k;
  95128. SrcList *pTabList;
  95129. ExprList *pEList;
  95130. struct SrcList_item *pFrom;
  95131. sqlite3 *db = pParse->db;
  95132. Expr *pE, *pRight, *pExpr;
  95133. u16 selFlags = p->selFlags;
  95134. p->selFlags |= SF_Expanded;
  95135. if( db->mallocFailed ){
  95136. return WRC_Abort;
  95137. }
  95138. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  95139. return WRC_Prune;
  95140. }
  95141. pTabList = p->pSrc;
  95142. pEList = p->pEList;
  95143. /* Make sure cursor numbers have been assigned to all entries in
  95144. ** the FROM clause of the SELECT statement.
  95145. */
  95146. sqlite3SrcListAssignCursors(pParse, pTabList);
  95147. /* Look up every table named in the FROM clause of the select. If
  95148. ** an entry of the FROM clause is a subquery instead of a table or view,
  95149. ** then create a transient table structure to describe the subquery.
  95150. */
  95151. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  95152. Table *pTab;
  95153. if( pFrom->pTab!=0 ){
  95154. /* This statement has already been prepared. There is no need
  95155. ** to go further. */
  95156. assert( i==0 );
  95157. return WRC_Prune;
  95158. }
  95159. if( pFrom->zName==0 ){
  95160. #ifndef SQLITE_OMIT_SUBQUERY
  95161. Select *pSel = pFrom->pSelect;
  95162. /* A sub-query in the FROM clause of a SELECT */
  95163. assert( pSel!=0 );
  95164. assert( pFrom->pTab==0 );
  95165. sqlite3WalkSelect(pWalker, pSel);
  95166. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  95167. if( pTab==0 ) return WRC_Abort;
  95168. pTab->nRef = 1;
  95169. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  95170. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  95171. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  95172. pTab->iPKey = -1;
  95173. pTab->nRowEst = 1048576;
  95174. pTab->tabFlags |= TF_Ephemeral;
  95175. #endif
  95176. }else{
  95177. /* An ordinary table or view name in the FROM clause */
  95178. assert( pFrom->pTab==0 );
  95179. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  95180. if( pTab==0 ) return WRC_Abort;
  95181. if( pTab->nRef==0xffff ){
  95182. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  95183. pTab->zName);
  95184. pFrom->pTab = 0;
  95185. return WRC_Abort;
  95186. }
  95187. pTab->nRef++;
  95188. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  95189. if( pTab->pSelect || IsVirtual(pTab) ){
  95190. /* We reach here if the named table is a really a view */
  95191. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  95192. assert( pFrom->pSelect==0 );
  95193. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  95194. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  95195. }
  95196. #endif
  95197. }
  95198. /* Locate the index named by the INDEXED BY clause, if any. */
  95199. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  95200. return WRC_Abort;
  95201. }
  95202. }
  95203. /* Process NATURAL keywords, and ON and USING clauses of joins.
  95204. */
  95205. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  95206. return WRC_Abort;
  95207. }
  95208. /* For every "*" that occurs in the column list, insert the names of
  95209. ** all columns in all tables. And for every TABLE.* insert the names
  95210. ** of all columns in TABLE. The parser inserted a special expression
  95211. ** with the TK_ALL operator for each "*" that it found in the column list.
  95212. ** The following code just has to locate the TK_ALL expressions and expand
  95213. ** each one to the list of all columns in all tables.
  95214. **
  95215. ** The first loop just checks to see if there are any "*" operators
  95216. ** that need expanding.
  95217. */
  95218. for(k=0; k<pEList->nExpr; k++){
  95219. pE = pEList->a[k].pExpr;
  95220. if( pE->op==TK_ALL ) break;
  95221. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  95222. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  95223. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  95224. }
  95225. if( k<pEList->nExpr ){
  95226. /*
  95227. ** If we get here it means the result set contains one or more "*"
  95228. ** operators that need to be expanded. Loop through each expression
  95229. ** in the result set and expand them one by one.
  95230. */
  95231. struct ExprList_item *a = pEList->a;
  95232. ExprList *pNew = 0;
  95233. int flags = pParse->db->flags;
  95234. int longNames = (flags & SQLITE_FullColNames)!=0
  95235. && (flags & SQLITE_ShortColNames)==0;
  95236. /* When processing FROM-clause subqueries, it is always the case
  95237. ** that full_column_names=OFF and short_column_names=ON. The
  95238. ** sqlite3ResultSetOfSelect() routine makes it so. */
  95239. assert( (p->selFlags & SF_NestedFrom)==0
  95240. || ((flags & SQLITE_FullColNames)==0 &&
  95241. (flags & SQLITE_ShortColNames)!=0) );
  95242. for(k=0; k<pEList->nExpr; k++){
  95243. pE = a[k].pExpr;
  95244. pRight = pE->pRight;
  95245. assert( pE->op!=TK_DOT || pRight!=0 );
  95246. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
  95247. /* This particular expression does not need to be expanded.
  95248. */
  95249. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  95250. if( pNew ){
  95251. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  95252. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  95253. a[k].zName = 0;
  95254. a[k].zSpan = 0;
  95255. }
  95256. a[k].pExpr = 0;
  95257. }else{
  95258. /* This expression is a "*" or a "TABLE.*" and needs to be
  95259. ** expanded. */
  95260. int tableSeen = 0; /* Set to 1 when TABLE matches */
  95261. char *zTName = 0; /* text of name of TABLE */
  95262. if( pE->op==TK_DOT ){
  95263. assert( pE->pLeft!=0 );
  95264. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  95265. zTName = pE->pLeft->u.zToken;
  95266. }
  95267. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  95268. Table *pTab = pFrom->pTab;
  95269. Select *pSub = pFrom->pSelect;
  95270. char *zTabName = pFrom->zAlias;
  95271. const char *zSchemaName = 0;
  95272. int iDb;
  95273. if( zTabName==0 ){
  95274. zTabName = pTab->zName;
  95275. }
  95276. if( db->mallocFailed ) break;
  95277. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  95278. pSub = 0;
  95279. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  95280. continue;
  95281. }
  95282. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95283. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  95284. }
  95285. for(j=0; j<pTab->nCol; j++){
  95286. char *zName = pTab->aCol[j].zName;
  95287. char *zColname; /* The computed column name */
  95288. char *zToFree; /* Malloced string that needs to be freed */
  95289. Token sColname; /* Computed column name as a token */
  95290. assert( zName );
  95291. if( zTName && pSub
  95292. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  95293. ){
  95294. continue;
  95295. }
  95296. /* If a column is marked as 'hidden' (currently only possible
  95297. ** for virtual tables), do not include it in the expanded
  95298. ** result-set list.
  95299. */
  95300. if( IsHiddenColumn(&pTab->aCol[j]) ){
  95301. assert(IsVirtual(pTab));
  95302. continue;
  95303. }
  95304. tableSeen = 1;
  95305. if( i>0 && zTName==0 ){
  95306. if( (pFrom->jointype & JT_NATURAL)!=0
  95307. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  95308. ){
  95309. /* In a NATURAL join, omit the join columns from the
  95310. ** table to the right of the join */
  95311. continue;
  95312. }
  95313. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  95314. /* In a join with a USING clause, omit columns in the
  95315. ** using clause from the table on the right. */
  95316. continue;
  95317. }
  95318. }
  95319. pRight = sqlite3Expr(db, TK_ID, zName);
  95320. zColname = zName;
  95321. zToFree = 0;
  95322. if( longNames || pTabList->nSrc>1 ){
  95323. Expr *pLeft;
  95324. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  95325. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  95326. if( zSchemaName ){
  95327. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  95328. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  95329. }
  95330. if( longNames ){
  95331. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  95332. zToFree = zColname;
  95333. }
  95334. }else{
  95335. pExpr = pRight;
  95336. }
  95337. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  95338. sColname.z = zColname;
  95339. sColname.n = sqlite3Strlen30(zColname);
  95340. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  95341. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  95342. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  95343. if( pSub ){
  95344. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  95345. testcase( pX->zSpan==0 );
  95346. }else{
  95347. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  95348. zSchemaName, zTabName, zColname);
  95349. testcase( pX->zSpan==0 );
  95350. }
  95351. pX->bSpanIsTab = 1;
  95352. }
  95353. sqlite3DbFree(db, zToFree);
  95354. }
  95355. }
  95356. if( !tableSeen ){
  95357. if( zTName ){
  95358. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  95359. }else{
  95360. sqlite3ErrorMsg(pParse, "no tables specified");
  95361. }
  95362. }
  95363. }
  95364. }
  95365. sqlite3ExprListDelete(db, pEList);
  95366. p->pEList = pNew;
  95367. }
  95368. #if SQLITE_MAX_COLUMN
  95369. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  95370. sqlite3ErrorMsg(pParse, "too many columns in result set");
  95371. }
  95372. #endif
  95373. return WRC_Continue;
  95374. }
  95375. /*
  95376. ** No-op routine for the parse-tree walker.
  95377. **
  95378. ** When this routine is the Walker.xExprCallback then expression trees
  95379. ** are walked without any actions being taken at each node. Presumably,
  95380. ** when this routine is used for Walker.xExprCallback then
  95381. ** Walker.xSelectCallback is set to do something useful for every
  95382. ** subquery in the parser tree.
  95383. */
  95384. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  95385. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  95386. return WRC_Continue;
  95387. }
  95388. /*
  95389. ** This routine "expands" a SELECT statement and all of its subqueries.
  95390. ** For additional information on what it means to "expand" a SELECT
  95391. ** statement, see the comment on the selectExpand worker callback above.
  95392. **
  95393. ** Expanding a SELECT statement is the first step in processing a
  95394. ** SELECT statement. The SELECT statement must be expanded before
  95395. ** name resolution is performed.
  95396. **
  95397. ** If anything goes wrong, an error message is written into pParse.
  95398. ** The calling function can detect the problem by looking at pParse->nErr
  95399. ** and/or pParse->db->mallocFailed.
  95400. */
  95401. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  95402. Walker w;
  95403. memset(&w, 0, sizeof(w));
  95404. w.xExprCallback = exprWalkNoop;
  95405. w.pParse = pParse;
  95406. if( pParse->hasCompound ){
  95407. w.xSelectCallback = convertCompoundSelectToSubquery;
  95408. sqlite3WalkSelect(&w, pSelect);
  95409. }
  95410. w.xSelectCallback = selectExpander;
  95411. sqlite3WalkSelect(&w, pSelect);
  95412. }
  95413. #ifndef SQLITE_OMIT_SUBQUERY
  95414. /*
  95415. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  95416. ** interface.
  95417. **
  95418. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  95419. ** information to the Table structure that represents the result set
  95420. ** of that subquery.
  95421. **
  95422. ** The Table structure that represents the result set was constructed
  95423. ** by selectExpander() but the type and collation information was omitted
  95424. ** at that point because identifiers had not yet been resolved. This
  95425. ** routine is called after identifier resolution.
  95426. */
  95427. static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  95428. Parse *pParse;
  95429. int i;
  95430. SrcList *pTabList;
  95431. struct SrcList_item *pFrom;
  95432. assert( p->selFlags & SF_Resolved );
  95433. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  95434. p->selFlags |= SF_HasTypeInfo;
  95435. pParse = pWalker->pParse;
  95436. pTabList = p->pSrc;
  95437. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  95438. Table *pTab = pFrom->pTab;
  95439. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  95440. /* A sub-query in the FROM clause of a SELECT */
  95441. Select *pSel = pFrom->pSelect;
  95442. assert( pSel );
  95443. while( pSel->pPrior ) pSel = pSel->pPrior;
  95444. selectAddColumnTypeAndCollation(pParse, pTab, pSel);
  95445. }
  95446. }
  95447. }
  95448. return WRC_Continue;
  95449. }
  95450. #endif
  95451. /*
  95452. ** This routine adds datatype and collating sequence information to
  95453. ** the Table structures of all FROM-clause subqueries in a
  95454. ** SELECT statement.
  95455. **
  95456. ** Use this routine after name resolution.
  95457. */
  95458. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  95459. #ifndef SQLITE_OMIT_SUBQUERY
  95460. Walker w;
  95461. memset(&w, 0, sizeof(w));
  95462. w.xSelectCallback = selectAddSubqueryTypeInfo;
  95463. w.xExprCallback = exprWalkNoop;
  95464. w.pParse = pParse;
  95465. w.bSelectDepthFirst = 1;
  95466. sqlite3WalkSelect(&w, pSelect);
  95467. #endif
  95468. }
  95469. /*
  95470. ** This routine sets up a SELECT statement for processing. The
  95471. ** following is accomplished:
  95472. **
  95473. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  95474. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  95475. ** * ON and USING clauses are shifted into WHERE statements
  95476. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  95477. ** * Identifiers in expression are matched to tables.
  95478. **
  95479. ** This routine acts recursively on all subqueries within the SELECT.
  95480. */
  95481. SQLITE_PRIVATE void sqlite3SelectPrep(
  95482. Parse *pParse, /* The parser context */
  95483. Select *p, /* The SELECT statement being coded. */
  95484. NameContext *pOuterNC /* Name context for container */
  95485. ){
  95486. sqlite3 *db;
  95487. if( NEVER(p==0) ) return;
  95488. db = pParse->db;
  95489. if( db->mallocFailed ) return;
  95490. if( p->selFlags & SF_HasTypeInfo ) return;
  95491. sqlite3SelectExpand(pParse, p);
  95492. if( pParse->nErr || db->mallocFailed ) return;
  95493. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  95494. if( pParse->nErr || db->mallocFailed ) return;
  95495. sqlite3SelectAddTypeInfo(pParse, p);
  95496. }
  95497. /*
  95498. ** Reset the aggregate accumulator.
  95499. **
  95500. ** The aggregate accumulator is a set of memory cells that hold
  95501. ** intermediate results while calculating an aggregate. This
  95502. ** routine generates code that stores NULLs in all of those memory
  95503. ** cells.
  95504. */
  95505. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  95506. Vdbe *v = pParse->pVdbe;
  95507. int i;
  95508. struct AggInfo_func *pFunc;
  95509. if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  95510. return;
  95511. }
  95512. for(i=0; i<pAggInfo->nColumn; i++){
  95513. sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  95514. }
  95515. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  95516. sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
  95517. if( pFunc->iDistinct>=0 ){
  95518. Expr *pE = pFunc->pExpr;
  95519. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  95520. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  95521. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  95522. "argument");
  95523. pFunc->iDistinct = -1;
  95524. }else{
  95525. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
  95526. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  95527. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  95528. }
  95529. }
  95530. }
  95531. }
  95532. /*
  95533. ** Invoke the OP_AggFinalize opcode for every aggregate function
  95534. ** in the AggInfo structure.
  95535. */
  95536. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  95537. Vdbe *v = pParse->pVdbe;
  95538. int i;
  95539. struct AggInfo_func *pF;
  95540. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  95541. ExprList *pList = pF->pExpr->x.pList;
  95542. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  95543. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  95544. (void*)pF->pFunc, P4_FUNCDEF);
  95545. }
  95546. }
  95547. /*
  95548. ** Update the accumulator memory cells for an aggregate based on
  95549. ** the current cursor position.
  95550. */
  95551. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  95552. Vdbe *v = pParse->pVdbe;
  95553. int i;
  95554. int regHit = 0;
  95555. int addrHitTest = 0;
  95556. struct AggInfo_func *pF;
  95557. struct AggInfo_col *pC;
  95558. pAggInfo->directMode = 1;
  95559. sqlite3ExprCacheClear(pParse);
  95560. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  95561. int nArg;
  95562. int addrNext = 0;
  95563. int regAgg;
  95564. ExprList *pList = pF->pExpr->x.pList;
  95565. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  95566. if( pList ){
  95567. nArg = pList->nExpr;
  95568. regAgg = sqlite3GetTempRange(pParse, nArg);
  95569. sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
  95570. }else{
  95571. nArg = 0;
  95572. regAgg = 0;
  95573. }
  95574. if( pF->iDistinct>=0 ){
  95575. addrNext = sqlite3VdbeMakeLabel(v);
  95576. assert( nArg==1 );
  95577. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  95578. }
  95579. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  95580. CollSeq *pColl = 0;
  95581. struct ExprList_item *pItem;
  95582. int j;
  95583. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  95584. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  95585. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  95586. }
  95587. if( !pColl ){
  95588. pColl = pParse->db->pDfltColl;
  95589. }
  95590. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  95591. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  95592. }
  95593. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  95594. (void*)pF->pFunc, P4_FUNCDEF);
  95595. sqlite3VdbeChangeP5(v, (u8)nArg);
  95596. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  95597. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  95598. if( addrNext ){
  95599. sqlite3VdbeResolveLabel(v, addrNext);
  95600. sqlite3ExprCacheClear(pParse);
  95601. }
  95602. }
  95603. /* Before populating the accumulator registers, clear the column cache.
  95604. ** Otherwise, if any of the required column values are already present
  95605. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  95606. ** to pC->iMem. But by the time the value is used, the original register
  95607. ** may have been used, invalidating the underlying buffer holding the
  95608. ** text or blob value. See ticket [883034dcb5].
  95609. **
  95610. ** Another solution would be to change the OP_SCopy used to copy cached
  95611. ** values to an OP_Copy.
  95612. */
  95613. if( regHit ){
  95614. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
  95615. }
  95616. sqlite3ExprCacheClear(pParse);
  95617. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  95618. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  95619. }
  95620. pAggInfo->directMode = 0;
  95621. sqlite3ExprCacheClear(pParse);
  95622. if( addrHitTest ){
  95623. sqlite3VdbeJumpHere(v, addrHitTest);
  95624. }
  95625. }
  95626. /*
  95627. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  95628. ** count(*) query ("SELECT count(*) FROM pTab").
  95629. */
  95630. #ifndef SQLITE_OMIT_EXPLAIN
  95631. static void explainSimpleCount(
  95632. Parse *pParse, /* Parse context */
  95633. Table *pTab, /* Table being queried */
  95634. Index *pIdx /* Index used to optimize scan, or NULL */
  95635. ){
  95636. if( pParse->explain==2 ){
  95637. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  95638. pTab->zName,
  95639. pIdx ? " USING COVERING INDEX " : "",
  95640. pIdx ? pIdx->zName : ""
  95641. );
  95642. sqlite3VdbeAddOp4(
  95643. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  95644. );
  95645. }
  95646. }
  95647. #else
  95648. # define explainSimpleCount(a,b,c)
  95649. #endif
  95650. /*
  95651. ** Generate code for the SELECT statement given in the p argument.
  95652. **
  95653. ** The results are distributed in various ways depending on the
  95654. ** contents of the SelectDest structure pointed to by argument pDest
  95655. ** as follows:
  95656. **
  95657. ** pDest->eDest Result
  95658. ** ------------ -------------------------------------------
  95659. ** SRT_Output Generate a row of output (using the OP_ResultRow
  95660. ** opcode) for each row in the result set.
  95661. **
  95662. ** SRT_Mem Only valid if the result is a single column.
  95663. ** Store the first column of the first result row
  95664. ** in register pDest->iSDParm then abandon the rest
  95665. ** of the query. This destination implies "LIMIT 1".
  95666. **
  95667. ** SRT_Set The result must be a single column. Store each
  95668. ** row of result as the key in table pDest->iSDParm.
  95669. ** Apply the affinity pDest->affSdst before storing
  95670. ** results. Used to implement "IN (SELECT ...)".
  95671. **
  95672. ** SRT_Union Store results as a key in a temporary table
  95673. ** identified by pDest->iSDParm.
  95674. **
  95675. ** SRT_Except Remove results from the temporary table pDest->iSDParm.
  95676. **
  95677. ** SRT_Table Store results in temporary table pDest->iSDParm.
  95678. ** This is like SRT_EphemTab except that the table
  95679. ** is assumed to already be open.
  95680. **
  95681. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  95682. ** the result there. The cursor is left open after
  95683. ** returning. This is like SRT_Table except that
  95684. ** this destination uses OP_OpenEphemeral to create
  95685. ** the table first.
  95686. **
  95687. ** SRT_Coroutine Generate a co-routine that returns a new row of
  95688. ** results each time it is invoked. The entry point
  95689. ** of the co-routine is stored in register pDest->iSDParm.
  95690. **
  95691. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  95692. ** set is not empty.
  95693. **
  95694. ** SRT_Discard Throw the results away. This is used by SELECT
  95695. ** statements within triggers whose only purpose is
  95696. ** the side-effects of functions.
  95697. **
  95698. ** This routine returns the number of errors. If any errors are
  95699. ** encountered, then an appropriate error message is left in
  95700. ** pParse->zErrMsg.
  95701. **
  95702. ** This routine does NOT free the Select structure passed in. The
  95703. ** calling function needs to do that.
  95704. */
  95705. SQLITE_PRIVATE int sqlite3Select(
  95706. Parse *pParse, /* The parser context */
  95707. Select *p, /* The SELECT statement being coded. */
  95708. SelectDest *pDest /* What to do with the query results */
  95709. ){
  95710. int i, j; /* Loop counters */
  95711. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  95712. Vdbe *v; /* The virtual machine under construction */
  95713. int isAgg; /* True for select lists like "count(*)" */
  95714. ExprList *pEList; /* List of columns to extract. */
  95715. SrcList *pTabList; /* List of tables to select from */
  95716. Expr *pWhere; /* The WHERE clause. May be NULL */
  95717. ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  95718. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  95719. Expr *pHaving; /* The HAVING clause. May be NULL */
  95720. int rc = 1; /* Value to return from this function */
  95721. int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
  95722. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  95723. AggInfo sAggInfo; /* Information used by aggregate queries */
  95724. int iEnd; /* Address of the end of the query */
  95725. sqlite3 *db; /* The database connection */
  95726. #ifndef SQLITE_OMIT_EXPLAIN
  95727. int iRestoreSelectId = pParse->iSelectId;
  95728. pParse->iSelectId = pParse->iNextSelectId++;
  95729. #endif
  95730. db = pParse->db;
  95731. if( p==0 || db->mallocFailed || pParse->nErr ){
  95732. return 1;
  95733. }
  95734. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  95735. memset(&sAggInfo, 0, sizeof(sAggInfo));
  95736. if( IgnorableOrderby(pDest) ){
  95737. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  95738. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
  95739. /* If ORDER BY makes no difference in the output then neither does
  95740. ** DISTINCT so it can be removed too. */
  95741. sqlite3ExprListDelete(db, p->pOrderBy);
  95742. p->pOrderBy = 0;
  95743. p->selFlags &= ~SF_Distinct;
  95744. }
  95745. sqlite3SelectPrep(pParse, p, 0);
  95746. pOrderBy = p->pOrderBy;
  95747. pTabList = p->pSrc;
  95748. pEList = p->pEList;
  95749. if( pParse->nErr || db->mallocFailed ){
  95750. goto select_end;
  95751. }
  95752. isAgg = (p->selFlags & SF_Aggregate)!=0;
  95753. assert( pEList!=0 );
  95754. /* Begin generating code.
  95755. */
  95756. v = sqlite3GetVdbe(pParse);
  95757. if( v==0 ) goto select_end;
  95758. /* If writing to memory or generating a set
  95759. ** only a single column may be output.
  95760. */
  95761. #ifndef SQLITE_OMIT_SUBQUERY
  95762. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  95763. goto select_end;
  95764. }
  95765. #endif
  95766. /* Generate code for all sub-queries in the FROM clause
  95767. */
  95768. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  95769. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  95770. struct SrcList_item *pItem = &pTabList->a[i];
  95771. SelectDest dest;
  95772. Select *pSub = pItem->pSelect;
  95773. int isAggSub;
  95774. if( pSub==0 ) continue;
  95775. /* Sometimes the code for a subquery will be generated more than
  95776. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  95777. ** for example. In that case, do not regenerate the code to manifest
  95778. ** a view or the co-routine to implement a view. The first instance
  95779. ** is sufficient, though the subroutine to manifest the view does need
  95780. ** to be invoked again. */
  95781. if( pItem->addrFillSub ){
  95782. if( pItem->viaCoroutine==0 ){
  95783. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  95784. }
  95785. continue;
  95786. }
  95787. /* Increment Parse.nHeight by the height of the largest expression
  95788. ** tree referred to by this, the parent select. The child select
  95789. ** may contain expression trees of at most
  95790. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  95791. ** more conservative than necessary, but much easier than enforcing
  95792. ** an exact limit.
  95793. */
  95794. pParse->nHeight += sqlite3SelectExprHeight(p);
  95795. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  95796. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  95797. /* This subquery can be absorbed into its parent. */
  95798. if( isAggSub ){
  95799. isAgg = 1;
  95800. p->selFlags |= SF_Aggregate;
  95801. }
  95802. i = -1;
  95803. }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
  95804. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  95805. ){
  95806. /* Implement a co-routine that will return a single row of the result
  95807. ** set on each invocation.
  95808. */
  95809. int addrTop;
  95810. int addrEof;
  95811. pItem->regReturn = ++pParse->nMem;
  95812. addrEof = ++pParse->nMem;
  95813. /* Before coding the OP_Goto to jump to the start of the main routine,
  95814. ** ensure that the jump to the verify-schema routine has already
  95815. ** been coded. Otherwise, the verify-schema would likely be coded as
  95816. ** part of the co-routine. If the main routine then accessed the
  95817. ** database before invoking the co-routine for the first time (for
  95818. ** example to initialize a LIMIT register from a sub-select), it would
  95819. ** be doing so without having verified the schema version and obtained
  95820. ** the required db locks. See ticket d6b36be38. */
  95821. sqlite3CodeVerifySchema(pParse, -1);
  95822. sqlite3VdbeAddOp0(v, OP_Goto);
  95823. addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
  95824. sqlite3VdbeChangeP5(v, 1);
  95825. VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
  95826. pItem->addrFillSub = addrTop;
  95827. sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
  95828. sqlite3VdbeChangeP5(v, 1);
  95829. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  95830. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  95831. sqlite3Select(pParse, pSub, &dest);
  95832. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  95833. pItem->viaCoroutine = 1;
  95834. sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
  95835. sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
  95836. sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
  95837. sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
  95838. VdbeComment((v, "end %s", pItem->pTab->zName));
  95839. sqlite3VdbeJumpHere(v, addrTop-1);
  95840. sqlite3ClearTempRegCache(pParse);
  95841. }else{
  95842. /* Generate a subroutine that will fill an ephemeral table with
  95843. ** the content of this subquery. pItem->addrFillSub will point
  95844. ** to the address of the generated subroutine. pItem->regReturn
  95845. ** is a register allocated to hold the subroutine return address
  95846. */
  95847. int topAddr;
  95848. int onceAddr = 0;
  95849. int retAddr;
  95850. assert( pItem->addrFillSub==0 );
  95851. pItem->regReturn = ++pParse->nMem;
  95852. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  95853. pItem->addrFillSub = topAddr+1;
  95854. VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
  95855. if( pItem->isCorrelated==0 ){
  95856. /* If the subquery is not correlated and if we are not inside of
  95857. ** a trigger, then we only need to compute the value of the subquery
  95858. ** once. */
  95859. onceAddr = sqlite3CodeOnce(pParse);
  95860. }
  95861. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  95862. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  95863. sqlite3Select(pParse, pSub, &dest);
  95864. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  95865. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  95866. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  95867. VdbeComment((v, "end %s", pItem->pTab->zName));
  95868. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  95869. sqlite3ClearTempRegCache(pParse);
  95870. }
  95871. if( /*pParse->nErr ||*/ db->mallocFailed ){
  95872. goto select_end;
  95873. }
  95874. pParse->nHeight -= sqlite3SelectExprHeight(p);
  95875. pTabList = p->pSrc;
  95876. if( !IgnorableOrderby(pDest) ){
  95877. pOrderBy = p->pOrderBy;
  95878. }
  95879. }
  95880. pEList = p->pEList;
  95881. #endif
  95882. pWhere = p->pWhere;
  95883. pGroupBy = p->pGroupBy;
  95884. pHaving = p->pHaving;
  95885. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  95886. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  95887. /* If there is are a sequence of queries, do the earlier ones first.
  95888. */
  95889. if( p->pPrior ){
  95890. if( p->pRightmost==0 ){
  95891. Select *pLoop, *pRight = 0;
  95892. int cnt = 0;
  95893. int mxSelect;
  95894. for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  95895. pLoop->pRightmost = p;
  95896. pLoop->pNext = pRight;
  95897. pRight = pLoop;
  95898. }
  95899. mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  95900. if( mxSelect && cnt>mxSelect ){
  95901. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  95902. goto select_end;
  95903. }
  95904. }
  95905. rc = multiSelect(pParse, p, pDest);
  95906. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  95907. return rc;
  95908. }
  95909. #endif
  95910. /* If there is both a GROUP BY and an ORDER BY clause and they are
  95911. ** identical, then disable the ORDER BY clause since the GROUP BY
  95912. ** will cause elements to come out in the correct order. This is
  95913. ** an optimization - the correct answer should result regardless.
  95914. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
  95915. ** to disable this optimization for testing purposes.
  95916. */
  95917. if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0
  95918. && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
  95919. pOrderBy = 0;
  95920. }
  95921. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  95922. ** if the select-list is the same as the ORDER BY list, then this query
  95923. ** can be rewritten as a GROUP BY. In other words, this:
  95924. **
  95925. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  95926. **
  95927. ** is transformed to:
  95928. **
  95929. ** SELECT xyz FROM ... GROUP BY xyz
  95930. **
  95931. ** The second form is preferred as a single index (or temp-table) may be
  95932. ** used for both the ORDER BY and DISTINCT processing. As originally
  95933. ** written the query must use a temp-table for at least one of the ORDER
  95934. ** BY and DISTINCT, and an index or separate temp-table for the other.
  95935. */
  95936. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  95937. && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0
  95938. ){
  95939. p->selFlags &= ~SF_Distinct;
  95940. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  95941. pGroupBy = p->pGroupBy;
  95942. pOrderBy = 0;
  95943. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  95944. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  95945. ** original setting of the SF_Distinct flag, not the current setting */
  95946. assert( sDistinct.isTnct );
  95947. }
  95948. /* If there is an ORDER BY clause, then this sorting
  95949. ** index might end up being unused if the data can be
  95950. ** extracted in pre-sorted order. If that is the case, then the
  95951. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  95952. ** we figure out that the sorting index is not needed. The addrSortIndex
  95953. ** variable is used to facilitate that change.
  95954. */
  95955. if( pOrderBy ){
  95956. KeyInfo *pKeyInfo;
  95957. pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  95958. pOrderBy->iECursor = pParse->nTab++;
  95959. p->addrOpenEphm[2] = addrSortIndex =
  95960. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  95961. pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
  95962. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  95963. }else{
  95964. addrSortIndex = -1;
  95965. }
  95966. /* If the output is destined for a temporary table, open that table.
  95967. */
  95968. if( pDest->eDest==SRT_EphemTab ){
  95969. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  95970. }
  95971. /* Set the limiter.
  95972. */
  95973. iEnd = sqlite3VdbeMakeLabel(v);
  95974. p->nSelectRow = LARGEST_INT64;
  95975. computeLimitRegisters(pParse, p, iEnd);
  95976. if( p->iLimit==0 && addrSortIndex>=0 ){
  95977. sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
  95978. p->selFlags |= SF_UseSorter;
  95979. }
  95980. /* Open a virtual index to use for the distinct set.
  95981. */
  95982. if( p->selFlags & SF_Distinct ){
  95983. sDistinct.tabTnct = pParse->nTab++;
  95984. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  95985. sDistinct.tabTnct, 0, 0,
  95986. (char*)keyInfoFromExprList(pParse, p->pEList),
  95987. P4_KEYINFO_HANDOFF);
  95988. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  95989. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  95990. }else{
  95991. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  95992. }
  95993. if( !isAgg && pGroupBy==0 ){
  95994. /* No aggregate functions and no GROUP BY clause */
  95995. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  95996. /* Begin the database scan. */
  95997. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList,
  95998. wctrlFlags, 0);
  95999. if( pWInfo==0 ) goto select_end;
  96000. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  96001. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  96002. }
  96003. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  96004. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  96005. }
  96006. if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
  96007. /* If sorting index that was created by a prior OP_OpenEphemeral
  96008. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  96009. ** into an OP_Noop.
  96010. */
  96011. if( addrSortIndex>=0 && pOrderBy==0 ){
  96012. sqlite3VdbeChangeToNoop(v, addrSortIndex);
  96013. p->addrOpenEphm[2] = -1;
  96014. }
  96015. /* Use the standard inner loop. */
  96016. selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
  96017. sqlite3WhereContinueLabel(pWInfo),
  96018. sqlite3WhereBreakLabel(pWInfo));
  96019. /* End the database scan loop.
  96020. */
  96021. sqlite3WhereEnd(pWInfo);
  96022. }else{
  96023. /* This case when there exist aggregate functions or a GROUP BY clause
  96024. ** or both */
  96025. NameContext sNC; /* Name context for processing aggregate information */
  96026. int iAMem; /* First Mem address for storing current GROUP BY */
  96027. int iBMem; /* First Mem address for previous GROUP BY */
  96028. int iUseFlag; /* Mem address holding flag indicating that at least
  96029. ** one row of the input to the aggregator has been
  96030. ** processed */
  96031. int iAbortFlag; /* Mem address which causes query abort if positive */
  96032. int groupBySort; /* Rows come from source in GROUP BY order */
  96033. int addrEnd; /* End of processing for this SELECT */
  96034. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  96035. int sortOut = 0; /* Output register from the sorter */
  96036. /* Remove any and all aliases between the result set and the
  96037. ** GROUP BY clause.
  96038. */
  96039. if( pGroupBy ){
  96040. int k; /* Loop counter */
  96041. struct ExprList_item *pItem; /* For looping over expression in a list */
  96042. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  96043. pItem->iAlias = 0;
  96044. }
  96045. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  96046. pItem->iAlias = 0;
  96047. }
  96048. if( p->nSelectRow>100 ) p->nSelectRow = 100;
  96049. }else{
  96050. p->nSelectRow = 1;
  96051. }
  96052. /* Create a label to jump to when we want to abort the query */
  96053. addrEnd = sqlite3VdbeMakeLabel(v);
  96054. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  96055. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  96056. ** SELECT statement.
  96057. */
  96058. memset(&sNC, 0, sizeof(sNC));
  96059. sNC.pParse = pParse;
  96060. sNC.pSrcList = pTabList;
  96061. sNC.pAggInfo = &sAggInfo;
  96062. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  96063. sAggInfo.pGroupBy = pGroupBy;
  96064. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  96065. sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
  96066. if( pHaving ){
  96067. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  96068. }
  96069. sAggInfo.nAccumulator = sAggInfo.nColumn;
  96070. for(i=0; i<sAggInfo.nFunc; i++){
  96071. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  96072. sNC.ncFlags |= NC_InAggFunc;
  96073. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  96074. sNC.ncFlags &= ~NC_InAggFunc;
  96075. }
  96076. if( db->mallocFailed ) goto select_end;
  96077. /* Processing for aggregates with GROUP BY is very different and
  96078. ** much more complex than aggregates without a GROUP BY.
  96079. */
  96080. if( pGroupBy ){
  96081. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  96082. int j1; /* A-vs-B comparision jump */
  96083. int addrOutputRow; /* Start of subroutine that outputs a result row */
  96084. int regOutputRow; /* Return address register for output subroutine */
  96085. int addrSetAbort; /* Set the abort flag and return */
  96086. int addrTopOfLoop; /* Top of the input loop */
  96087. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  96088. int addrReset; /* Subroutine for resetting the accumulator */
  96089. int regReset; /* Return address register for reset subroutine */
  96090. /* If there is a GROUP BY clause we might need a sorting index to
  96091. ** implement it. Allocate that sorting index now. If it turns out
  96092. ** that we do not need it after all, the OP_SorterOpen instruction
  96093. ** will be converted into a Noop.
  96094. */
  96095. sAggInfo.sortingIdx = pParse->nTab++;
  96096. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  96097. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  96098. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  96099. 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  96100. /* Initialize memory locations used by GROUP BY aggregate processing
  96101. */
  96102. iUseFlag = ++pParse->nMem;
  96103. iAbortFlag = ++pParse->nMem;
  96104. regOutputRow = ++pParse->nMem;
  96105. addrOutputRow = sqlite3VdbeMakeLabel(v);
  96106. regReset = ++pParse->nMem;
  96107. addrReset = sqlite3VdbeMakeLabel(v);
  96108. iAMem = pParse->nMem + 1;
  96109. pParse->nMem += pGroupBy->nExpr;
  96110. iBMem = pParse->nMem + 1;
  96111. pParse->nMem += pGroupBy->nExpr;
  96112. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  96113. VdbeComment((v, "clear abort flag"));
  96114. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  96115. VdbeComment((v, "indicate accumulator empty"));
  96116. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  96117. /* Begin a loop that will extract all source rows in GROUP BY order.
  96118. ** This might involve two separate loops with an OP_Sort in between, or
  96119. ** it might be a single loop that uses an index to extract information
  96120. ** in the right order to begin with.
  96121. */
  96122. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  96123. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  96124. WHERE_GROUPBY, 0);
  96125. if( pWInfo==0 ) goto select_end;
  96126. if( sqlite3WhereIsOrdered(pWInfo) ){
  96127. /* The optimizer is able to deliver rows in group by order so
  96128. ** we do not have to sort. The OP_OpenEphemeral table will be
  96129. ** cancelled later because we still need to use the pKeyInfo
  96130. */
  96131. groupBySort = 0;
  96132. }else{
  96133. /* Rows are coming out in undetermined order. We have to push
  96134. ** each row into a sorting index, terminate the first loop,
  96135. ** then loop over the sorting index in order to get the output
  96136. ** in sorted order
  96137. */
  96138. int regBase;
  96139. int regRecord;
  96140. int nCol;
  96141. int nGroupBy;
  96142. explainTempTable(pParse,
  96143. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  96144. "DISTINCT" : "GROUP BY");
  96145. groupBySort = 1;
  96146. nGroupBy = pGroupBy->nExpr;
  96147. nCol = nGroupBy + 1;
  96148. j = nGroupBy+1;
  96149. for(i=0; i<sAggInfo.nColumn; i++){
  96150. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  96151. nCol++;
  96152. j++;
  96153. }
  96154. }
  96155. regBase = sqlite3GetTempRange(pParse, nCol);
  96156. sqlite3ExprCacheClear(pParse);
  96157. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  96158. sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
  96159. j = nGroupBy+1;
  96160. for(i=0; i<sAggInfo.nColumn; i++){
  96161. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  96162. if( pCol->iSorterColumn>=j ){
  96163. int r1 = j + regBase;
  96164. int r2;
  96165. r2 = sqlite3ExprCodeGetColumn(pParse,
  96166. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  96167. if( r1!=r2 ){
  96168. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  96169. }
  96170. j++;
  96171. }
  96172. }
  96173. regRecord = sqlite3GetTempReg(pParse);
  96174. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  96175. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  96176. sqlite3ReleaseTempReg(pParse, regRecord);
  96177. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  96178. sqlite3WhereEnd(pWInfo);
  96179. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  96180. sortOut = sqlite3GetTempReg(pParse);
  96181. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  96182. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  96183. VdbeComment((v, "GROUP BY sort"));
  96184. sAggInfo.useSortingIdx = 1;
  96185. sqlite3ExprCacheClear(pParse);
  96186. }
  96187. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  96188. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  96189. ** Then compare the current GROUP BY terms against the GROUP BY terms
  96190. ** from the previous row currently stored in a0, a1, a2...
  96191. */
  96192. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  96193. sqlite3ExprCacheClear(pParse);
  96194. if( groupBySort ){
  96195. sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
  96196. }
  96197. for(j=0; j<pGroupBy->nExpr; j++){
  96198. if( groupBySort ){
  96199. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  96200. if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  96201. }else{
  96202. sAggInfo.directMode = 1;
  96203. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  96204. }
  96205. }
  96206. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  96207. (char*)pKeyInfo, P4_KEYINFO);
  96208. j1 = sqlite3VdbeCurrentAddr(v);
  96209. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
  96210. /* Generate code that runs whenever the GROUP BY changes.
  96211. ** Changes in the GROUP BY are detected by the previous code
  96212. ** block. If there were no changes, this block is skipped.
  96213. **
  96214. ** This code copies current group by terms in b0,b1,b2,...
  96215. ** over to a0,a1,a2. It then calls the output subroutine
  96216. ** and resets the aggregate accumulator registers in preparation
  96217. ** for the next GROUP BY batch.
  96218. */
  96219. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  96220. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  96221. VdbeComment((v, "output one row"));
  96222. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
  96223. VdbeComment((v, "check abort flag"));
  96224. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  96225. VdbeComment((v, "reset accumulator"));
  96226. /* Update the aggregate accumulators based on the content of
  96227. ** the current row
  96228. */
  96229. sqlite3VdbeJumpHere(v, j1);
  96230. updateAccumulator(pParse, &sAggInfo);
  96231. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  96232. VdbeComment((v, "indicate data in accumulator"));
  96233. /* End of the loop
  96234. */
  96235. if( groupBySort ){
  96236. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  96237. }else{
  96238. sqlite3WhereEnd(pWInfo);
  96239. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  96240. }
  96241. /* Output the final row of result
  96242. */
  96243. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  96244. VdbeComment((v, "output final row"));
  96245. /* Jump over the subroutines
  96246. */
  96247. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  96248. /* Generate a subroutine that outputs a single row of the result
  96249. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  96250. ** is less than or equal to zero, the subroutine is a no-op. If
  96251. ** the processing calls for the query to abort, this subroutine
  96252. ** increments the iAbortFlag memory location before returning in
  96253. ** order to signal the caller to abort.
  96254. */
  96255. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  96256. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  96257. VdbeComment((v, "set abort flag"));
  96258. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  96259. sqlite3VdbeResolveLabel(v, addrOutputRow);
  96260. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  96261. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  96262. VdbeComment((v, "Groupby result generator entry point"));
  96263. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  96264. finalizeAggFunctions(pParse, &sAggInfo);
  96265. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  96266. selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  96267. &sDistinct, pDest,
  96268. addrOutputRow+1, addrSetAbort);
  96269. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  96270. VdbeComment((v, "end groupby result generator"));
  96271. /* Generate a subroutine that will reset the group-by accumulator
  96272. */
  96273. sqlite3VdbeResolveLabel(v, addrReset);
  96274. resetAccumulator(pParse, &sAggInfo);
  96275. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  96276. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  96277. else {
  96278. ExprList *pDel = 0;
  96279. #ifndef SQLITE_OMIT_BTREECOUNT
  96280. Table *pTab;
  96281. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  96282. /* If isSimpleCount() returns a pointer to a Table structure, then
  96283. ** the SQL statement is of the form:
  96284. **
  96285. ** SELECT count(*) FROM <tbl>
  96286. **
  96287. ** where the Table structure returned represents table <tbl>.
  96288. **
  96289. ** This statement is so common that it is optimized specially. The
  96290. ** OP_Count instruction is executed either on the intkey table that
  96291. ** contains the data for table <tbl> or on one of its indexes. It
  96292. ** is better to execute the op on an index, as indexes are almost
  96293. ** always spread across less pages than their corresponding tables.
  96294. */
  96295. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  96296. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  96297. Index *pIdx; /* Iterator variable */
  96298. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  96299. Index *pBest = 0; /* Best index found so far */
  96300. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  96301. sqlite3CodeVerifySchema(pParse, iDb);
  96302. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  96303. /* Search for the index that has the lowest scan cost.
  96304. **
  96305. ** (2011-04-15) Do not do a full scan of an unordered index.
  96306. **
  96307. ** (2013-10-03) Do not count the entires in a partial index.
  96308. **
  96309. ** In practice the KeyInfo structure will not be used. It is only
  96310. ** passed to keep OP_OpenRead happy.
  96311. */
  96312. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  96313. if( pIdx->bUnordered==0
  96314. && pIdx->szIdxRow<pTab->szTabRow
  96315. && pIdx->pPartIdxWhere==0
  96316. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  96317. ){
  96318. pBest = pIdx;
  96319. }
  96320. }
  96321. if( pBest ){
  96322. iRoot = pBest->tnum;
  96323. pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
  96324. }
  96325. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  96326. sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
  96327. if( pKeyInfo ){
  96328. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
  96329. }
  96330. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  96331. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  96332. explainSimpleCount(pParse, pTab, pBest);
  96333. }else
  96334. #endif /* SQLITE_OMIT_BTREECOUNT */
  96335. {
  96336. /* Check if the query is of one of the following forms:
  96337. **
  96338. ** SELECT min(x) FROM ...
  96339. ** SELECT max(x) FROM ...
  96340. **
  96341. ** If it is, then ask the code in where.c to attempt to sort results
  96342. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  96343. ** If where.c is able to produce results sorted in this order, then
  96344. ** add vdbe code to break out of the processing loop after the
  96345. ** first iteration (since the first iteration of the loop is
  96346. ** guaranteed to operate on the row with the minimum or maximum
  96347. ** value of x, the only row required).
  96348. **
  96349. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  96350. ** modify behavior as follows:
  96351. **
  96352. ** + If the query is a "SELECT min(x)", then the loop coded by
  96353. ** where.c should not iterate over any values with a NULL value
  96354. ** for x.
  96355. **
  96356. ** + The optimizer code in where.c (the thing that decides which
  96357. ** index or indices to use) should place a different priority on
  96358. ** satisfying the 'ORDER BY' clause than it does in other cases.
  96359. ** Refer to code and comments in where.c for details.
  96360. */
  96361. ExprList *pMinMax = 0;
  96362. u8 flag = WHERE_ORDERBY_NORMAL;
  96363. assert( p->pGroupBy==0 );
  96364. assert( flag==0 );
  96365. if( p->pHaving==0 ){
  96366. flag = minMaxQuery(&sAggInfo, &pMinMax);
  96367. }
  96368. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  96369. if( flag ){
  96370. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  96371. pDel = pMinMax;
  96372. if( pMinMax && !db->mallocFailed ){
  96373. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  96374. pMinMax->a[0].pExpr->op = TK_COLUMN;
  96375. }
  96376. }
  96377. /* This case runs if the aggregate has no GROUP BY clause. The
  96378. ** processing is much simpler since there is only a single row
  96379. ** of output.
  96380. */
  96381. resetAccumulator(pParse, &sAggInfo);
  96382. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  96383. if( pWInfo==0 ){
  96384. sqlite3ExprListDelete(db, pDel);
  96385. goto select_end;
  96386. }
  96387. updateAccumulator(pParse, &sAggInfo);
  96388. assert( pMinMax==0 || pMinMax->nExpr==1 );
  96389. if( sqlite3WhereIsOrdered(pWInfo) ){
  96390. sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
  96391. VdbeComment((v, "%s() by index",
  96392. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  96393. }
  96394. sqlite3WhereEnd(pWInfo);
  96395. finalizeAggFunctions(pParse, &sAggInfo);
  96396. }
  96397. pOrderBy = 0;
  96398. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  96399. selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
  96400. pDest, addrEnd, addrEnd);
  96401. sqlite3ExprListDelete(db, pDel);
  96402. }
  96403. sqlite3VdbeResolveLabel(v, addrEnd);
  96404. } /* endif aggregate query */
  96405. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  96406. explainTempTable(pParse, "DISTINCT");
  96407. }
  96408. /* If there is an ORDER BY clause, then we need to sort the results
  96409. ** and send them to the callback one by one.
  96410. */
  96411. if( pOrderBy ){
  96412. explainTempTable(pParse, "ORDER BY");
  96413. generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  96414. }
  96415. /* Jump here to skip this query
  96416. */
  96417. sqlite3VdbeResolveLabel(v, iEnd);
  96418. /* The SELECT was successfully coded. Set the return code to 0
  96419. ** to indicate no errors.
  96420. */
  96421. rc = 0;
  96422. /* Control jumps to here if an error is encountered above, or upon
  96423. ** successful coding of the SELECT.
  96424. */
  96425. select_end:
  96426. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  96427. /* Identify column names if results of the SELECT are to be output.
  96428. */
  96429. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  96430. generateColumnNames(pParse, pTabList, pEList);
  96431. }
  96432. sqlite3DbFree(db, sAggInfo.aCol);
  96433. sqlite3DbFree(db, sAggInfo.aFunc);
  96434. return rc;
  96435. }
  96436. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  96437. /*
  96438. ** Generate a human-readable description of a the Select object.
  96439. */
  96440. static void explainOneSelect(Vdbe *pVdbe, Select *p){
  96441. sqlite3ExplainPrintf(pVdbe, "SELECT ");
  96442. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  96443. if( p->selFlags & SF_Distinct ){
  96444. sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
  96445. }
  96446. if( p->selFlags & SF_Aggregate ){
  96447. sqlite3ExplainPrintf(pVdbe, "agg_flag ");
  96448. }
  96449. sqlite3ExplainNL(pVdbe);
  96450. sqlite3ExplainPrintf(pVdbe, " ");
  96451. }
  96452. sqlite3ExplainExprList(pVdbe, p->pEList);
  96453. sqlite3ExplainNL(pVdbe);
  96454. if( p->pSrc && p->pSrc->nSrc ){
  96455. int i;
  96456. sqlite3ExplainPrintf(pVdbe, "FROM ");
  96457. sqlite3ExplainPush(pVdbe);
  96458. for(i=0; i<p->pSrc->nSrc; i++){
  96459. struct SrcList_item *pItem = &p->pSrc->a[i];
  96460. sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
  96461. if( pItem->pSelect ){
  96462. sqlite3ExplainSelect(pVdbe, pItem->pSelect);
  96463. if( pItem->pTab ){
  96464. sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
  96465. }
  96466. }else if( pItem->zName ){
  96467. sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
  96468. }
  96469. if( pItem->zAlias ){
  96470. sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
  96471. }
  96472. if( pItem->jointype & JT_LEFT ){
  96473. sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
  96474. }
  96475. sqlite3ExplainNL(pVdbe);
  96476. }
  96477. sqlite3ExplainPop(pVdbe);
  96478. }
  96479. if( p->pWhere ){
  96480. sqlite3ExplainPrintf(pVdbe, "WHERE ");
  96481. sqlite3ExplainExpr(pVdbe, p->pWhere);
  96482. sqlite3ExplainNL(pVdbe);
  96483. }
  96484. if( p->pGroupBy ){
  96485. sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
  96486. sqlite3ExplainExprList(pVdbe, p->pGroupBy);
  96487. sqlite3ExplainNL(pVdbe);
  96488. }
  96489. if( p->pHaving ){
  96490. sqlite3ExplainPrintf(pVdbe, "HAVING ");
  96491. sqlite3ExplainExpr(pVdbe, p->pHaving);
  96492. sqlite3ExplainNL(pVdbe);
  96493. }
  96494. if( p->pOrderBy ){
  96495. sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
  96496. sqlite3ExplainExprList(pVdbe, p->pOrderBy);
  96497. sqlite3ExplainNL(pVdbe);
  96498. }
  96499. if( p->pLimit ){
  96500. sqlite3ExplainPrintf(pVdbe, "LIMIT ");
  96501. sqlite3ExplainExpr(pVdbe, p->pLimit);
  96502. sqlite3ExplainNL(pVdbe);
  96503. }
  96504. if( p->pOffset ){
  96505. sqlite3ExplainPrintf(pVdbe, "OFFSET ");
  96506. sqlite3ExplainExpr(pVdbe, p->pOffset);
  96507. sqlite3ExplainNL(pVdbe);
  96508. }
  96509. }
  96510. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
  96511. if( p==0 ){
  96512. sqlite3ExplainPrintf(pVdbe, "(null-select)");
  96513. return;
  96514. }
  96515. while( p->pPrior ){
  96516. p->pPrior->pNext = p;
  96517. p = p->pPrior;
  96518. }
  96519. sqlite3ExplainPush(pVdbe);
  96520. while( p ){
  96521. explainOneSelect(pVdbe, p);
  96522. p = p->pNext;
  96523. if( p==0 ) break;
  96524. sqlite3ExplainNL(pVdbe);
  96525. sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
  96526. }
  96527. sqlite3ExplainPrintf(pVdbe, "END");
  96528. sqlite3ExplainPop(pVdbe);
  96529. }
  96530. /* End of the structure debug printing code
  96531. *****************************************************************************/
  96532. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  96533. /************** End of select.c **********************************************/
  96534. /************** Begin file table.c *******************************************/
  96535. /*
  96536. ** 2001 September 15
  96537. **
  96538. ** The author disclaims copyright to this source code. In place of
  96539. ** a legal notice, here is a blessing:
  96540. **
  96541. ** May you do good and not evil.
  96542. ** May you find forgiveness for yourself and forgive others.
  96543. ** May you share freely, never taking more than you give.
  96544. **
  96545. *************************************************************************
  96546. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  96547. ** interface routines. These are just wrappers around the main
  96548. ** interface routine of sqlite3_exec().
  96549. **
  96550. ** These routines are in a separate files so that they will not be linked
  96551. ** if they are not used.
  96552. */
  96553. /* #include <stdlib.h> */
  96554. /* #include <string.h> */
  96555. #ifndef SQLITE_OMIT_GET_TABLE
  96556. /*
  96557. ** This structure is used to pass data from sqlite3_get_table() through
  96558. ** to the callback function is uses to build the result.
  96559. */
  96560. typedef struct TabResult {
  96561. char **azResult; /* Accumulated output */
  96562. char *zErrMsg; /* Error message text, if an error occurs */
  96563. int nAlloc; /* Slots allocated for azResult[] */
  96564. int nRow; /* Number of rows in the result */
  96565. int nColumn; /* Number of columns in the result */
  96566. int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  96567. int rc; /* Return code from sqlite3_exec() */
  96568. } TabResult;
  96569. /*
  96570. ** This routine is called once for each row in the result table. Its job
  96571. ** is to fill in the TabResult structure appropriately, allocating new
  96572. ** memory as necessary.
  96573. */
  96574. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  96575. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  96576. int need; /* Slots needed in p->azResult[] */
  96577. int i; /* Loop counter */
  96578. char *z; /* A single column of result */
  96579. /* Make sure there is enough space in p->azResult to hold everything
  96580. ** we need to remember from this invocation of the callback.
  96581. */
  96582. if( p->nRow==0 && argv!=0 ){
  96583. need = nCol*2;
  96584. }else{
  96585. need = nCol;
  96586. }
  96587. if( p->nData + need > p->nAlloc ){
  96588. char **azNew;
  96589. p->nAlloc = p->nAlloc*2 + need;
  96590. azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
  96591. if( azNew==0 ) goto malloc_failed;
  96592. p->azResult = azNew;
  96593. }
  96594. /* If this is the first row, then generate an extra row containing
  96595. ** the names of all columns.
  96596. */
  96597. if( p->nRow==0 ){
  96598. p->nColumn = nCol;
  96599. for(i=0; i<nCol; i++){
  96600. z = sqlite3_mprintf("%s", colv[i]);
  96601. if( z==0 ) goto malloc_failed;
  96602. p->azResult[p->nData++] = z;
  96603. }
  96604. }else if( p->nColumn!=nCol ){
  96605. sqlite3_free(p->zErrMsg);
  96606. p->zErrMsg = sqlite3_mprintf(
  96607. "sqlite3_get_table() called with two or more incompatible queries"
  96608. );
  96609. p->rc = SQLITE_ERROR;
  96610. return 1;
  96611. }
  96612. /* Copy over the row data
  96613. */
  96614. if( argv!=0 ){
  96615. for(i=0; i<nCol; i++){
  96616. if( argv[i]==0 ){
  96617. z = 0;
  96618. }else{
  96619. int n = sqlite3Strlen30(argv[i])+1;
  96620. z = sqlite3_malloc( n );
  96621. if( z==0 ) goto malloc_failed;
  96622. memcpy(z, argv[i], n);
  96623. }
  96624. p->azResult[p->nData++] = z;
  96625. }
  96626. p->nRow++;
  96627. }
  96628. return 0;
  96629. malloc_failed:
  96630. p->rc = SQLITE_NOMEM;
  96631. return 1;
  96632. }
  96633. /*
  96634. ** Query the database. But instead of invoking a callback for each row,
  96635. ** malloc() for space to hold the result and return the entire results
  96636. ** at the conclusion of the call.
  96637. **
  96638. ** The result that is written to ***pazResult is held in memory obtained
  96639. ** from malloc(). But the caller cannot free this memory directly.
  96640. ** Instead, the entire table should be passed to sqlite3_free_table() when
  96641. ** the calling procedure is finished using it.
  96642. */
  96643. SQLITE_API int sqlite3_get_table(
  96644. sqlite3 *db, /* The database on which the SQL executes */
  96645. const char *zSql, /* The SQL to be executed */
  96646. char ***pazResult, /* Write the result table here */
  96647. int *pnRow, /* Write the number of rows in the result here */
  96648. int *pnColumn, /* Write the number of columns of result here */
  96649. char **pzErrMsg /* Write error messages here */
  96650. ){
  96651. int rc;
  96652. TabResult res;
  96653. *pazResult = 0;
  96654. if( pnColumn ) *pnColumn = 0;
  96655. if( pnRow ) *pnRow = 0;
  96656. if( pzErrMsg ) *pzErrMsg = 0;
  96657. res.zErrMsg = 0;
  96658. res.nRow = 0;
  96659. res.nColumn = 0;
  96660. res.nData = 1;
  96661. res.nAlloc = 20;
  96662. res.rc = SQLITE_OK;
  96663. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  96664. if( res.azResult==0 ){
  96665. db->errCode = SQLITE_NOMEM;
  96666. return SQLITE_NOMEM;
  96667. }
  96668. res.azResult[0] = 0;
  96669. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  96670. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  96671. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  96672. if( (rc&0xff)==SQLITE_ABORT ){
  96673. sqlite3_free_table(&res.azResult[1]);
  96674. if( res.zErrMsg ){
  96675. if( pzErrMsg ){
  96676. sqlite3_free(*pzErrMsg);
  96677. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  96678. }
  96679. sqlite3_free(res.zErrMsg);
  96680. }
  96681. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  96682. return res.rc;
  96683. }
  96684. sqlite3_free(res.zErrMsg);
  96685. if( rc!=SQLITE_OK ){
  96686. sqlite3_free_table(&res.azResult[1]);
  96687. return rc;
  96688. }
  96689. if( res.nAlloc>res.nData ){
  96690. char **azNew;
  96691. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
  96692. if( azNew==0 ){
  96693. sqlite3_free_table(&res.azResult[1]);
  96694. db->errCode = SQLITE_NOMEM;
  96695. return SQLITE_NOMEM;
  96696. }
  96697. res.azResult = azNew;
  96698. }
  96699. *pazResult = &res.azResult[1];
  96700. if( pnColumn ) *pnColumn = res.nColumn;
  96701. if( pnRow ) *pnRow = res.nRow;
  96702. return rc;
  96703. }
  96704. /*
  96705. ** This routine frees the space the sqlite3_get_table() malloced.
  96706. */
  96707. SQLITE_API void sqlite3_free_table(
  96708. char **azResult /* Result returned from from sqlite3_get_table() */
  96709. ){
  96710. if( azResult ){
  96711. int i, n;
  96712. azResult--;
  96713. assert( azResult!=0 );
  96714. n = SQLITE_PTR_TO_INT(azResult[0]);
  96715. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  96716. sqlite3_free(azResult);
  96717. }
  96718. }
  96719. #endif /* SQLITE_OMIT_GET_TABLE */
  96720. /************** End of table.c ***********************************************/
  96721. /************** Begin file trigger.c *****************************************/
  96722. /*
  96723. **
  96724. ** The author disclaims copyright to this source code. In place of
  96725. ** a legal notice, here is a blessing:
  96726. **
  96727. ** May you do good and not evil.
  96728. ** May you find forgiveness for yourself and forgive others.
  96729. ** May you share freely, never taking more than you give.
  96730. **
  96731. *************************************************************************
  96732. ** This file contains the implementation for TRIGGERs
  96733. */
  96734. #ifndef SQLITE_OMIT_TRIGGER
  96735. /*
  96736. ** Delete a linked list of TriggerStep structures.
  96737. */
  96738. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  96739. while( pTriggerStep ){
  96740. TriggerStep * pTmp = pTriggerStep;
  96741. pTriggerStep = pTriggerStep->pNext;
  96742. sqlite3ExprDelete(db, pTmp->pWhere);
  96743. sqlite3ExprListDelete(db, pTmp->pExprList);
  96744. sqlite3SelectDelete(db, pTmp->pSelect);
  96745. sqlite3IdListDelete(db, pTmp->pIdList);
  96746. sqlite3DbFree(db, pTmp);
  96747. }
  96748. }
  96749. /*
  96750. ** Given table pTab, return a list of all the triggers attached to
  96751. ** the table. The list is connected by Trigger.pNext pointers.
  96752. **
  96753. ** All of the triggers on pTab that are in the same database as pTab
  96754. ** are already attached to pTab->pTrigger. But there might be additional
  96755. ** triggers on pTab in the TEMP schema. This routine prepends all
  96756. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  96757. ** and returns the combined list.
  96758. **
  96759. ** To state it another way: This routine returns a list of all triggers
  96760. ** that fire off of pTab. The list will include any TEMP triggers on
  96761. ** pTab as well as the triggers lised in pTab->pTrigger.
  96762. */
  96763. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  96764. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  96765. Trigger *pList = 0; /* List of triggers to return */
  96766. if( pParse->disableTriggers ){
  96767. return 0;
  96768. }
  96769. if( pTmpSchema!=pTab->pSchema ){
  96770. HashElem *p;
  96771. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  96772. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  96773. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  96774. if( pTrig->pTabSchema==pTab->pSchema
  96775. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  96776. ){
  96777. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  96778. pList = pTrig;
  96779. }
  96780. }
  96781. }
  96782. return (pList ? pList : pTab->pTrigger);
  96783. }
  96784. /*
  96785. ** This is called by the parser when it sees a CREATE TRIGGER statement
  96786. ** up to the point of the BEGIN before the trigger actions. A Trigger
  96787. ** structure is generated based on the information available and stored
  96788. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  96789. ** sqlite3FinishTrigger() function is called to complete the trigger
  96790. ** construction process.
  96791. */
  96792. SQLITE_PRIVATE void sqlite3BeginTrigger(
  96793. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  96794. Token *pName1, /* The name of the trigger */
  96795. Token *pName2, /* The name of the trigger */
  96796. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  96797. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  96798. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  96799. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  96800. Expr *pWhen, /* WHEN clause */
  96801. int isTemp, /* True if the TEMPORARY keyword is present */
  96802. int noErr /* Suppress errors if the trigger already exists */
  96803. ){
  96804. Trigger *pTrigger = 0; /* The new trigger */
  96805. Table *pTab; /* Table that the trigger fires off of */
  96806. char *zName = 0; /* Name of the trigger */
  96807. sqlite3 *db = pParse->db; /* The database connection */
  96808. int iDb; /* The database to store the trigger in */
  96809. Token *pName; /* The unqualified db name */
  96810. DbFixer sFix; /* State vector for the DB fixer */
  96811. int iTabDb; /* Index of the database holding pTab */
  96812. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  96813. assert( pName2!=0 );
  96814. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  96815. assert( op>0 && op<0xff );
  96816. if( isTemp ){
  96817. /* If TEMP was specified, then the trigger name may not be qualified. */
  96818. if( pName2->n>0 ){
  96819. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  96820. goto trigger_cleanup;
  96821. }
  96822. iDb = 1;
  96823. pName = pName1;
  96824. }else{
  96825. /* Figure out the db that the trigger will be created in */
  96826. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  96827. if( iDb<0 ){
  96828. goto trigger_cleanup;
  96829. }
  96830. }
  96831. if( !pTableName || db->mallocFailed ){
  96832. goto trigger_cleanup;
  96833. }
  96834. /* A long-standing parser bug is that this syntax was allowed:
  96835. **
  96836. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  96837. ** ^^^^^^^^
  96838. **
  96839. ** To maintain backwards compatibility, ignore the database
  96840. ** name on pTableName if we are reparsing our of SQLITE_MASTER.
  96841. */
  96842. if( db->init.busy && iDb!=1 ){
  96843. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  96844. pTableName->a[0].zDatabase = 0;
  96845. }
  96846. /* If the trigger name was unqualified, and the table is a temp table,
  96847. ** then set iDb to 1 to create the trigger in the temporary database.
  96848. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  96849. ** exist, the error is caught by the block below.
  96850. */
  96851. pTab = sqlite3SrcListLookup(pParse, pTableName);
  96852. if( db->init.busy==0 && pName2->n==0 && pTab
  96853. && pTab->pSchema==db->aDb[1].pSchema ){
  96854. iDb = 1;
  96855. }
  96856. /* Ensure the table name matches database name and that the table exists */
  96857. if( db->mallocFailed ) goto trigger_cleanup;
  96858. assert( pTableName->nSrc==1 );
  96859. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  96860. if( sqlite3FixSrcList(&sFix, pTableName) ){
  96861. goto trigger_cleanup;
  96862. }
  96863. pTab = sqlite3SrcListLookup(pParse, pTableName);
  96864. if( !pTab ){
  96865. /* The table does not exist. */
  96866. if( db->init.iDb==1 ){
  96867. /* Ticket #3810.
  96868. ** Normally, whenever a table is dropped, all associated triggers are
  96869. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  96870. ** and the table is dropped by a different database connection, the
  96871. ** trigger is not visible to the database connection that does the
  96872. ** drop so the trigger cannot be dropped. This results in an
  96873. ** "orphaned trigger" - a trigger whose associated table is missing.
  96874. */
  96875. db->init.orphanTrigger = 1;
  96876. }
  96877. goto trigger_cleanup;
  96878. }
  96879. if( IsVirtual(pTab) ){
  96880. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  96881. goto trigger_cleanup;
  96882. }
  96883. /* Check that the trigger name is not reserved and that no trigger of the
  96884. ** specified name exists */
  96885. zName = sqlite3NameFromToken(db, pName);
  96886. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  96887. goto trigger_cleanup;
  96888. }
  96889. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  96890. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
  96891. zName, sqlite3Strlen30(zName)) ){
  96892. if( !noErr ){
  96893. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  96894. }else{
  96895. assert( !db->init.busy );
  96896. sqlite3CodeVerifySchema(pParse, iDb);
  96897. }
  96898. goto trigger_cleanup;
  96899. }
  96900. /* Do not create a trigger on a system table */
  96901. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  96902. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  96903. pParse->nErr++;
  96904. goto trigger_cleanup;
  96905. }
  96906. /* INSTEAD of triggers are only for views and views only support INSTEAD
  96907. ** of triggers.
  96908. */
  96909. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  96910. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  96911. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  96912. goto trigger_cleanup;
  96913. }
  96914. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  96915. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  96916. " trigger on table: %S", pTableName, 0);
  96917. goto trigger_cleanup;
  96918. }
  96919. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  96920. #ifndef SQLITE_OMIT_AUTHORIZATION
  96921. {
  96922. int code = SQLITE_CREATE_TRIGGER;
  96923. const char *zDb = db->aDb[iTabDb].zName;
  96924. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  96925. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  96926. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  96927. goto trigger_cleanup;
  96928. }
  96929. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  96930. goto trigger_cleanup;
  96931. }
  96932. }
  96933. #endif
  96934. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  96935. ** cannot appear on views. So we might as well translate every
  96936. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  96937. ** elsewhere.
  96938. */
  96939. if (tr_tm == TK_INSTEAD){
  96940. tr_tm = TK_BEFORE;
  96941. }
  96942. /* Build the Trigger object */
  96943. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  96944. if( pTrigger==0 ) goto trigger_cleanup;
  96945. pTrigger->zName = zName;
  96946. zName = 0;
  96947. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  96948. pTrigger->pSchema = db->aDb[iDb].pSchema;
  96949. pTrigger->pTabSchema = pTab->pSchema;
  96950. pTrigger->op = (u8)op;
  96951. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  96952. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  96953. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  96954. assert( pParse->pNewTrigger==0 );
  96955. pParse->pNewTrigger = pTrigger;
  96956. trigger_cleanup:
  96957. sqlite3DbFree(db, zName);
  96958. sqlite3SrcListDelete(db, pTableName);
  96959. sqlite3IdListDelete(db, pColumns);
  96960. sqlite3ExprDelete(db, pWhen);
  96961. if( !pParse->pNewTrigger ){
  96962. sqlite3DeleteTrigger(db, pTrigger);
  96963. }else{
  96964. assert( pParse->pNewTrigger==pTrigger );
  96965. }
  96966. }
  96967. /*
  96968. ** This routine is called after all of the trigger actions have been parsed
  96969. ** in order to complete the process of building the trigger.
  96970. */
  96971. SQLITE_PRIVATE void sqlite3FinishTrigger(
  96972. Parse *pParse, /* Parser context */
  96973. TriggerStep *pStepList, /* The triggered program */
  96974. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  96975. ){
  96976. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  96977. char *zName; /* Name of trigger */
  96978. sqlite3 *db = pParse->db; /* The database */
  96979. DbFixer sFix; /* Fixer object */
  96980. int iDb; /* Database containing the trigger */
  96981. Token nameToken; /* Trigger name for error reporting */
  96982. pParse->pNewTrigger = 0;
  96983. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  96984. zName = pTrig->zName;
  96985. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  96986. pTrig->step_list = pStepList;
  96987. while( pStepList ){
  96988. pStepList->pTrig = pTrig;
  96989. pStepList = pStepList->pNext;
  96990. }
  96991. nameToken.z = pTrig->zName;
  96992. nameToken.n = sqlite3Strlen30(nameToken.z);
  96993. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  96994. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  96995. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  96996. ){
  96997. goto triggerfinish_cleanup;
  96998. }
  96999. /* if we are not initializing,
  97000. ** build the sqlite_master entry
  97001. */
  97002. if( !db->init.busy ){
  97003. Vdbe *v;
  97004. char *z;
  97005. /* Make an entry in the sqlite_master table */
  97006. v = sqlite3GetVdbe(pParse);
  97007. if( v==0 ) goto triggerfinish_cleanup;
  97008. sqlite3BeginWriteOperation(pParse, 0, iDb);
  97009. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  97010. sqlite3NestedParse(pParse,
  97011. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  97012. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  97013. pTrig->table, z);
  97014. sqlite3DbFree(db, z);
  97015. sqlite3ChangeCookie(pParse, iDb);
  97016. sqlite3VdbeAddParseSchemaOp(v, iDb,
  97017. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  97018. }
  97019. if( db->init.busy ){
  97020. Trigger *pLink = pTrig;
  97021. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  97022. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97023. pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
  97024. if( pTrig ){
  97025. db->mallocFailed = 1;
  97026. }else if( pLink->pSchema==pLink->pTabSchema ){
  97027. Table *pTab;
  97028. int n = sqlite3Strlen30(pLink->table);
  97029. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
  97030. assert( pTab!=0 );
  97031. pLink->pNext = pTab->pTrigger;
  97032. pTab->pTrigger = pLink;
  97033. }
  97034. }
  97035. triggerfinish_cleanup:
  97036. sqlite3DeleteTrigger(db, pTrig);
  97037. assert( !pParse->pNewTrigger );
  97038. sqlite3DeleteTriggerStep(db, pStepList);
  97039. }
  97040. /*
  97041. ** Turn a SELECT statement (that the pSelect parameter points to) into
  97042. ** a trigger step. Return a pointer to a TriggerStep structure.
  97043. **
  97044. ** The parser calls this routine when it finds a SELECT statement in
  97045. ** body of a TRIGGER.
  97046. */
  97047. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  97048. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  97049. if( pTriggerStep==0 ) {
  97050. sqlite3SelectDelete(db, pSelect);
  97051. return 0;
  97052. }
  97053. pTriggerStep->op = TK_SELECT;
  97054. pTriggerStep->pSelect = pSelect;
  97055. pTriggerStep->orconf = OE_Default;
  97056. return pTriggerStep;
  97057. }
  97058. /*
  97059. ** Allocate space to hold a new trigger step. The allocated space
  97060. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  97061. **
  97062. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  97063. */
  97064. static TriggerStep *triggerStepAllocate(
  97065. sqlite3 *db, /* Database connection */
  97066. u8 op, /* Trigger opcode */
  97067. Token *pName /* The target name */
  97068. ){
  97069. TriggerStep *pTriggerStep;
  97070. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  97071. if( pTriggerStep ){
  97072. char *z = (char*)&pTriggerStep[1];
  97073. memcpy(z, pName->z, pName->n);
  97074. pTriggerStep->target.z = z;
  97075. pTriggerStep->target.n = pName->n;
  97076. pTriggerStep->op = op;
  97077. }
  97078. return pTriggerStep;
  97079. }
  97080. /*
  97081. ** Build a trigger step out of an INSERT statement. Return a pointer
  97082. ** to the new trigger step.
  97083. **
  97084. ** The parser calls this routine when it sees an INSERT inside the
  97085. ** body of a trigger.
  97086. */
  97087. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  97088. sqlite3 *db, /* The database connection */
  97089. Token *pTableName, /* Name of the table into which we insert */
  97090. IdList *pColumn, /* List of columns in pTableName to insert into */
  97091. ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  97092. Select *pSelect, /* A SELECT statement that supplies values */
  97093. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  97094. ){
  97095. TriggerStep *pTriggerStep;
  97096. assert(pEList == 0 || pSelect == 0);
  97097. assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
  97098. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  97099. if( pTriggerStep ){
  97100. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  97101. pTriggerStep->pIdList = pColumn;
  97102. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  97103. pTriggerStep->orconf = orconf;
  97104. }else{
  97105. sqlite3IdListDelete(db, pColumn);
  97106. }
  97107. sqlite3ExprListDelete(db, pEList);
  97108. sqlite3SelectDelete(db, pSelect);
  97109. return pTriggerStep;
  97110. }
  97111. /*
  97112. ** Construct a trigger step that implements an UPDATE statement and return
  97113. ** a pointer to that trigger step. The parser calls this routine when it
  97114. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  97115. */
  97116. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  97117. sqlite3 *db, /* The database connection */
  97118. Token *pTableName, /* Name of the table to be updated */
  97119. ExprList *pEList, /* The SET clause: list of column and new values */
  97120. Expr *pWhere, /* The WHERE clause */
  97121. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  97122. ){
  97123. TriggerStep *pTriggerStep;
  97124. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  97125. if( pTriggerStep ){
  97126. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  97127. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  97128. pTriggerStep->orconf = orconf;
  97129. }
  97130. sqlite3ExprListDelete(db, pEList);
  97131. sqlite3ExprDelete(db, pWhere);
  97132. return pTriggerStep;
  97133. }
  97134. /*
  97135. ** Construct a trigger step that implements a DELETE statement and return
  97136. ** a pointer to that trigger step. The parser calls this routine when it
  97137. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  97138. */
  97139. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  97140. sqlite3 *db, /* Database connection */
  97141. Token *pTableName, /* The table from which rows are deleted */
  97142. Expr *pWhere /* The WHERE clause */
  97143. ){
  97144. TriggerStep *pTriggerStep;
  97145. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  97146. if( pTriggerStep ){
  97147. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  97148. pTriggerStep->orconf = OE_Default;
  97149. }
  97150. sqlite3ExprDelete(db, pWhere);
  97151. return pTriggerStep;
  97152. }
  97153. /*
  97154. ** Recursively delete a Trigger structure
  97155. */
  97156. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  97157. if( pTrigger==0 ) return;
  97158. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  97159. sqlite3DbFree(db, pTrigger->zName);
  97160. sqlite3DbFree(db, pTrigger->table);
  97161. sqlite3ExprDelete(db, pTrigger->pWhen);
  97162. sqlite3IdListDelete(db, pTrigger->pColumns);
  97163. sqlite3DbFree(db, pTrigger);
  97164. }
  97165. /*
  97166. ** This function is called to drop a trigger from the database schema.
  97167. **
  97168. ** This may be called directly from the parser and therefore identifies
  97169. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  97170. ** same job as this routine except it takes a pointer to the trigger
  97171. ** instead of the trigger name.
  97172. **/
  97173. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  97174. Trigger *pTrigger = 0;
  97175. int i;
  97176. const char *zDb;
  97177. const char *zName;
  97178. int nName;
  97179. sqlite3 *db = pParse->db;
  97180. if( db->mallocFailed ) goto drop_trigger_cleanup;
  97181. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  97182. goto drop_trigger_cleanup;
  97183. }
  97184. assert( pName->nSrc==1 );
  97185. zDb = pName->a[0].zDatabase;
  97186. zName = pName->a[0].zName;
  97187. nName = sqlite3Strlen30(zName);
  97188. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  97189. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  97190. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  97191. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  97192. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  97193. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
  97194. if( pTrigger ) break;
  97195. }
  97196. if( !pTrigger ){
  97197. if( !noErr ){
  97198. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  97199. }else{
  97200. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  97201. }
  97202. pParse->checkSchema = 1;
  97203. goto drop_trigger_cleanup;
  97204. }
  97205. sqlite3DropTriggerPtr(pParse, pTrigger);
  97206. drop_trigger_cleanup:
  97207. sqlite3SrcListDelete(db, pName);
  97208. }
  97209. /*
  97210. ** Return a pointer to the Table structure for the table that a trigger
  97211. ** is set on.
  97212. */
  97213. static Table *tableOfTrigger(Trigger *pTrigger){
  97214. int n = sqlite3Strlen30(pTrigger->table);
  97215. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
  97216. }
  97217. /*
  97218. ** Drop a trigger given a pointer to that trigger.
  97219. */
  97220. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  97221. Table *pTable;
  97222. Vdbe *v;
  97223. sqlite3 *db = pParse->db;
  97224. int iDb;
  97225. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  97226. assert( iDb>=0 && iDb<db->nDb );
  97227. pTable = tableOfTrigger(pTrigger);
  97228. assert( pTable );
  97229. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  97230. #ifndef SQLITE_OMIT_AUTHORIZATION
  97231. {
  97232. int code = SQLITE_DROP_TRIGGER;
  97233. const char *zDb = db->aDb[iDb].zName;
  97234. const char *zTab = SCHEMA_TABLE(iDb);
  97235. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  97236. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  97237. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  97238. return;
  97239. }
  97240. }
  97241. #endif
  97242. /* Generate code to destroy the database record of the trigger.
  97243. */
  97244. assert( pTable!=0 );
  97245. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  97246. int base;
  97247. static const VdbeOpList dropTrigger[] = {
  97248. { OP_Rewind, 0, ADDR(9), 0},
  97249. { OP_String8, 0, 1, 0}, /* 1 */
  97250. { OP_Column, 0, 1, 2},
  97251. { OP_Ne, 2, ADDR(8), 1},
  97252. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  97253. { OP_Column, 0, 0, 2},
  97254. { OP_Ne, 2, ADDR(8), 1},
  97255. { OP_Delete, 0, 0, 0},
  97256. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  97257. };
  97258. sqlite3BeginWriteOperation(pParse, 0, iDb);
  97259. sqlite3OpenMasterTable(pParse, iDb);
  97260. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  97261. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  97262. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  97263. sqlite3ChangeCookie(pParse, iDb);
  97264. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  97265. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  97266. if( pParse->nMem<3 ){
  97267. pParse->nMem = 3;
  97268. }
  97269. }
  97270. }
  97271. /*
  97272. ** Remove a trigger from the hash tables of the sqlite* pointer.
  97273. */
  97274. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  97275. Trigger *pTrigger;
  97276. Hash *pHash;
  97277. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97278. pHash = &(db->aDb[iDb].pSchema->trigHash);
  97279. pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
  97280. if( ALWAYS(pTrigger) ){
  97281. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  97282. Table *pTab = tableOfTrigger(pTrigger);
  97283. Trigger **pp;
  97284. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  97285. *pp = (*pp)->pNext;
  97286. }
  97287. sqlite3DeleteTrigger(db, pTrigger);
  97288. db->flags |= SQLITE_InternChanges;
  97289. }
  97290. }
  97291. /*
  97292. ** pEList is the SET clause of an UPDATE statement. Each entry
  97293. ** in pEList is of the format <id>=<expr>. If any of the entries
  97294. ** in pEList have an <id> which matches an identifier in pIdList,
  97295. ** then return TRUE. If pIdList==NULL, then it is considered a
  97296. ** wildcard that matches anything. Likewise if pEList==NULL then
  97297. ** it matches anything so always return true. Return false only
  97298. ** if there is no match.
  97299. */
  97300. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  97301. int e;
  97302. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  97303. for(e=0; e<pEList->nExpr; e++){
  97304. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  97305. }
  97306. return 0;
  97307. }
  97308. /*
  97309. ** Return a list of all triggers on table pTab if there exists at least
  97310. ** one trigger that must be fired when an operation of type 'op' is
  97311. ** performed on the table, and, if that operation is an UPDATE, if at
  97312. ** least one of the columns in pChanges is being modified.
  97313. */
  97314. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  97315. Parse *pParse, /* Parse context */
  97316. Table *pTab, /* The table the contains the triggers */
  97317. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  97318. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  97319. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  97320. ){
  97321. int mask = 0;
  97322. Trigger *pList = 0;
  97323. Trigger *p;
  97324. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  97325. pList = sqlite3TriggerList(pParse, pTab);
  97326. }
  97327. assert( pList==0 || IsVirtual(pTab)==0 );
  97328. for(p=pList; p; p=p->pNext){
  97329. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  97330. mask |= p->tr_tm;
  97331. }
  97332. }
  97333. if( pMask ){
  97334. *pMask = mask;
  97335. }
  97336. return (mask ? pList : 0);
  97337. }
  97338. /*
  97339. ** Convert the pStep->target token into a SrcList and return a pointer
  97340. ** to that SrcList.
  97341. **
  97342. ** This routine adds a specific database name, if needed, to the target when
  97343. ** forming the SrcList. This prevents a trigger in one database from
  97344. ** referring to a target in another database. An exception is when the
  97345. ** trigger is in TEMP in which case it can refer to any other database it
  97346. ** wants.
  97347. */
  97348. static SrcList *targetSrcList(
  97349. Parse *pParse, /* The parsing context */
  97350. TriggerStep *pStep /* The trigger containing the target token */
  97351. ){
  97352. int iDb; /* Index of the database to use */
  97353. SrcList *pSrc; /* SrcList to be returned */
  97354. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  97355. if( pSrc ){
  97356. assert( pSrc->nSrc>0 );
  97357. assert( pSrc->a!=0 );
  97358. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  97359. if( iDb==0 || iDb>=2 ){
  97360. sqlite3 *db = pParse->db;
  97361. assert( iDb<pParse->db->nDb );
  97362. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  97363. }
  97364. }
  97365. return pSrc;
  97366. }
  97367. /*
  97368. ** Generate VDBE code for the statements inside the body of a single
  97369. ** trigger.
  97370. */
  97371. static int codeTriggerProgram(
  97372. Parse *pParse, /* The parser context */
  97373. TriggerStep *pStepList, /* List of statements inside the trigger body */
  97374. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  97375. ){
  97376. TriggerStep *pStep;
  97377. Vdbe *v = pParse->pVdbe;
  97378. sqlite3 *db = pParse->db;
  97379. assert( pParse->pTriggerTab && pParse->pToplevel );
  97380. assert( pStepList );
  97381. assert( v!=0 );
  97382. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  97383. /* Figure out the ON CONFLICT policy that will be used for this step
  97384. ** of the trigger program. If the statement that caused this trigger
  97385. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  97386. ** the ON CONFLICT policy that was specified as part of the trigger
  97387. ** step statement. Example:
  97388. **
  97389. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  97390. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  97391. ** END;
  97392. **
  97393. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  97394. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  97395. */
  97396. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  97397. /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
  97398. ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
  97399. ** that it is not safe to refactor constants (this happens after the
  97400. ** start of the first loop in the SQL statement is coded - at that
  97401. ** point code may be conditionally executed, so it is no longer safe to
  97402. ** initialize constant register values). */
  97403. assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
  97404. pParse->cookieGoto = 0;
  97405. switch( pStep->op ){
  97406. case TK_UPDATE: {
  97407. sqlite3Update(pParse,
  97408. targetSrcList(pParse, pStep),
  97409. sqlite3ExprListDup(db, pStep->pExprList, 0),
  97410. sqlite3ExprDup(db, pStep->pWhere, 0),
  97411. pParse->eOrconf
  97412. );
  97413. break;
  97414. }
  97415. case TK_INSERT: {
  97416. sqlite3Insert(pParse,
  97417. targetSrcList(pParse, pStep),
  97418. sqlite3ExprListDup(db, pStep->pExprList, 0),
  97419. sqlite3SelectDup(db, pStep->pSelect, 0),
  97420. sqlite3IdListDup(db, pStep->pIdList),
  97421. pParse->eOrconf
  97422. );
  97423. break;
  97424. }
  97425. case TK_DELETE: {
  97426. sqlite3DeleteFrom(pParse,
  97427. targetSrcList(pParse, pStep),
  97428. sqlite3ExprDup(db, pStep->pWhere, 0)
  97429. );
  97430. break;
  97431. }
  97432. default: assert( pStep->op==TK_SELECT ); {
  97433. SelectDest sDest;
  97434. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  97435. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  97436. sqlite3Select(pParse, pSelect, &sDest);
  97437. sqlite3SelectDelete(db, pSelect);
  97438. break;
  97439. }
  97440. }
  97441. if( pStep->op!=TK_SELECT ){
  97442. sqlite3VdbeAddOp0(v, OP_ResetCount);
  97443. }
  97444. }
  97445. return 0;
  97446. }
  97447. #ifdef SQLITE_DEBUG
  97448. /*
  97449. ** This function is used to add VdbeComment() annotations to a VDBE
  97450. ** program. It is not used in production code, only for debugging.
  97451. */
  97452. static const char *onErrorText(int onError){
  97453. switch( onError ){
  97454. case OE_Abort: return "abort";
  97455. case OE_Rollback: return "rollback";
  97456. case OE_Fail: return "fail";
  97457. case OE_Replace: return "replace";
  97458. case OE_Ignore: return "ignore";
  97459. case OE_Default: return "default";
  97460. }
  97461. return "n/a";
  97462. }
  97463. #endif
  97464. /*
  97465. ** Parse context structure pFrom has just been used to create a sub-vdbe
  97466. ** (trigger program). If an error has occurred, transfer error information
  97467. ** from pFrom to pTo.
  97468. */
  97469. static void transferParseError(Parse *pTo, Parse *pFrom){
  97470. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  97471. assert( pTo->zErrMsg==0 || pTo->nErr );
  97472. if( pTo->nErr==0 ){
  97473. pTo->zErrMsg = pFrom->zErrMsg;
  97474. pTo->nErr = pFrom->nErr;
  97475. }else{
  97476. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  97477. }
  97478. }
  97479. /*
  97480. ** Create and populate a new TriggerPrg object with a sub-program
  97481. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  97482. */
  97483. static TriggerPrg *codeRowTrigger(
  97484. Parse *pParse, /* Current parse context */
  97485. Trigger *pTrigger, /* Trigger to code */
  97486. Table *pTab, /* The table pTrigger is attached to */
  97487. int orconf /* ON CONFLICT policy to code trigger program with */
  97488. ){
  97489. Parse *pTop = sqlite3ParseToplevel(pParse);
  97490. sqlite3 *db = pParse->db; /* Database handle */
  97491. TriggerPrg *pPrg; /* Value to return */
  97492. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  97493. Vdbe *v; /* Temporary VM */
  97494. NameContext sNC; /* Name context for sub-vdbe */
  97495. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  97496. Parse *pSubParse; /* Parse context for sub-vdbe */
  97497. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  97498. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  97499. assert( pTop->pVdbe );
  97500. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  97501. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  97502. ** list of the top-level Parse object sooner rather than later. */
  97503. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  97504. if( !pPrg ) return 0;
  97505. pPrg->pNext = pTop->pTriggerPrg;
  97506. pTop->pTriggerPrg = pPrg;
  97507. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  97508. if( !pProgram ) return 0;
  97509. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  97510. pPrg->pTrigger = pTrigger;
  97511. pPrg->orconf = orconf;
  97512. pPrg->aColmask[0] = 0xffffffff;
  97513. pPrg->aColmask[1] = 0xffffffff;
  97514. /* Allocate and populate a new Parse context to use for coding the
  97515. ** trigger sub-program. */
  97516. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  97517. if( !pSubParse ) return 0;
  97518. memset(&sNC, 0, sizeof(sNC));
  97519. sNC.pParse = pSubParse;
  97520. pSubParse->db = db;
  97521. pSubParse->pTriggerTab = pTab;
  97522. pSubParse->pToplevel = pTop;
  97523. pSubParse->zAuthContext = pTrigger->zName;
  97524. pSubParse->eTriggerOp = pTrigger->op;
  97525. pSubParse->nQueryLoop = pParse->nQueryLoop;
  97526. v = sqlite3GetVdbe(pSubParse);
  97527. if( v ){
  97528. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  97529. pTrigger->zName, onErrorText(orconf),
  97530. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  97531. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  97532. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  97533. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  97534. pTab->zName
  97535. ));
  97536. #ifndef SQLITE_OMIT_TRACE
  97537. sqlite3VdbeChangeP4(v, -1,
  97538. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  97539. );
  97540. #endif
  97541. /* If one was specified, code the WHEN clause. If it evaluates to false
  97542. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  97543. ** OP_Halt inserted at the end of the program. */
  97544. if( pTrigger->pWhen ){
  97545. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  97546. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  97547. && db->mallocFailed==0
  97548. ){
  97549. iEndTrigger = sqlite3VdbeMakeLabel(v);
  97550. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  97551. }
  97552. sqlite3ExprDelete(db, pWhen);
  97553. }
  97554. /* Code the trigger program into the sub-vdbe. */
  97555. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  97556. /* Insert an OP_Halt at the end of the sub-program. */
  97557. if( iEndTrigger ){
  97558. sqlite3VdbeResolveLabel(v, iEndTrigger);
  97559. }
  97560. sqlite3VdbeAddOp0(v, OP_Halt);
  97561. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  97562. transferParseError(pParse, pSubParse);
  97563. if( db->mallocFailed==0 ){
  97564. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  97565. }
  97566. pProgram->nMem = pSubParse->nMem;
  97567. pProgram->nCsr = pSubParse->nTab;
  97568. pProgram->nOnce = pSubParse->nOnce;
  97569. pProgram->token = (void *)pTrigger;
  97570. pPrg->aColmask[0] = pSubParse->oldmask;
  97571. pPrg->aColmask[1] = pSubParse->newmask;
  97572. sqlite3VdbeDelete(v);
  97573. }
  97574. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  97575. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  97576. sqlite3StackFree(db, pSubParse);
  97577. return pPrg;
  97578. }
  97579. /*
  97580. ** Return a pointer to a TriggerPrg object containing the sub-program for
  97581. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  97582. ** TriggerPrg object exists, a new object is allocated and populated before
  97583. ** being returned.
  97584. */
  97585. static TriggerPrg *getRowTrigger(
  97586. Parse *pParse, /* Current parse context */
  97587. Trigger *pTrigger, /* Trigger to code */
  97588. Table *pTab, /* The table trigger pTrigger is attached to */
  97589. int orconf /* ON CONFLICT algorithm. */
  97590. ){
  97591. Parse *pRoot = sqlite3ParseToplevel(pParse);
  97592. TriggerPrg *pPrg;
  97593. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  97594. /* It may be that this trigger has already been coded (or is in the
  97595. ** process of being coded). If this is the case, then an entry with
  97596. ** a matching TriggerPrg.pTrigger field will be present somewhere
  97597. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  97598. for(pPrg=pRoot->pTriggerPrg;
  97599. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  97600. pPrg=pPrg->pNext
  97601. );
  97602. /* If an existing TriggerPrg could not be located, create a new one. */
  97603. if( !pPrg ){
  97604. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  97605. }
  97606. return pPrg;
  97607. }
  97608. /*
  97609. ** Generate code for the trigger program associated with trigger p on
  97610. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  97611. ** function are the same as those described in the header function for
  97612. ** sqlite3CodeRowTrigger()
  97613. */
  97614. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  97615. Parse *pParse, /* Parse context */
  97616. Trigger *p, /* Trigger to code */
  97617. Table *pTab, /* The table to code triggers from */
  97618. int reg, /* Reg array containing OLD.* and NEW.* values */
  97619. int orconf, /* ON CONFLICT policy */
  97620. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  97621. ){
  97622. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  97623. TriggerPrg *pPrg;
  97624. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  97625. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  97626. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  97627. ** is a pointer to the sub-vdbe containing the trigger program. */
  97628. if( pPrg ){
  97629. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  97630. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  97631. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  97632. VdbeComment(
  97633. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  97634. /* Set the P5 operand of the OP_Program instruction to non-zero if
  97635. ** recursive invocation of this trigger program is disallowed. Recursive
  97636. ** invocation is disallowed if (a) the sub-program is really a trigger,
  97637. ** not a foreign key action, and (b) the flag to enable recursive triggers
  97638. ** is clear. */
  97639. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  97640. }
  97641. }
  97642. /*
  97643. ** This is called to code the required FOR EACH ROW triggers for an operation
  97644. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  97645. ** is given by the op parameter. The tr_tm parameter determines whether the
  97646. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  97647. ** parameter pChanges is passed the list of columns being modified.
  97648. **
  97649. ** If there are no triggers that fire at the specified time for the specified
  97650. ** operation on pTab, this function is a no-op.
  97651. **
  97652. ** The reg argument is the address of the first in an array of registers
  97653. ** that contain the values substituted for the new.* and old.* references
  97654. ** in the trigger program. If N is the number of columns in table pTab
  97655. ** (a copy of pTab->nCol), then registers are populated as follows:
  97656. **
  97657. ** Register Contains
  97658. ** ------------------------------------------------------
  97659. ** reg+0 OLD.rowid
  97660. ** reg+1 OLD.* value of left-most column of pTab
  97661. ** ... ...
  97662. ** reg+N OLD.* value of right-most column of pTab
  97663. ** reg+N+1 NEW.rowid
  97664. ** reg+N+2 OLD.* value of left-most column of pTab
  97665. ** ... ...
  97666. ** reg+N+N+1 NEW.* value of right-most column of pTab
  97667. **
  97668. ** For ON DELETE triggers, the registers containing the NEW.* values will
  97669. ** never be accessed by the trigger program, so they are not allocated or
  97670. ** populated by the caller (there is no data to populate them with anyway).
  97671. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  97672. ** are never accessed, and so are not allocated by the caller. So, for an
  97673. ** ON INSERT trigger, the value passed to this function as parameter reg
  97674. ** is not a readable register, although registers (reg+N) through
  97675. ** (reg+N+N+1) are.
  97676. **
  97677. ** Parameter orconf is the default conflict resolution algorithm for the
  97678. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  97679. ** is the instruction that control should jump to if a trigger program
  97680. ** raises an IGNORE exception.
  97681. */
  97682. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  97683. Parse *pParse, /* Parse context */
  97684. Trigger *pTrigger, /* List of triggers on table pTab */
  97685. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  97686. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  97687. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  97688. Table *pTab, /* The table to code triggers from */
  97689. int reg, /* The first in an array of registers (see above) */
  97690. int orconf, /* ON CONFLICT policy */
  97691. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  97692. ){
  97693. Trigger *p; /* Used to iterate through pTrigger list */
  97694. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  97695. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  97696. assert( (op==TK_UPDATE)==(pChanges!=0) );
  97697. for(p=pTrigger; p; p=p->pNext){
  97698. /* Sanity checking: The schema for the trigger and for the table are
  97699. ** always defined. The trigger must be in the same schema as the table
  97700. ** or else it must be a TEMP trigger. */
  97701. assert( p->pSchema!=0 );
  97702. assert( p->pTabSchema!=0 );
  97703. assert( p->pSchema==p->pTabSchema
  97704. || p->pSchema==pParse->db->aDb[1].pSchema );
  97705. /* Determine whether we should code this trigger */
  97706. if( p->op==op
  97707. && p->tr_tm==tr_tm
  97708. && checkColumnOverlap(p->pColumns, pChanges)
  97709. ){
  97710. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  97711. }
  97712. }
  97713. }
  97714. /*
  97715. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  97716. ** This function returns a 32-bit bitmask indicating which columns of the
  97717. ** old.* or new.* tables actually are used by triggers. This information
  97718. ** may be used by the caller, for example, to avoid having to load the entire
  97719. ** old.* record into memory when executing an UPDATE or DELETE command.
  97720. **
  97721. ** Bit 0 of the returned mask is set if the left-most column of the
  97722. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  97723. ** the second leftmost column value is required, and so on. If there
  97724. ** are more than 32 columns in the table, and at least one of the columns
  97725. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  97726. **
  97727. ** It is not possible to determine if the old.rowid or new.rowid column is
  97728. ** accessed by triggers. The caller must always assume that it is.
  97729. **
  97730. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  97731. ** applies to the old.* table. If 1, the new.* table.
  97732. **
  97733. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  97734. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  97735. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  97736. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  97737. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  97738. */
  97739. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  97740. Parse *pParse, /* Parse context */
  97741. Trigger *pTrigger, /* List of triggers on table pTab */
  97742. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  97743. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  97744. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  97745. Table *pTab, /* The table to code triggers from */
  97746. int orconf /* Default ON CONFLICT policy for trigger steps */
  97747. ){
  97748. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  97749. u32 mask = 0;
  97750. Trigger *p;
  97751. assert( isNew==1 || isNew==0 );
  97752. for(p=pTrigger; p; p=p->pNext){
  97753. if( p->op==op && (tr_tm&p->tr_tm)
  97754. && checkColumnOverlap(p->pColumns,pChanges)
  97755. ){
  97756. TriggerPrg *pPrg;
  97757. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  97758. if( pPrg ){
  97759. mask |= pPrg->aColmask[isNew];
  97760. }
  97761. }
  97762. }
  97763. return mask;
  97764. }
  97765. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  97766. /************** End of trigger.c *********************************************/
  97767. /************** Begin file update.c ******************************************/
  97768. /*
  97769. ** 2001 September 15
  97770. **
  97771. ** The author disclaims copyright to this source code. In place of
  97772. ** a legal notice, here is a blessing:
  97773. **
  97774. ** May you do good and not evil.
  97775. ** May you find forgiveness for yourself and forgive others.
  97776. ** May you share freely, never taking more than you give.
  97777. **
  97778. *************************************************************************
  97779. ** This file contains C code routines that are called by the parser
  97780. ** to handle UPDATE statements.
  97781. */
  97782. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97783. /* Forward declaration */
  97784. static void updateVirtualTable(
  97785. Parse *pParse, /* The parsing context */
  97786. SrcList *pSrc, /* The virtual table to be modified */
  97787. Table *pTab, /* The virtual table */
  97788. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  97789. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  97790. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  97791. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  97792. int onError /* ON CONFLICT strategy */
  97793. );
  97794. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  97795. /*
  97796. ** The most recently coded instruction was an OP_Column to retrieve the
  97797. ** i-th column of table pTab. This routine sets the P4 parameter of the
  97798. ** OP_Column to the default value, if any.
  97799. **
  97800. ** The default value of a column is specified by a DEFAULT clause in the
  97801. ** column definition. This was either supplied by the user when the table
  97802. ** was created, or added later to the table definition by an ALTER TABLE
  97803. ** command. If the latter, then the row-records in the table btree on disk
  97804. ** may not contain a value for the column and the default value, taken
  97805. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  97806. ** If the former, then all row-records are guaranteed to include a value
  97807. ** for the column and the P4 value is not required.
  97808. **
  97809. ** Column definitions created by an ALTER TABLE command may only have
  97810. ** literal default values specified: a number, null or a string. (If a more
  97811. ** complicated default expression value was provided, it is evaluated
  97812. ** when the ALTER TABLE is executed and one of the literal values written
  97813. ** into the sqlite_master table.)
  97814. **
  97815. ** Therefore, the P4 parameter is only required if the default value for
  97816. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  97817. ** function is capable of transforming these types of expressions into
  97818. ** sqlite3_value objects.
  97819. **
  97820. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  97821. ** on register iReg. This is used when an equivalent integer value is
  97822. ** stored in place of an 8-byte floating point value in order to save
  97823. ** space.
  97824. */
  97825. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  97826. assert( pTab!=0 );
  97827. if( !pTab->pSelect ){
  97828. sqlite3_value *pValue = 0;
  97829. u8 enc = ENC(sqlite3VdbeDb(v));
  97830. Column *pCol = &pTab->aCol[i];
  97831. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  97832. assert( i<pTab->nCol );
  97833. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  97834. pCol->affinity, &pValue);
  97835. if( pValue ){
  97836. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  97837. }
  97838. #ifndef SQLITE_OMIT_FLOATING_POINT
  97839. if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  97840. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  97841. }
  97842. #endif
  97843. }
  97844. }
  97845. /*
  97846. ** Process an UPDATE statement.
  97847. **
  97848. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  97849. ** \_______/ \________/ \______/ \________________/
  97850. * onError pTabList pChanges pWhere
  97851. */
  97852. SQLITE_PRIVATE void sqlite3Update(
  97853. Parse *pParse, /* The parser context */
  97854. SrcList *pTabList, /* The table in which we should change things */
  97855. ExprList *pChanges, /* Things to be changed */
  97856. Expr *pWhere, /* The WHERE clause. May be null */
  97857. int onError /* How to handle constraint errors */
  97858. ){
  97859. int i, j; /* Loop counters */
  97860. Table *pTab; /* The table to be updated */
  97861. int addr = 0; /* VDBE instruction address of the start of the loop */
  97862. WhereInfo *pWInfo; /* Information about the WHERE clause */
  97863. Vdbe *v; /* The virtual database engine */
  97864. Index *pIdx; /* For looping over indices */
  97865. int nIdx; /* Number of indices that need updating */
  97866. int iCur; /* VDBE Cursor number of pTab */
  97867. sqlite3 *db; /* The database structure */
  97868. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  97869. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  97870. ** an expression for the i-th column of the table.
  97871. ** aXRef[i]==-1 if the i-th column is not changed. */
  97872. int chngRowid; /* True if the record number is being changed */
  97873. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  97874. int openAll = 0; /* True if all indices need to be opened */
  97875. AuthContext sContext; /* The authorization context */
  97876. NameContext sNC; /* The name-context to resolve expressions in */
  97877. int iDb; /* Database containing the table being updated */
  97878. int okOnePass; /* True for one-pass algorithm without the FIFO */
  97879. int hasFK; /* True if foreign key processing is required */
  97880. #ifndef SQLITE_OMIT_TRIGGER
  97881. int isView; /* True when updating a view (INSTEAD OF trigger) */
  97882. Trigger *pTrigger; /* List of triggers on pTab, if required */
  97883. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  97884. #endif
  97885. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  97886. /* Register Allocations */
  97887. int regRowCount = 0; /* A count of rows changed */
  97888. int regOldRowid; /* The old rowid */
  97889. int regNewRowid; /* The new rowid */
  97890. int regNew; /* Content of the NEW.* table in triggers */
  97891. int regOld = 0; /* Content of OLD.* table in triggers */
  97892. int regRowSet = 0; /* Rowset of rows to be updated */
  97893. memset(&sContext, 0, sizeof(sContext));
  97894. db = pParse->db;
  97895. if( pParse->nErr || db->mallocFailed ){
  97896. goto update_cleanup;
  97897. }
  97898. assert( pTabList->nSrc==1 );
  97899. /* Locate the table which we want to update.
  97900. */
  97901. pTab = sqlite3SrcListLookup(pParse, pTabList);
  97902. if( pTab==0 ) goto update_cleanup;
  97903. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  97904. /* Figure out if we have any triggers and if the table being
  97905. ** updated is a view.
  97906. */
  97907. #ifndef SQLITE_OMIT_TRIGGER
  97908. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  97909. isView = pTab->pSelect!=0;
  97910. assert( pTrigger || tmask==0 );
  97911. #else
  97912. # define pTrigger 0
  97913. # define isView 0
  97914. # define tmask 0
  97915. #endif
  97916. #ifdef SQLITE_OMIT_VIEW
  97917. # undef isView
  97918. # define isView 0
  97919. #endif
  97920. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  97921. goto update_cleanup;
  97922. }
  97923. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  97924. goto update_cleanup;
  97925. }
  97926. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  97927. if( aXRef==0 ) goto update_cleanup;
  97928. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  97929. /* Allocate a cursors for the main database table and for all indices.
  97930. ** The index cursors might not be used, but if they are used they
  97931. ** need to occur right after the database cursor. So go ahead and
  97932. ** allocate enough space, just in case.
  97933. */
  97934. pTabList->a[0].iCursor = iCur = pParse->nTab++;
  97935. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  97936. pParse->nTab++;
  97937. }
  97938. /* Initialize the name-context */
  97939. memset(&sNC, 0, sizeof(sNC));
  97940. sNC.pParse = pParse;
  97941. sNC.pSrcList = pTabList;
  97942. /* Resolve the column names in all the expressions of the
  97943. ** of the UPDATE statement. Also find the column index
  97944. ** for each column to be updated in the pChanges array. For each
  97945. ** column to be updated, make sure we have authorization to change
  97946. ** that column.
  97947. */
  97948. chngRowid = 0;
  97949. for(i=0; i<pChanges->nExpr; i++){
  97950. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  97951. goto update_cleanup;
  97952. }
  97953. for(j=0; j<pTab->nCol; j++){
  97954. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  97955. if( j==pTab->iPKey ){
  97956. chngRowid = 1;
  97957. pRowidExpr = pChanges->a[i].pExpr;
  97958. }
  97959. aXRef[j] = i;
  97960. break;
  97961. }
  97962. }
  97963. if( j>=pTab->nCol ){
  97964. if( sqlite3IsRowid(pChanges->a[i].zName) ){
  97965. j = -1;
  97966. chngRowid = 1;
  97967. pRowidExpr = pChanges->a[i].pExpr;
  97968. }else{
  97969. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  97970. pParse->checkSchema = 1;
  97971. goto update_cleanup;
  97972. }
  97973. }
  97974. #ifndef SQLITE_OMIT_AUTHORIZATION
  97975. {
  97976. int rc;
  97977. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  97978. j<0 ? "ROWID" : pTab->aCol[j].zName,
  97979. db->aDb[iDb].zName);
  97980. if( rc==SQLITE_DENY ){
  97981. goto update_cleanup;
  97982. }else if( rc==SQLITE_IGNORE ){
  97983. aXRef[j] = -1;
  97984. }
  97985. }
  97986. #endif
  97987. }
  97988. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
  97989. /* Allocate memory for the array aRegIdx[]. There is one entry in the
  97990. ** array for each index associated with table being updated. Fill in
  97991. ** the value with a register number for indices that are to be used
  97992. ** and with zero for unused indices.
  97993. */
  97994. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  97995. if( nIdx>0 ){
  97996. aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
  97997. if( aRegIdx==0 ) goto update_cleanup;
  97998. }
  97999. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  98000. int reg;
  98001. if( hasFK || chngRowid || pIdx->pPartIdxWhere ){
  98002. reg = ++pParse->nMem;
  98003. }else{
  98004. reg = 0;
  98005. for(i=0; i<pIdx->nColumn; i++){
  98006. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  98007. reg = ++pParse->nMem;
  98008. break;
  98009. }
  98010. }
  98011. }
  98012. aRegIdx[j] = reg;
  98013. }
  98014. /* Begin generating code. */
  98015. v = sqlite3GetVdbe(pParse);
  98016. if( v==0 ) goto update_cleanup;
  98017. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  98018. sqlite3BeginWriteOperation(pParse, 1, iDb);
  98019. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98020. /* Virtual tables must be handled separately */
  98021. if( IsVirtual(pTab) ){
  98022. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  98023. pWhere, onError);
  98024. pWhere = 0;
  98025. pTabList = 0;
  98026. goto update_cleanup;
  98027. }
  98028. #endif
  98029. /* Allocate required registers. */
  98030. regRowSet = ++pParse->nMem;
  98031. regOldRowid = regNewRowid = ++pParse->nMem;
  98032. if( pTrigger || hasFK ){
  98033. regOld = pParse->nMem + 1;
  98034. pParse->nMem += pTab->nCol;
  98035. }
  98036. if( chngRowid || pTrigger || hasFK ){
  98037. regNewRowid = ++pParse->nMem;
  98038. }
  98039. regNew = pParse->nMem + 1;
  98040. pParse->nMem += pTab->nCol;
  98041. /* Start the view context. */
  98042. if( isView ){
  98043. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  98044. }
  98045. /* If we are trying to update a view, realize that view into
  98046. ** a ephemeral table.
  98047. */
  98048. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  98049. if( isView ){
  98050. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  98051. }
  98052. #endif
  98053. /* Resolve the column names in all the expressions in the
  98054. ** WHERE clause.
  98055. */
  98056. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  98057. goto update_cleanup;
  98058. }
  98059. /* Begin the database scan
  98060. */
  98061. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  98062. pWInfo = sqlite3WhereBegin(
  98063. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
  98064. );
  98065. if( pWInfo==0 ) goto update_cleanup;
  98066. okOnePass = sqlite3WhereOkOnePass(pWInfo);
  98067. /* Remember the rowid of every item to be updated.
  98068. */
  98069. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
  98070. if( !okOnePass ){
  98071. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  98072. }
  98073. /* End the database scan loop.
  98074. */
  98075. sqlite3WhereEnd(pWInfo);
  98076. /* Initialize the count of updated rows
  98077. */
  98078. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  98079. regRowCount = ++pParse->nMem;
  98080. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  98081. }
  98082. if( !isView ){
  98083. /*
  98084. ** Open every index that needs updating. Note that if any
  98085. ** index could potentially invoke a REPLACE conflict resolution
  98086. ** action, then we need to open all indices because we might need
  98087. ** to be deleting some records.
  98088. */
  98089. if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
  98090. if( onError==OE_Replace ){
  98091. openAll = 1;
  98092. }else{
  98093. openAll = 0;
  98094. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  98095. if( pIdx->onError==OE_Replace ){
  98096. openAll = 1;
  98097. break;
  98098. }
  98099. }
  98100. }
  98101. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  98102. assert( aRegIdx );
  98103. if( openAll || aRegIdx[i]>0 ){
  98104. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  98105. sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
  98106. (char*)pKey, P4_KEYINFO_HANDOFF);
  98107. assert( pParse->nTab>iCur+i+1 );
  98108. }
  98109. }
  98110. }
  98111. /* Top of the update loop */
  98112. if( okOnePass ){
  98113. int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
  98114. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  98115. sqlite3VdbeJumpHere(v, a1);
  98116. }else{
  98117. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  98118. }
  98119. /* Make cursor iCur point to the record that is being updated. If
  98120. ** this record does not exist for some reason (deleted by a trigger,
  98121. ** for example, then jump to the next iteration of the RowSet loop. */
  98122. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  98123. /* If the record number will change, set register regNewRowid to
  98124. ** contain the new value. If the record number is not being modified,
  98125. ** then regNewRowid is the same register as regOldRowid, which is
  98126. ** already populated. */
  98127. assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
  98128. if( chngRowid ){
  98129. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  98130. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  98131. }
  98132. /* If there are triggers on this table, populate an array of registers
  98133. ** with the required old.* column data. */
  98134. if( hasFK || pTrigger ){
  98135. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  98136. oldmask |= sqlite3TriggerColmask(pParse,
  98137. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  98138. );
  98139. for(i=0; i<pTab->nCol; i++){
  98140. if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
  98141. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
  98142. }else{
  98143. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  98144. }
  98145. }
  98146. if( chngRowid==0 ){
  98147. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  98148. }
  98149. }
  98150. /* Populate the array of registers beginning at regNew with the new
  98151. ** row data. This array is used to check constaints, create the new
  98152. ** table and index records, and as the values for any new.* references
  98153. ** made by triggers.
  98154. **
  98155. ** If there are one or more BEFORE triggers, then do not populate the
  98156. ** registers associated with columns that are (a) not modified by
  98157. ** this UPDATE statement and (b) not accessed by new.* references. The
  98158. ** values for registers not modified by the UPDATE must be reloaded from
  98159. ** the database after the BEFORE triggers are fired anyway (as the trigger
  98160. ** may have modified them). So not loading those that are not going to
  98161. ** be used eliminates some redundant opcodes.
  98162. */
  98163. newmask = sqlite3TriggerColmask(
  98164. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  98165. );
  98166. sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
  98167. for(i=0; i<pTab->nCol; i++){
  98168. if( i==pTab->iPKey ){
  98169. /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
  98170. }else{
  98171. j = aXRef[i];
  98172. if( j>=0 ){
  98173. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  98174. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
  98175. /* This branch loads the value of a column that will not be changed
  98176. ** into a register. This is done if there are no BEFORE triggers, or
  98177. ** if there are one or more BEFORE triggers that use this value via
  98178. ** a new.* reference in a trigger program.
  98179. */
  98180. testcase( i==31 );
  98181. testcase( i==32 );
  98182. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  98183. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  98184. }
  98185. }
  98186. }
  98187. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  98188. ** verified. One could argue that this is wrong.
  98189. */
  98190. if( tmask&TRIGGER_BEFORE ){
  98191. sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
  98192. sqlite3TableAffinityStr(v, pTab);
  98193. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  98194. TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
  98195. /* The row-trigger may have deleted the row being updated. In this
  98196. ** case, jump to the next row. No updates or AFTER triggers are
  98197. ** required. This behavior - what happens when the row being updated
  98198. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  98199. ** documentation.
  98200. */
  98201. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  98202. /* If it did not delete it, the row-trigger may still have modified
  98203. ** some of the columns of the row being updated. Load the values for
  98204. ** all columns not modified by the update statement into their
  98205. ** registers in case this has happened.
  98206. */
  98207. for(i=0; i<pTab->nCol; i++){
  98208. if( aXRef[i]<0 && i!=pTab->iPKey ){
  98209. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  98210. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  98211. }
  98212. }
  98213. }
  98214. if( !isView ){
  98215. int j1; /* Address of jump instruction */
  98216. /* Do constraint checks. */
  98217. sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
  98218. aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
  98219. /* Do FK constraint checks. */
  98220. if( hasFK ){
  98221. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngRowid);
  98222. }
  98223. /* Delete the index entries associated with the current record. */
  98224. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
  98225. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  98226. /* If changing the record number, delete the old record. */
  98227. if( hasFK || chngRowid ){
  98228. sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
  98229. }
  98230. sqlite3VdbeJumpHere(v, j1);
  98231. if( hasFK ){
  98232. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngRowid);
  98233. }
  98234. /* Insert the new index entries and the new record. */
  98235. sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
  98236. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  98237. ** handle rows (possibly in other tables) that refer via a foreign key
  98238. ** to the row just updated. */
  98239. if( hasFK ){
  98240. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngRowid);
  98241. }
  98242. }
  98243. /* Increment the row counter
  98244. */
  98245. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  98246. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  98247. }
  98248. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  98249. TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
  98250. /* Repeat the above with the next record to be updated, until
  98251. ** all record selected by the WHERE clause have been updated.
  98252. */
  98253. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  98254. sqlite3VdbeJumpHere(v, addr);
  98255. /* Close all tables */
  98256. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  98257. assert( aRegIdx );
  98258. if( openAll || aRegIdx[i]>0 ){
  98259. sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
  98260. }
  98261. }
  98262. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  98263. /* Update the sqlite_sequence table by storing the content of the
  98264. ** maximum rowid counter values recorded while inserting into
  98265. ** autoincrement tables.
  98266. */
  98267. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  98268. sqlite3AutoincrementEnd(pParse);
  98269. }
  98270. /*
  98271. ** Return the number of rows that were changed. If this routine is
  98272. ** generating code because of a call to sqlite3NestedParse(), do not
  98273. ** invoke the callback function.
  98274. */
  98275. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  98276. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  98277. sqlite3VdbeSetNumCols(v, 1);
  98278. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  98279. }
  98280. update_cleanup:
  98281. sqlite3AuthContextPop(&sContext);
  98282. sqlite3DbFree(db, aRegIdx);
  98283. sqlite3DbFree(db, aXRef);
  98284. sqlite3SrcListDelete(db, pTabList);
  98285. sqlite3ExprListDelete(db, pChanges);
  98286. sqlite3ExprDelete(db, pWhere);
  98287. return;
  98288. }
  98289. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  98290. ** thely may interfere with compilation of other functions in this file
  98291. ** (or in another file, if this file becomes part of the amalgamation). */
  98292. #ifdef isView
  98293. #undef isView
  98294. #endif
  98295. #ifdef pTrigger
  98296. #undef pTrigger
  98297. #endif
  98298. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98299. /*
  98300. ** Generate code for an UPDATE of a virtual table.
  98301. **
  98302. ** The strategy is that we create an ephemerial table that contains
  98303. ** for each row to be changed:
  98304. **
  98305. ** (A) The original rowid of that row.
  98306. ** (B) The revised rowid for the row. (note1)
  98307. ** (C) The content of every column in the row.
  98308. **
  98309. ** Then we loop over this ephemeral table and for each row in
  98310. ** the ephermeral table call VUpdate.
  98311. **
  98312. ** When finished, drop the ephemeral table.
  98313. **
  98314. ** (note1) Actually, if we know in advance that (A) is always the same
  98315. ** as (B) we only store (A), then duplicate (A) when pulling
  98316. ** it out of the ephemeral table before calling VUpdate.
  98317. */
  98318. static void updateVirtualTable(
  98319. Parse *pParse, /* The parsing context */
  98320. SrcList *pSrc, /* The virtual table to be modified */
  98321. Table *pTab, /* The virtual table */
  98322. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  98323. Expr *pRowid, /* Expression used to recompute the rowid */
  98324. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  98325. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  98326. int onError /* ON CONFLICT strategy */
  98327. ){
  98328. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  98329. ExprList *pEList = 0; /* The result set of the SELECT statement */
  98330. Select *pSelect = 0; /* The SELECT statement */
  98331. Expr *pExpr; /* Temporary expression */
  98332. int ephemTab; /* Table holding the result of the SELECT */
  98333. int i; /* Loop counter */
  98334. int addr; /* Address of top of loop */
  98335. int iReg; /* First register in set passed to OP_VUpdate */
  98336. sqlite3 *db = pParse->db; /* Database connection */
  98337. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  98338. SelectDest dest;
  98339. /* Construct the SELECT statement that will find the new values for
  98340. ** all updated rows.
  98341. */
  98342. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  98343. if( pRowid ){
  98344. pEList = sqlite3ExprListAppend(pParse, pEList,
  98345. sqlite3ExprDup(db, pRowid, 0));
  98346. }
  98347. assert( pTab->iPKey<0 );
  98348. for(i=0; i<pTab->nCol; i++){
  98349. if( aXRef[i]>=0 ){
  98350. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  98351. }else{
  98352. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  98353. }
  98354. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  98355. }
  98356. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  98357. /* Create the ephemeral table into which the update results will
  98358. ** be stored.
  98359. */
  98360. assert( v );
  98361. ephemTab = pParse->nTab++;
  98362. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  98363. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  98364. /* fill the ephemeral table
  98365. */
  98366. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  98367. sqlite3Select(pParse, pSelect, &dest);
  98368. /* Generate code to scan the ephemeral table and call VUpdate. */
  98369. iReg = ++pParse->nMem;
  98370. pParse->nMem += pTab->nCol+1;
  98371. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  98372. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  98373. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  98374. for(i=0; i<pTab->nCol; i++){
  98375. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  98376. }
  98377. sqlite3VtabMakeWritable(pParse, pTab);
  98378. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  98379. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  98380. sqlite3MayAbort(pParse);
  98381. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
  98382. sqlite3VdbeJumpHere(v, addr);
  98383. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  98384. /* Cleanup */
  98385. sqlite3SelectDelete(db, pSelect);
  98386. }
  98387. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  98388. /************** End of update.c **********************************************/
  98389. /************** Begin file vacuum.c ******************************************/
  98390. /*
  98391. ** 2003 April 6
  98392. **
  98393. ** The author disclaims copyright to this source code. In place of
  98394. ** a legal notice, here is a blessing:
  98395. **
  98396. ** May you do good and not evil.
  98397. ** May you find forgiveness for yourself and forgive others.
  98398. ** May you share freely, never taking more than you give.
  98399. **
  98400. *************************************************************************
  98401. ** This file contains code used to implement the VACUUM command.
  98402. **
  98403. ** Most of the code in this file may be omitted by defining the
  98404. ** SQLITE_OMIT_VACUUM macro.
  98405. */
  98406. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  98407. /*
  98408. ** Finalize a prepared statement. If there was an error, store the
  98409. ** text of the error message in *pzErrMsg. Return the result code.
  98410. */
  98411. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  98412. int rc;
  98413. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  98414. if( rc ){
  98415. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  98416. }
  98417. return rc;
  98418. }
  98419. /*
  98420. ** Execute zSql on database db. Return an error code.
  98421. */
  98422. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  98423. sqlite3_stmt *pStmt;
  98424. VVA_ONLY( int rc; )
  98425. if( !zSql ){
  98426. return SQLITE_NOMEM;
  98427. }
  98428. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  98429. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  98430. return sqlite3_errcode(db);
  98431. }
  98432. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  98433. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  98434. return vacuumFinalize(db, pStmt, pzErrMsg);
  98435. }
  98436. /*
  98437. ** Execute zSql on database db. The statement returns exactly
  98438. ** one column. Execute this as SQL on the same database.
  98439. */
  98440. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  98441. sqlite3_stmt *pStmt;
  98442. int rc;
  98443. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  98444. if( rc!=SQLITE_OK ) return rc;
  98445. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  98446. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  98447. if( rc!=SQLITE_OK ){
  98448. vacuumFinalize(db, pStmt, pzErrMsg);
  98449. return rc;
  98450. }
  98451. }
  98452. return vacuumFinalize(db, pStmt, pzErrMsg);
  98453. }
  98454. /*
  98455. ** The VACUUM command is used to clean up the database,
  98456. ** collapse free space, etc. It is modelled after the VACUUM command
  98457. ** in PostgreSQL. The VACUUM command works as follows:
  98458. **
  98459. ** (1) Create a new transient database file
  98460. ** (2) Copy all content from the database being vacuumed into
  98461. ** the new transient database file
  98462. ** (3) Copy content from the transient database back into the
  98463. ** original database.
  98464. **
  98465. ** The transient database requires temporary disk space approximately
  98466. ** equal to the size of the original database. The copy operation of
  98467. ** step (3) requires additional temporary disk space approximately equal
  98468. ** to the size of the original database for the rollback journal.
  98469. ** Hence, temporary disk space that is approximately 2x the size of the
  98470. ** orginal database is required. Every page of the database is written
  98471. ** approximately 3 times: Once for step (2) and twice for step (3).
  98472. ** Two writes per page are required in step (3) because the original
  98473. ** database content must be written into the rollback journal prior to
  98474. ** overwriting the database with the vacuumed content.
  98475. **
  98476. ** Only 1x temporary space and only 1x writes would be required if
  98477. ** the copy of step (3) were replace by deleting the original database
  98478. ** and renaming the transient database as the original. But that will
  98479. ** not work if other processes are attached to the original database.
  98480. ** And a power loss in between deleting the original and renaming the
  98481. ** transient would cause the database file to appear to be deleted
  98482. ** following reboot.
  98483. */
  98484. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  98485. Vdbe *v = sqlite3GetVdbe(pParse);
  98486. if( v ){
  98487. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  98488. sqlite3VdbeUsesBtree(v, 0);
  98489. }
  98490. return;
  98491. }
  98492. /*
  98493. ** This routine implements the OP_Vacuum opcode of the VDBE.
  98494. */
  98495. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  98496. int rc = SQLITE_OK; /* Return code from service routines */
  98497. Btree *pMain; /* The database being vacuumed */
  98498. Btree *pTemp; /* The temporary database we vacuum into */
  98499. char *zSql = 0; /* SQL statements */
  98500. int saved_flags; /* Saved value of the db->flags */
  98501. int saved_nChange; /* Saved value of db->nChange */
  98502. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  98503. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  98504. Db *pDb = 0; /* Database to detach at end of vacuum */
  98505. int isMemDb; /* True if vacuuming a :memory: database */
  98506. int nRes; /* Bytes of reserved space at the end of each page */
  98507. int nDb; /* Number of attached databases */
  98508. if( !db->autoCommit ){
  98509. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  98510. return SQLITE_ERROR;
  98511. }
  98512. if( db->nVdbeActive>1 ){
  98513. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  98514. return SQLITE_ERROR;
  98515. }
  98516. /* Save the current value of the database flags so that it can be
  98517. ** restored before returning. Then set the writable-schema flag, and
  98518. ** disable CHECK and foreign key constraints. */
  98519. saved_flags = db->flags;
  98520. saved_nChange = db->nChange;
  98521. saved_nTotalChange = db->nTotalChange;
  98522. saved_xTrace = db->xTrace;
  98523. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  98524. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  98525. db->xTrace = 0;
  98526. pMain = db->aDb[0].pBt;
  98527. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  98528. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  98529. ** can be set to 'off' for this file, as it is not recovered if a crash
  98530. ** occurs anyway. The integrity of the database is maintained by a
  98531. ** (possibly synchronous) transaction opened on the main database before
  98532. ** sqlite3BtreeCopyFile() is called.
  98533. **
  98534. ** An optimisation would be to use a non-journaled pager.
  98535. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  98536. ** that actually made the VACUUM run slower. Very little journalling
  98537. ** actually occurs when doing a vacuum since the vacuum_db is initially
  98538. ** empty. Only the journal header is written. Apparently it takes more
  98539. ** time to parse and run the PRAGMA to turn journalling off than it does
  98540. ** to write the journal header file.
  98541. */
  98542. nDb = db->nDb;
  98543. if( sqlite3TempInMemory(db) ){
  98544. zSql = "ATTACH ':memory:' AS vacuum_db;";
  98545. }else{
  98546. zSql = "ATTACH '' AS vacuum_db;";
  98547. }
  98548. rc = execSql(db, pzErrMsg, zSql);
  98549. if( db->nDb>nDb ){
  98550. pDb = &db->aDb[db->nDb-1];
  98551. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  98552. }
  98553. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98554. pTemp = db->aDb[db->nDb-1].pBt;
  98555. /* The call to execSql() to attach the temp database has left the file
  98556. ** locked (as there was more than one active statement when the transaction
  98557. ** to read the schema was concluded. Unlock it here so that this doesn't
  98558. ** cause problems for the call to BtreeSetPageSize() below. */
  98559. sqlite3BtreeCommit(pTemp);
  98560. nRes = sqlite3BtreeGetReserve(pMain);
  98561. /* A VACUUM cannot change the pagesize of an encrypted database. */
  98562. #ifdef SQLITE_HAS_CODEC
  98563. if( db->nextPagesize ){
  98564. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  98565. int nKey;
  98566. char *zKey;
  98567. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  98568. if( nKey ) db->nextPagesize = 0;
  98569. }
  98570. #endif
  98571. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  98572. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98573. /* Begin a transaction and take an exclusive lock on the main database
  98574. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  98575. ** to ensure that we do not try to change the page-size on a WAL database.
  98576. */
  98577. rc = execSql(db, pzErrMsg, "BEGIN;");
  98578. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98579. rc = sqlite3BtreeBeginTrans(pMain, 2);
  98580. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98581. /* Do not attempt to change the page size for a WAL database */
  98582. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  98583. ==PAGER_JOURNALMODE_WAL ){
  98584. db->nextPagesize = 0;
  98585. }
  98586. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  98587. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  98588. || NEVER(db->mallocFailed)
  98589. ){
  98590. rc = SQLITE_NOMEM;
  98591. goto end_of_vacuum;
  98592. }
  98593. #ifndef SQLITE_OMIT_AUTOVACUUM
  98594. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  98595. sqlite3BtreeGetAutoVacuum(pMain));
  98596. #endif
  98597. /* Query the schema of the main database. Create a mirror schema
  98598. ** in the temporary database.
  98599. */
  98600. rc = execExecSql(db, pzErrMsg,
  98601. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  98602. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  98603. " AND rootpage>0"
  98604. );
  98605. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98606. rc = execExecSql(db, pzErrMsg,
  98607. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  98608. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  98609. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98610. rc = execExecSql(db, pzErrMsg,
  98611. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  98612. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  98613. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98614. /* Loop through the tables in the main database. For each, do
  98615. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  98616. ** the contents to the temporary database.
  98617. */
  98618. rc = execExecSql(db, pzErrMsg,
  98619. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  98620. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  98621. "FROM main.sqlite_master "
  98622. "WHERE type = 'table' AND name!='sqlite_sequence' "
  98623. " AND rootpage>0"
  98624. );
  98625. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98626. /* Copy over the sequence table
  98627. */
  98628. rc = execExecSql(db, pzErrMsg,
  98629. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  98630. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  98631. );
  98632. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98633. rc = execExecSql(db, pzErrMsg,
  98634. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  98635. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  98636. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  98637. );
  98638. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98639. /* Copy the triggers, views, and virtual tables from the main database
  98640. ** over to the temporary database. None of these objects has any
  98641. ** associated storage, so all we have to do is copy their entries
  98642. ** from the SQLITE_MASTER table.
  98643. */
  98644. rc = execSql(db, pzErrMsg,
  98645. "INSERT INTO vacuum_db.sqlite_master "
  98646. " SELECT type, name, tbl_name, rootpage, sql"
  98647. " FROM main.sqlite_master"
  98648. " WHERE type='view' OR type='trigger'"
  98649. " OR (type='table' AND rootpage=0)"
  98650. );
  98651. if( rc ) goto end_of_vacuum;
  98652. /* At this point, there is a write transaction open on both the
  98653. ** vacuum database and the main database. Assuming no error occurs,
  98654. ** both transactions are closed by this block - the main database
  98655. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  98656. ** call to sqlite3BtreeCommit().
  98657. */
  98658. {
  98659. u32 meta;
  98660. int i;
  98661. /* This array determines which meta meta values are preserved in the
  98662. ** vacuum. Even entries are the meta value number and odd entries
  98663. ** are an increment to apply to the meta value after the vacuum.
  98664. ** The increment is used to increase the schema cookie so that other
  98665. ** connections to the same database will know to reread the schema.
  98666. */
  98667. static const unsigned char aCopy[] = {
  98668. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  98669. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  98670. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  98671. BTREE_USER_VERSION, 0, /* Preserve the user version */
  98672. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  98673. };
  98674. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  98675. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  98676. /* Copy Btree meta values */
  98677. for(i=0; i<ArraySize(aCopy); i+=2){
  98678. /* GetMeta() and UpdateMeta() cannot fail in this context because
  98679. ** we already have page 1 loaded into cache and marked dirty. */
  98680. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  98681. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  98682. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  98683. }
  98684. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  98685. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98686. rc = sqlite3BtreeCommit(pTemp);
  98687. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  98688. #ifndef SQLITE_OMIT_AUTOVACUUM
  98689. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  98690. #endif
  98691. }
  98692. assert( rc==SQLITE_OK );
  98693. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  98694. end_of_vacuum:
  98695. /* Restore the original value of db->flags */
  98696. db->flags = saved_flags;
  98697. db->nChange = saved_nChange;
  98698. db->nTotalChange = saved_nTotalChange;
  98699. db->xTrace = saved_xTrace;
  98700. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  98701. /* Currently there is an SQL level transaction open on the vacuum
  98702. ** database. No locks are held on any other files (since the main file
  98703. ** was committed at the btree level). So it safe to end the transaction
  98704. ** by manually setting the autoCommit flag to true and detaching the
  98705. ** vacuum database. The vacuum_db journal file is deleted when the pager
  98706. ** is closed by the DETACH.
  98707. */
  98708. db->autoCommit = 1;
  98709. if( pDb ){
  98710. sqlite3BtreeClose(pDb->pBt);
  98711. pDb->pBt = 0;
  98712. pDb->pSchema = 0;
  98713. }
  98714. /* This both clears the schemas and reduces the size of the db->aDb[]
  98715. ** array. */
  98716. sqlite3ResetAllSchemasOfConnection(db);
  98717. return rc;
  98718. }
  98719. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  98720. /************** End of vacuum.c **********************************************/
  98721. /************** Begin file vtab.c ********************************************/
  98722. /*
  98723. ** 2006 June 10
  98724. **
  98725. ** The author disclaims copyright to this source code. In place of
  98726. ** a legal notice, here is a blessing:
  98727. **
  98728. ** May you do good and not evil.
  98729. ** May you find forgiveness for yourself and forgive others.
  98730. ** May you share freely, never taking more than you give.
  98731. **
  98732. *************************************************************************
  98733. ** This file contains code used to help implement virtual tables.
  98734. */
  98735. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98736. /*
  98737. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  98738. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  98739. ** this struct allocated on the stack. It is used by the implementation of
  98740. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  98741. ** are invoked only from within xCreate and xConnect methods.
  98742. */
  98743. struct VtabCtx {
  98744. VTable *pVTable; /* The virtual table being constructed */
  98745. Table *pTab; /* The Table object to which the virtual table belongs */
  98746. };
  98747. /*
  98748. ** The actual function that does the work of creating a new module.
  98749. ** This function implements the sqlite3_create_module() and
  98750. ** sqlite3_create_module_v2() interfaces.
  98751. */
  98752. static int createModule(
  98753. sqlite3 *db, /* Database in which module is registered */
  98754. const char *zName, /* Name assigned to this module */
  98755. const sqlite3_module *pModule, /* The definition of the module */
  98756. void *pAux, /* Context pointer for xCreate/xConnect */
  98757. void (*xDestroy)(void *) /* Module destructor function */
  98758. ){
  98759. int rc = SQLITE_OK;
  98760. int nName;
  98761. sqlite3_mutex_enter(db->mutex);
  98762. nName = sqlite3Strlen30(zName);
  98763. if( sqlite3HashFind(&db->aModule, zName, nName) ){
  98764. rc = SQLITE_MISUSE_BKPT;
  98765. }else{
  98766. Module *pMod;
  98767. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  98768. if( pMod ){
  98769. Module *pDel;
  98770. char *zCopy = (char *)(&pMod[1]);
  98771. memcpy(zCopy, zName, nName+1);
  98772. pMod->zName = zCopy;
  98773. pMod->pModule = pModule;
  98774. pMod->pAux = pAux;
  98775. pMod->xDestroy = xDestroy;
  98776. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
  98777. assert( pDel==0 || pDel==pMod );
  98778. if( pDel ){
  98779. db->mallocFailed = 1;
  98780. sqlite3DbFree(db, pDel);
  98781. }
  98782. }
  98783. }
  98784. rc = sqlite3ApiExit(db, rc);
  98785. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  98786. sqlite3_mutex_leave(db->mutex);
  98787. return rc;
  98788. }
  98789. /*
  98790. ** External API function used to create a new virtual-table module.
  98791. */
  98792. SQLITE_API int sqlite3_create_module(
  98793. sqlite3 *db, /* Database in which module is registered */
  98794. const char *zName, /* Name assigned to this module */
  98795. const sqlite3_module *pModule, /* The definition of the module */
  98796. void *pAux /* Context pointer for xCreate/xConnect */
  98797. ){
  98798. return createModule(db, zName, pModule, pAux, 0);
  98799. }
  98800. /*
  98801. ** External API function used to create a new virtual-table module.
  98802. */
  98803. SQLITE_API int sqlite3_create_module_v2(
  98804. sqlite3 *db, /* Database in which module is registered */
  98805. const char *zName, /* Name assigned to this module */
  98806. const sqlite3_module *pModule, /* The definition of the module */
  98807. void *pAux, /* Context pointer for xCreate/xConnect */
  98808. void (*xDestroy)(void *) /* Module destructor function */
  98809. ){
  98810. return createModule(db, zName, pModule, pAux, xDestroy);
  98811. }
  98812. /*
  98813. ** Lock the virtual table so that it cannot be disconnected.
  98814. ** Locks nest. Every lock should have a corresponding unlock.
  98815. ** If an unlock is omitted, resources leaks will occur.
  98816. **
  98817. ** If a disconnect is attempted while a virtual table is locked,
  98818. ** the disconnect is deferred until all locks have been removed.
  98819. */
  98820. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  98821. pVTab->nRef++;
  98822. }
  98823. /*
  98824. ** pTab is a pointer to a Table structure representing a virtual-table.
  98825. ** Return a pointer to the VTable object used by connection db to access
  98826. ** this virtual-table, if one has been created, or NULL otherwise.
  98827. */
  98828. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  98829. VTable *pVtab;
  98830. assert( IsVirtual(pTab) );
  98831. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  98832. return pVtab;
  98833. }
  98834. /*
  98835. ** Decrement the ref-count on a virtual table object. When the ref-count
  98836. ** reaches zero, call the xDisconnect() method to delete the object.
  98837. */
  98838. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  98839. sqlite3 *db = pVTab->db;
  98840. assert( db );
  98841. assert( pVTab->nRef>0 );
  98842. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  98843. pVTab->nRef--;
  98844. if( pVTab->nRef==0 ){
  98845. sqlite3_vtab *p = pVTab->pVtab;
  98846. if( p ){
  98847. p->pModule->xDisconnect(p);
  98848. }
  98849. sqlite3DbFree(db, pVTab);
  98850. }
  98851. }
  98852. /*
  98853. ** Table p is a virtual table. This function moves all elements in the
  98854. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  98855. ** database connections to be disconnected at the next opportunity.
  98856. ** Except, if argument db is not NULL, then the entry associated with
  98857. ** connection db is left in the p->pVTable list.
  98858. */
  98859. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  98860. VTable *pRet = 0;
  98861. VTable *pVTable = p->pVTable;
  98862. p->pVTable = 0;
  98863. /* Assert that the mutex (if any) associated with the BtShared database
  98864. ** that contains table p is held by the caller. See header comments
  98865. ** above function sqlite3VtabUnlockList() for an explanation of why
  98866. ** this makes it safe to access the sqlite3.pDisconnect list of any
  98867. ** database connection that may have an entry in the p->pVTable list.
  98868. */
  98869. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  98870. while( pVTable ){
  98871. sqlite3 *db2 = pVTable->db;
  98872. VTable *pNext = pVTable->pNext;
  98873. assert( db2 );
  98874. if( db2==db ){
  98875. pRet = pVTable;
  98876. p->pVTable = pRet;
  98877. pRet->pNext = 0;
  98878. }else{
  98879. pVTable->pNext = db2->pDisconnect;
  98880. db2->pDisconnect = pVTable;
  98881. }
  98882. pVTable = pNext;
  98883. }
  98884. assert( !db || pRet );
  98885. return pRet;
  98886. }
  98887. /*
  98888. ** Table *p is a virtual table. This function removes the VTable object
  98889. ** for table *p associated with database connection db from the linked
  98890. ** list in p->pVTab. It also decrements the VTable ref count. This is
  98891. ** used when closing database connection db to free all of its VTable
  98892. ** objects without disturbing the rest of the Schema object (which may
  98893. ** be being used by other shared-cache connections).
  98894. */
  98895. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  98896. VTable **ppVTab;
  98897. assert( IsVirtual(p) );
  98898. assert( sqlite3BtreeHoldsAllMutexes(db) );
  98899. assert( sqlite3_mutex_held(db->mutex) );
  98900. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  98901. if( (*ppVTab)->db==db ){
  98902. VTable *pVTab = *ppVTab;
  98903. *ppVTab = pVTab->pNext;
  98904. sqlite3VtabUnlock(pVTab);
  98905. break;
  98906. }
  98907. }
  98908. }
  98909. /*
  98910. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  98911. **
  98912. ** This function may only be called when the mutexes associated with all
  98913. ** shared b-tree databases opened using connection db are held by the
  98914. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  98915. ** sqlite3.pDisconnect list is accessed only as follows:
  98916. **
  98917. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  98918. ** associated with the database handle itself must be held.
  98919. **
  98920. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  98921. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  98922. ** associated with the database the virtual table is stored in is held
  98923. ** or, if the virtual table is stored in a non-sharable database, then
  98924. ** the database handle mutex is held.
  98925. **
  98926. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  98927. ** by multiple threads. It is thread-safe.
  98928. */
  98929. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  98930. VTable *p = db->pDisconnect;
  98931. db->pDisconnect = 0;
  98932. assert( sqlite3BtreeHoldsAllMutexes(db) );
  98933. assert( sqlite3_mutex_held(db->mutex) );
  98934. if( p ){
  98935. sqlite3ExpirePreparedStatements(db);
  98936. do {
  98937. VTable *pNext = p->pNext;
  98938. sqlite3VtabUnlock(p);
  98939. p = pNext;
  98940. }while( p );
  98941. }
  98942. }
  98943. /*
  98944. ** Clear any and all virtual-table information from the Table record.
  98945. ** This routine is called, for example, just before deleting the Table
  98946. ** record.
  98947. **
  98948. ** Since it is a virtual-table, the Table structure contains a pointer
  98949. ** to the head of a linked list of VTable structures. Each VTable
  98950. ** structure is associated with a single sqlite3* user of the schema.
  98951. ** The reference count of the VTable structure associated with database
  98952. ** connection db is decremented immediately (which may lead to the
  98953. ** structure being xDisconnected and free). Any other VTable structures
  98954. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  98955. ** database connection.
  98956. */
  98957. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  98958. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  98959. if( p->azModuleArg ){
  98960. int i;
  98961. for(i=0; i<p->nModuleArg; i++){
  98962. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  98963. }
  98964. sqlite3DbFree(db, p->azModuleArg);
  98965. }
  98966. }
  98967. /*
  98968. ** Add a new module argument to pTable->azModuleArg[].
  98969. ** The string is not copied - the pointer is stored. The
  98970. ** string will be freed automatically when the table is
  98971. ** deleted.
  98972. */
  98973. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  98974. int i = pTable->nModuleArg++;
  98975. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  98976. char **azModuleArg;
  98977. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  98978. if( azModuleArg==0 ){
  98979. int j;
  98980. for(j=0; j<i; j++){
  98981. sqlite3DbFree(db, pTable->azModuleArg[j]);
  98982. }
  98983. sqlite3DbFree(db, zArg);
  98984. sqlite3DbFree(db, pTable->azModuleArg);
  98985. pTable->nModuleArg = 0;
  98986. }else{
  98987. azModuleArg[i] = zArg;
  98988. azModuleArg[i+1] = 0;
  98989. }
  98990. pTable->azModuleArg = azModuleArg;
  98991. }
  98992. /*
  98993. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  98994. ** statement. The module name has been parsed, but the optional list
  98995. ** of parameters that follow the module name are still pending.
  98996. */
  98997. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  98998. Parse *pParse, /* Parsing context */
  98999. Token *pName1, /* Name of new table, or database name */
  99000. Token *pName2, /* Name of new table or NULL */
  99001. Token *pModuleName, /* Name of the module for the virtual table */
  99002. int ifNotExists /* No error if the table already exists */
  99003. ){
  99004. int iDb; /* The database the table is being created in */
  99005. Table *pTable; /* The new virtual table */
  99006. sqlite3 *db; /* Database connection */
  99007. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  99008. pTable = pParse->pNewTable;
  99009. if( pTable==0 ) return;
  99010. assert( 0==pTable->pIndex );
  99011. db = pParse->db;
  99012. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  99013. assert( iDb>=0 );
  99014. pTable->tabFlags |= TF_Virtual;
  99015. pTable->nModuleArg = 0;
  99016. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  99017. addModuleArgument(db, pTable, 0);
  99018. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  99019. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  99020. #ifndef SQLITE_OMIT_AUTHORIZATION
  99021. /* Creating a virtual table invokes the authorization callback twice.
  99022. ** The first invocation, to obtain permission to INSERT a row into the
  99023. ** sqlite_master table, has already been made by sqlite3StartTable().
  99024. ** The second call, to obtain permission to create the table, is made now.
  99025. */
  99026. if( pTable->azModuleArg ){
  99027. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  99028. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  99029. }
  99030. #endif
  99031. }
  99032. /*
  99033. ** This routine takes the module argument that has been accumulating
  99034. ** in pParse->zArg[] and appends it to the list of arguments on the
  99035. ** virtual table currently under construction in pParse->pTable.
  99036. */
  99037. static void addArgumentToVtab(Parse *pParse){
  99038. if( pParse->sArg.z && pParse->pNewTable ){
  99039. const char *z = (const char*)pParse->sArg.z;
  99040. int n = pParse->sArg.n;
  99041. sqlite3 *db = pParse->db;
  99042. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  99043. }
  99044. }
  99045. /*
  99046. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  99047. ** has been completely parsed.
  99048. */
  99049. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  99050. Table *pTab = pParse->pNewTable; /* The table being constructed */
  99051. sqlite3 *db = pParse->db; /* The database connection */
  99052. if( pTab==0 ) return;
  99053. addArgumentToVtab(pParse);
  99054. pParse->sArg.z = 0;
  99055. if( pTab->nModuleArg<1 ) return;
  99056. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  99057. ** first time (in other words if the virtual table is actually being
  99058. ** created now instead of just being read out of sqlite_master) then
  99059. ** do additional initialization work and store the statement text
  99060. ** in the sqlite_master table.
  99061. */
  99062. if( !db->init.busy ){
  99063. char *zStmt;
  99064. char *zWhere;
  99065. int iDb;
  99066. Vdbe *v;
  99067. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  99068. if( pEnd ){
  99069. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  99070. }
  99071. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  99072. /* A slot for the record has already been allocated in the
  99073. ** SQLITE_MASTER table. We just need to update that slot with all
  99074. ** the information we've collected.
  99075. **
  99076. ** The VM register number pParse->regRowid holds the rowid of an
  99077. ** entry in the sqlite_master table tht was created for this vtab
  99078. ** by sqlite3StartTable().
  99079. */
  99080. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  99081. sqlite3NestedParse(pParse,
  99082. "UPDATE %Q.%s "
  99083. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  99084. "WHERE rowid=#%d",
  99085. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  99086. pTab->zName,
  99087. pTab->zName,
  99088. zStmt,
  99089. pParse->regRowid
  99090. );
  99091. sqlite3DbFree(db, zStmt);
  99092. v = sqlite3GetVdbe(pParse);
  99093. sqlite3ChangeCookie(pParse, iDb);
  99094. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  99095. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  99096. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  99097. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  99098. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  99099. }
  99100. /* If we are rereading the sqlite_master table create the in-memory
  99101. ** record of the table. The xConnect() method is not called until
  99102. ** the first time the virtual table is used in an SQL statement. This
  99103. ** allows a schema that contains virtual tables to be loaded before
  99104. ** the required virtual table implementations are registered. */
  99105. else {
  99106. Table *pOld;
  99107. Schema *pSchema = pTab->pSchema;
  99108. const char *zName = pTab->zName;
  99109. int nName = sqlite3Strlen30(zName);
  99110. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  99111. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
  99112. if( pOld ){
  99113. db->mallocFailed = 1;
  99114. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  99115. return;
  99116. }
  99117. pParse->pNewTable = 0;
  99118. }
  99119. }
  99120. /*
  99121. ** The parser calls this routine when it sees the first token
  99122. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  99123. */
  99124. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  99125. addArgumentToVtab(pParse);
  99126. pParse->sArg.z = 0;
  99127. pParse->sArg.n = 0;
  99128. }
  99129. /*
  99130. ** The parser calls this routine for each token after the first token
  99131. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  99132. */
  99133. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  99134. Token *pArg = &pParse->sArg;
  99135. if( pArg->z==0 ){
  99136. pArg->z = p->z;
  99137. pArg->n = p->n;
  99138. }else{
  99139. assert(pArg->z < p->z);
  99140. pArg->n = (int)(&p->z[p->n] - pArg->z);
  99141. }
  99142. }
  99143. /*
  99144. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  99145. ** pointer to the function to invoke is passed as the fourth parameter
  99146. ** to this procedure.
  99147. */
  99148. static int vtabCallConstructor(
  99149. sqlite3 *db,
  99150. Table *pTab,
  99151. Module *pMod,
  99152. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  99153. char **pzErr
  99154. ){
  99155. VtabCtx sCtx, *pPriorCtx;
  99156. VTable *pVTable;
  99157. int rc;
  99158. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  99159. int nArg = pTab->nModuleArg;
  99160. char *zErr = 0;
  99161. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  99162. int iDb;
  99163. if( !zModuleName ){
  99164. return SQLITE_NOMEM;
  99165. }
  99166. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  99167. if( !pVTable ){
  99168. sqlite3DbFree(db, zModuleName);
  99169. return SQLITE_NOMEM;
  99170. }
  99171. pVTable->db = db;
  99172. pVTable->pMod = pMod;
  99173. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  99174. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  99175. /* Invoke the virtual table constructor */
  99176. assert( &db->pVtabCtx );
  99177. assert( xConstruct );
  99178. sCtx.pTab = pTab;
  99179. sCtx.pVTable = pVTable;
  99180. pPriorCtx = db->pVtabCtx;
  99181. db->pVtabCtx = &sCtx;
  99182. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  99183. db->pVtabCtx = pPriorCtx;
  99184. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  99185. if( SQLITE_OK!=rc ){
  99186. if( zErr==0 ){
  99187. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  99188. }else {
  99189. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  99190. sqlite3_free(zErr);
  99191. }
  99192. sqlite3DbFree(db, pVTable);
  99193. }else if( ALWAYS(pVTable->pVtab) ){
  99194. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  99195. ** the sqlite3_vtab object if successful. */
  99196. pVTable->pVtab->pModule = pMod->pModule;
  99197. pVTable->nRef = 1;
  99198. if( sCtx.pTab ){
  99199. const char *zFormat = "vtable constructor did not declare schema: %s";
  99200. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  99201. sqlite3VtabUnlock(pVTable);
  99202. rc = SQLITE_ERROR;
  99203. }else{
  99204. int iCol;
  99205. /* If everything went according to plan, link the new VTable structure
  99206. ** into the linked list headed by pTab->pVTable. Then loop through the
  99207. ** columns of the table to see if any of them contain the token "hidden".
  99208. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  99209. ** the type string. */
  99210. pVTable->pNext = pTab->pVTable;
  99211. pTab->pVTable = pVTable;
  99212. for(iCol=0; iCol<pTab->nCol; iCol++){
  99213. char *zType = pTab->aCol[iCol].zType;
  99214. int nType;
  99215. int i = 0;
  99216. if( !zType ) continue;
  99217. nType = sqlite3Strlen30(zType);
  99218. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  99219. for(i=0; i<nType; i++){
  99220. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  99221. && (zType[i+7]=='\0' || zType[i+7]==' ')
  99222. ){
  99223. i++;
  99224. break;
  99225. }
  99226. }
  99227. }
  99228. if( i<nType ){
  99229. int j;
  99230. int nDel = 6 + (zType[i+6] ? 1 : 0);
  99231. for(j=i; (j+nDel)<=nType; j++){
  99232. zType[j] = zType[j+nDel];
  99233. }
  99234. if( zType[i]=='\0' && i>0 ){
  99235. assert(zType[i-1]==' ');
  99236. zType[i-1] = '\0';
  99237. }
  99238. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  99239. }
  99240. }
  99241. }
  99242. }
  99243. sqlite3DbFree(db, zModuleName);
  99244. return rc;
  99245. }
  99246. /*
  99247. ** This function is invoked by the parser to call the xConnect() method
  99248. ** of the virtual table pTab. If an error occurs, an error code is returned
  99249. ** and an error left in pParse.
  99250. **
  99251. ** This call is a no-op if table pTab is not a virtual table.
  99252. */
  99253. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  99254. sqlite3 *db = pParse->db;
  99255. const char *zMod;
  99256. Module *pMod;
  99257. int rc;
  99258. assert( pTab );
  99259. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  99260. return SQLITE_OK;
  99261. }
  99262. /* Locate the required virtual table module */
  99263. zMod = pTab->azModuleArg[0];
  99264. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  99265. if( !pMod ){
  99266. const char *zModule = pTab->azModuleArg[0];
  99267. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  99268. rc = SQLITE_ERROR;
  99269. }else{
  99270. char *zErr = 0;
  99271. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  99272. if( rc!=SQLITE_OK ){
  99273. sqlite3ErrorMsg(pParse, "%s", zErr);
  99274. }
  99275. sqlite3DbFree(db, zErr);
  99276. }
  99277. return rc;
  99278. }
  99279. /*
  99280. ** Grow the db->aVTrans[] array so that there is room for at least one
  99281. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  99282. */
  99283. static int growVTrans(sqlite3 *db){
  99284. const int ARRAY_INCR = 5;
  99285. /* Grow the sqlite3.aVTrans array if required */
  99286. if( (db->nVTrans%ARRAY_INCR)==0 ){
  99287. VTable **aVTrans;
  99288. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  99289. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  99290. if( !aVTrans ){
  99291. return SQLITE_NOMEM;
  99292. }
  99293. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  99294. db->aVTrans = aVTrans;
  99295. }
  99296. return SQLITE_OK;
  99297. }
  99298. /*
  99299. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  99300. ** have already been reserved using growVTrans().
  99301. */
  99302. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  99303. /* Add pVtab to the end of sqlite3.aVTrans */
  99304. db->aVTrans[db->nVTrans++] = pVTab;
  99305. sqlite3VtabLock(pVTab);
  99306. }
  99307. /*
  99308. ** This function is invoked by the vdbe to call the xCreate method
  99309. ** of the virtual table named zTab in database iDb.
  99310. **
  99311. ** If an error occurs, *pzErr is set to point an an English language
  99312. ** description of the error and an SQLITE_XXX error code is returned.
  99313. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  99314. */
  99315. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  99316. int rc = SQLITE_OK;
  99317. Table *pTab;
  99318. Module *pMod;
  99319. const char *zMod;
  99320. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  99321. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  99322. /* Locate the required virtual table module */
  99323. zMod = pTab->azModuleArg[0];
  99324. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  99325. /* If the module has been registered and includes a Create method,
  99326. ** invoke it now. If the module has not been registered, return an
  99327. ** error. Otherwise, do nothing.
  99328. */
  99329. if( !pMod ){
  99330. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  99331. rc = SQLITE_ERROR;
  99332. }else{
  99333. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  99334. }
  99335. /* Justification of ALWAYS(): The xConstructor method is required to
  99336. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  99337. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  99338. rc = growVTrans(db);
  99339. if( rc==SQLITE_OK ){
  99340. addToVTrans(db, sqlite3GetVTable(db, pTab));
  99341. }
  99342. }
  99343. return rc;
  99344. }
  99345. /*
  99346. ** This function is used to set the schema of a virtual table. It is only
  99347. ** valid to call this function from within the xCreate() or xConnect() of a
  99348. ** virtual table module.
  99349. */
  99350. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  99351. Parse *pParse;
  99352. int rc = SQLITE_OK;
  99353. Table *pTab;
  99354. char *zErr = 0;
  99355. sqlite3_mutex_enter(db->mutex);
  99356. if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
  99357. sqlite3Error(db, SQLITE_MISUSE, 0);
  99358. sqlite3_mutex_leave(db->mutex);
  99359. return SQLITE_MISUSE_BKPT;
  99360. }
  99361. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  99362. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  99363. if( pParse==0 ){
  99364. rc = SQLITE_NOMEM;
  99365. }else{
  99366. pParse->declareVtab = 1;
  99367. pParse->db = db;
  99368. pParse->nQueryLoop = 1;
  99369. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  99370. && pParse->pNewTable
  99371. && !db->mallocFailed
  99372. && !pParse->pNewTable->pSelect
  99373. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  99374. ){
  99375. if( !pTab->aCol ){
  99376. pTab->aCol = pParse->pNewTable->aCol;
  99377. pTab->nCol = pParse->pNewTable->nCol;
  99378. pParse->pNewTable->nCol = 0;
  99379. pParse->pNewTable->aCol = 0;
  99380. }
  99381. db->pVtabCtx->pTab = 0;
  99382. }else{
  99383. sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  99384. sqlite3DbFree(db, zErr);
  99385. rc = SQLITE_ERROR;
  99386. }
  99387. pParse->declareVtab = 0;
  99388. if( pParse->pVdbe ){
  99389. sqlite3VdbeFinalize(pParse->pVdbe);
  99390. }
  99391. sqlite3DeleteTable(db, pParse->pNewTable);
  99392. sqlite3StackFree(db, pParse);
  99393. }
  99394. assert( (rc&0xff)==rc );
  99395. rc = sqlite3ApiExit(db, rc);
  99396. sqlite3_mutex_leave(db->mutex);
  99397. return rc;
  99398. }
  99399. /*
  99400. ** This function is invoked by the vdbe to call the xDestroy method
  99401. ** of the virtual table named zTab in database iDb. This occurs
  99402. ** when a DROP TABLE is mentioned.
  99403. **
  99404. ** This call is a no-op if zTab is not a virtual table.
  99405. */
  99406. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  99407. int rc = SQLITE_OK;
  99408. Table *pTab;
  99409. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  99410. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  99411. VTable *p = vtabDisconnectAll(db, pTab);
  99412. assert( rc==SQLITE_OK );
  99413. rc = p->pMod->pModule->xDestroy(p->pVtab);
  99414. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  99415. if( rc==SQLITE_OK ){
  99416. assert( pTab->pVTable==p && p->pNext==0 );
  99417. p->pVtab = 0;
  99418. pTab->pVTable = 0;
  99419. sqlite3VtabUnlock(p);
  99420. }
  99421. }
  99422. return rc;
  99423. }
  99424. /*
  99425. ** This function invokes either the xRollback or xCommit method
  99426. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  99427. ** called is identified by the second argument, "offset", which is
  99428. ** the offset of the method to call in the sqlite3_module structure.
  99429. **
  99430. ** The array is cleared after invoking the callbacks.
  99431. */
  99432. static void callFinaliser(sqlite3 *db, int offset){
  99433. int i;
  99434. if( db->aVTrans ){
  99435. for(i=0; i<db->nVTrans; i++){
  99436. VTable *pVTab = db->aVTrans[i];
  99437. sqlite3_vtab *p = pVTab->pVtab;
  99438. if( p ){
  99439. int (*x)(sqlite3_vtab *);
  99440. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  99441. if( x ) x(p);
  99442. }
  99443. pVTab->iSavepoint = 0;
  99444. sqlite3VtabUnlock(pVTab);
  99445. }
  99446. sqlite3DbFree(db, db->aVTrans);
  99447. db->nVTrans = 0;
  99448. db->aVTrans = 0;
  99449. }
  99450. }
  99451. /*
  99452. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  99453. ** array. Return the error code for the first error that occurs, or
  99454. ** SQLITE_OK if all xSync operations are successful.
  99455. **
  99456. ** If an error message is available, leave it in p->zErrMsg.
  99457. */
  99458. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  99459. int i;
  99460. int rc = SQLITE_OK;
  99461. VTable **aVTrans = db->aVTrans;
  99462. db->aVTrans = 0;
  99463. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  99464. int (*x)(sqlite3_vtab *);
  99465. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  99466. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  99467. rc = x(pVtab);
  99468. sqlite3VtabImportErrmsg(p, pVtab);
  99469. }
  99470. }
  99471. db->aVTrans = aVTrans;
  99472. return rc;
  99473. }
  99474. /*
  99475. ** Invoke the xRollback method of all virtual tables in the
  99476. ** sqlite3.aVTrans array. Then clear the array itself.
  99477. */
  99478. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  99479. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  99480. return SQLITE_OK;
  99481. }
  99482. /*
  99483. ** Invoke the xCommit method of all virtual tables in the
  99484. ** sqlite3.aVTrans array. Then clear the array itself.
  99485. */
  99486. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  99487. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  99488. return SQLITE_OK;
  99489. }
  99490. /*
  99491. ** If the virtual table pVtab supports the transaction interface
  99492. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  99493. ** not currently open, invoke the xBegin method now.
  99494. **
  99495. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  99496. ** in the sqlite3.aVTrans array.
  99497. */
  99498. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  99499. int rc = SQLITE_OK;
  99500. const sqlite3_module *pModule;
  99501. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  99502. ** than zero, then this function is being called from within a
  99503. ** virtual module xSync() callback. It is illegal to write to
  99504. ** virtual module tables in this case, so return SQLITE_LOCKED.
  99505. */
  99506. if( sqlite3VtabInSync(db) ){
  99507. return SQLITE_LOCKED;
  99508. }
  99509. if( !pVTab ){
  99510. return SQLITE_OK;
  99511. }
  99512. pModule = pVTab->pVtab->pModule;
  99513. if( pModule->xBegin ){
  99514. int i;
  99515. /* If pVtab is already in the aVTrans array, return early */
  99516. for(i=0; i<db->nVTrans; i++){
  99517. if( db->aVTrans[i]==pVTab ){
  99518. return SQLITE_OK;
  99519. }
  99520. }
  99521. /* Invoke the xBegin method. If successful, add the vtab to the
  99522. ** sqlite3.aVTrans[] array. */
  99523. rc = growVTrans(db);
  99524. if( rc==SQLITE_OK ){
  99525. rc = pModule->xBegin(pVTab->pVtab);
  99526. if( rc==SQLITE_OK ){
  99527. addToVTrans(db, pVTab);
  99528. }
  99529. }
  99530. }
  99531. return rc;
  99532. }
  99533. /*
  99534. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  99535. ** virtual tables that currently have an open transaction. Pass iSavepoint
  99536. ** as the second argument to the virtual table method invoked.
  99537. **
  99538. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  99539. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  99540. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  99541. ** an open transaction is invoked.
  99542. **
  99543. ** If any virtual table method returns an error code other than SQLITE_OK,
  99544. ** processing is abandoned and the error returned to the caller of this
  99545. ** function immediately. If all calls to virtual table methods are successful,
  99546. ** SQLITE_OK is returned.
  99547. */
  99548. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  99549. int rc = SQLITE_OK;
  99550. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  99551. assert( iSavepoint>=0 );
  99552. if( db->aVTrans ){
  99553. int i;
  99554. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  99555. VTable *pVTab = db->aVTrans[i];
  99556. const sqlite3_module *pMod = pVTab->pMod->pModule;
  99557. if( pVTab->pVtab && pMod->iVersion>=2 ){
  99558. int (*xMethod)(sqlite3_vtab *, int);
  99559. switch( op ){
  99560. case SAVEPOINT_BEGIN:
  99561. xMethod = pMod->xSavepoint;
  99562. pVTab->iSavepoint = iSavepoint+1;
  99563. break;
  99564. case SAVEPOINT_ROLLBACK:
  99565. xMethod = pMod->xRollbackTo;
  99566. break;
  99567. default:
  99568. xMethod = pMod->xRelease;
  99569. break;
  99570. }
  99571. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  99572. rc = xMethod(pVTab->pVtab, iSavepoint);
  99573. }
  99574. }
  99575. }
  99576. }
  99577. return rc;
  99578. }
  99579. /*
  99580. ** The first parameter (pDef) is a function implementation. The
  99581. ** second parameter (pExpr) is the first argument to this function.
  99582. ** If pExpr is a column in a virtual table, then let the virtual
  99583. ** table implementation have an opportunity to overload the function.
  99584. **
  99585. ** This routine is used to allow virtual table implementations to
  99586. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  99587. **
  99588. ** Return either the pDef argument (indicating no change) or a
  99589. ** new FuncDef structure that is marked as ephemeral using the
  99590. ** SQLITE_FUNC_EPHEM flag.
  99591. */
  99592. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  99593. sqlite3 *db, /* Database connection for reporting malloc problems */
  99594. FuncDef *pDef, /* Function to possibly overload */
  99595. int nArg, /* Number of arguments to the function */
  99596. Expr *pExpr /* First argument to the function */
  99597. ){
  99598. Table *pTab;
  99599. sqlite3_vtab *pVtab;
  99600. sqlite3_module *pMod;
  99601. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  99602. void *pArg = 0;
  99603. FuncDef *pNew;
  99604. int rc = 0;
  99605. char *zLowerName;
  99606. unsigned char *z;
  99607. /* Check to see the left operand is a column in a virtual table */
  99608. if( NEVER(pExpr==0) ) return pDef;
  99609. if( pExpr->op!=TK_COLUMN ) return pDef;
  99610. pTab = pExpr->pTab;
  99611. if( NEVER(pTab==0) ) return pDef;
  99612. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  99613. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  99614. assert( pVtab!=0 );
  99615. assert( pVtab->pModule!=0 );
  99616. pMod = (sqlite3_module *)pVtab->pModule;
  99617. if( pMod->xFindFunction==0 ) return pDef;
  99618. /* Call the xFindFunction method on the virtual table implementation
  99619. ** to see if the implementation wants to overload this function
  99620. */
  99621. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  99622. if( zLowerName ){
  99623. for(z=(unsigned char*)zLowerName; *z; z++){
  99624. *z = sqlite3UpperToLower[*z];
  99625. }
  99626. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  99627. sqlite3DbFree(db, zLowerName);
  99628. }
  99629. if( rc==0 ){
  99630. return pDef;
  99631. }
  99632. /* Create a new ephemeral function definition for the overloaded
  99633. ** function */
  99634. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  99635. + sqlite3Strlen30(pDef->zName) + 1);
  99636. if( pNew==0 ){
  99637. return pDef;
  99638. }
  99639. *pNew = *pDef;
  99640. pNew->zName = (char *)&pNew[1];
  99641. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  99642. pNew->xFunc = xFunc;
  99643. pNew->pUserData = pArg;
  99644. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  99645. return pNew;
  99646. }
  99647. /*
  99648. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  99649. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  99650. ** array if it is missing. If pTab is already in the array, this routine
  99651. ** is a no-op.
  99652. */
  99653. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  99654. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  99655. int i, n;
  99656. Table **apVtabLock;
  99657. assert( IsVirtual(pTab) );
  99658. for(i=0; i<pToplevel->nVtabLock; i++){
  99659. if( pTab==pToplevel->apVtabLock[i] ) return;
  99660. }
  99661. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  99662. apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
  99663. if( apVtabLock ){
  99664. pToplevel->apVtabLock = apVtabLock;
  99665. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  99666. }else{
  99667. pToplevel->db->mallocFailed = 1;
  99668. }
  99669. }
  99670. /*
  99671. ** Return the ON CONFLICT resolution mode in effect for the virtual
  99672. ** table update operation currently in progress.
  99673. **
  99674. ** The results of this routine are undefined unless it is called from
  99675. ** within an xUpdate method.
  99676. */
  99677. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  99678. static const unsigned char aMap[] = {
  99679. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  99680. };
  99681. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  99682. assert( OE_Ignore==4 && OE_Replace==5 );
  99683. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  99684. return (int)aMap[db->vtabOnConflict-1];
  99685. }
  99686. /*
  99687. ** Call from within the xCreate() or xConnect() methods to provide
  99688. ** the SQLite core with additional information about the behavior
  99689. ** of the virtual table being implemented.
  99690. */
  99691. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  99692. va_list ap;
  99693. int rc = SQLITE_OK;
  99694. sqlite3_mutex_enter(db->mutex);
  99695. va_start(ap, op);
  99696. switch( op ){
  99697. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  99698. VtabCtx *p = db->pVtabCtx;
  99699. if( !p ){
  99700. rc = SQLITE_MISUSE_BKPT;
  99701. }else{
  99702. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  99703. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  99704. }
  99705. break;
  99706. }
  99707. default:
  99708. rc = SQLITE_MISUSE_BKPT;
  99709. break;
  99710. }
  99711. va_end(ap);
  99712. if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
  99713. sqlite3_mutex_leave(db->mutex);
  99714. return rc;
  99715. }
  99716. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  99717. /************** End of vtab.c ************************************************/
  99718. /************** Begin file where.c *******************************************/
  99719. /*
  99720. ** 2001 September 15
  99721. **
  99722. ** The author disclaims copyright to this source code. In place of
  99723. ** a legal notice, here is a blessing:
  99724. **
  99725. ** May you do good and not evil.
  99726. ** May you find forgiveness for yourself and forgive others.
  99727. ** May you share freely, never taking more than you give.
  99728. **
  99729. *************************************************************************
  99730. ** This module contains C code that generates VDBE code used to process
  99731. ** the WHERE clause of SQL statements. This module is responsible for
  99732. ** generating the code that loops through a table looking for applicable
  99733. ** rows. Indices are selected and used to speed the search when doing
  99734. ** so is applicable. Because this module is responsible for selecting
  99735. ** indices, you might also think of this module as the "query optimizer".
  99736. */
  99737. /*
  99738. ** Trace output macros
  99739. */
  99740. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  99741. /***/ int sqlite3WhereTrace = 0;
  99742. #endif
  99743. #if defined(SQLITE_DEBUG) \
  99744. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  99745. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  99746. # define WHERETRACE_ENABLED 1
  99747. #else
  99748. # define WHERETRACE(K,X)
  99749. #endif
  99750. /* Forward references
  99751. */
  99752. typedef struct WhereClause WhereClause;
  99753. typedef struct WhereMaskSet WhereMaskSet;
  99754. typedef struct WhereOrInfo WhereOrInfo;
  99755. typedef struct WhereAndInfo WhereAndInfo;
  99756. typedef struct WhereLevel WhereLevel;
  99757. typedef struct WhereLoop WhereLoop;
  99758. typedef struct WherePath WherePath;
  99759. typedef struct WhereTerm WhereTerm;
  99760. typedef struct WhereLoopBuilder WhereLoopBuilder;
  99761. typedef struct WhereScan WhereScan;
  99762. typedef struct WhereOrCost WhereOrCost;
  99763. typedef struct WhereOrSet WhereOrSet;
  99764. /*
  99765. ** This object contains information needed to implement a single nested
  99766. ** loop in WHERE clause.
  99767. **
  99768. ** Contrast this object with WhereLoop. This object describes the
  99769. ** implementation of the loop. WhereLoop describes the algorithm.
  99770. ** This object contains a pointer to the WhereLoop algorithm as one of
  99771. ** its elements.
  99772. **
  99773. ** The WhereInfo object contains a single instance of this object for
  99774. ** each term in the FROM clause (which is to say, for each of the
  99775. ** nested loops as implemented). The order of WhereLevel objects determines
  99776. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  99777. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  99778. */
  99779. struct WhereLevel {
  99780. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  99781. int iTabCur; /* The VDBE cursor used to access the table */
  99782. int iIdxCur; /* The VDBE cursor used to access pIdx */
  99783. int addrBrk; /* Jump here to break out of the loop */
  99784. int addrNxt; /* Jump here to start the next IN combination */
  99785. int addrCont; /* Jump here to continue with the next loop cycle */
  99786. int addrFirst; /* First instruction of interior of the loop */
  99787. int addrBody; /* Beginning of the body of this loop */
  99788. u8 iFrom; /* Which entry in the FROM clause */
  99789. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  99790. int p1, p2; /* Operands of the opcode used to ends the loop */
  99791. union { /* Information that depends on pWLoop->wsFlags */
  99792. struct {
  99793. int nIn; /* Number of entries in aInLoop[] */
  99794. struct InLoop {
  99795. int iCur; /* The VDBE cursor used by this IN operator */
  99796. int addrInTop; /* Top of the IN loop */
  99797. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  99798. } *aInLoop; /* Information about each nested IN operator */
  99799. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  99800. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  99801. } u;
  99802. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  99803. Bitmask notReady; /* FROM entries not usable at this level */
  99804. };
  99805. /*
  99806. ** Each instance of this object represents an algorithm for evaluating one
  99807. ** term of a join. Every term of the FROM clause will have at least
  99808. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  99809. ** prevent a query solution - which is an error) and many terms of the
  99810. ** FROM clause will have multiple WhereLoop objects, each describing a
  99811. ** potential way of implementing that FROM-clause term, together with
  99812. ** dependencies and cost estimates for using the chosen algorithm.
  99813. **
  99814. ** Query planning consists of building up a collection of these WhereLoop
  99815. ** objects, then computing a particular sequence of WhereLoop objects, with
  99816. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  99817. ** and that minimize the overall cost.
  99818. */
  99819. struct WhereLoop {
  99820. Bitmask prereq; /* Bitmask of other loops that must run first */
  99821. Bitmask maskSelf; /* Bitmask identifying table iTab */
  99822. #ifdef SQLITE_DEBUG
  99823. char cId; /* Symbolic ID of this loop for debugging use */
  99824. #endif
  99825. u8 iTab; /* Position in FROM clause of table for this loop */
  99826. u8 iSortIdx; /* Sorting index number. 0==None */
  99827. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  99828. LogEst rRun; /* Cost of running each loop */
  99829. LogEst nOut; /* Estimated number of output rows */
  99830. union {
  99831. struct { /* Information for internal btree tables */
  99832. int nEq; /* Number of equality constraints */
  99833. Index *pIndex; /* Index used, or NULL */
  99834. } btree;
  99835. struct { /* Information for virtual tables */
  99836. int idxNum; /* Index number */
  99837. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  99838. u8 isOrdered; /* True if satisfies ORDER BY */
  99839. u16 omitMask; /* Terms that may be omitted */
  99840. char *idxStr; /* Index identifier string */
  99841. } vtab;
  99842. } u;
  99843. u32 wsFlags; /* WHERE_* flags describing the plan */
  99844. u16 nLTerm; /* Number of entries in aLTerm[] */
  99845. /**** whereLoopXfer() copies fields above ***********************/
  99846. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  99847. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  99848. WhereTerm **aLTerm; /* WhereTerms used */
  99849. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  99850. WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
  99851. };
  99852. /* This object holds the prerequisites and the cost of running a
  99853. ** subquery on one operand of an OR operator in the WHERE clause.
  99854. ** See WhereOrSet for additional information
  99855. */
  99856. struct WhereOrCost {
  99857. Bitmask prereq; /* Prerequisites */
  99858. LogEst rRun; /* Cost of running this subquery */
  99859. LogEst nOut; /* Number of outputs for this subquery */
  99860. };
  99861. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  99862. ** correspond to the subquery(s) of OR-clause processing. Only the
  99863. ** best N_OR_COST elements are retained.
  99864. */
  99865. #define N_OR_COST 3
  99866. struct WhereOrSet {
  99867. u16 n; /* Number of valid a[] entries */
  99868. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  99869. };
  99870. /* Forward declaration of methods */
  99871. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  99872. /*
  99873. ** Each instance of this object holds a sequence of WhereLoop objects
  99874. ** that implement some or all of a query plan.
  99875. **
  99876. ** Think of each WhereLoop object as a node in a graph with arcs
  99877. ** showing dependencies and costs for travelling between nodes. (That is
  99878. ** not a completely accurate description because WhereLoop costs are a
  99879. ** vector, not a scalar, and because dependencies are many-to-one, not
  99880. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  99881. ** Then a WherePath object is a path through the graph that visits some
  99882. ** or all of the WhereLoop objects once.
  99883. **
  99884. ** The "solver" works by creating the N best WherePath objects of length
  99885. ** 1. Then using those as a basis to compute the N best WherePath objects
  99886. ** of length 2. And so forth until the length of WherePaths equals the
  99887. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  99888. ** at the end is the choosen query plan.
  99889. */
  99890. struct WherePath {
  99891. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  99892. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  99893. LogEst nRow; /* Estimated number of rows generated by this path */
  99894. LogEst rCost; /* Total cost of this path */
  99895. u8 isOrdered; /* True if this path satisfies ORDER BY */
  99896. u8 isOrderedValid; /* True if the isOrdered field is valid */
  99897. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  99898. };
  99899. /*
  99900. ** The query generator uses an array of instances of this structure to
  99901. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  99902. ** clause subexpression is separated from the others by AND operators,
  99903. ** usually, or sometimes subexpressions separated by OR.
  99904. **
  99905. ** All WhereTerms are collected into a single WhereClause structure.
  99906. ** The following identity holds:
  99907. **
  99908. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  99909. **
  99910. ** When a term is of the form:
  99911. **
  99912. ** X <op> <expr>
  99913. **
  99914. ** where X is a column name and <op> is one of certain operators,
  99915. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  99916. ** cursor number and column number for X. WhereTerm.eOperator records
  99917. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  99918. ** use of a bitmask encoding for the operator allows us to search
  99919. ** quickly for terms that match any of several different operators.
  99920. **
  99921. ** A WhereTerm might also be two or more subterms connected by OR:
  99922. **
  99923. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  99924. **
  99925. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  99926. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  99927. ** is collected about the OR clause.
  99928. **
  99929. ** If a term in the WHERE clause does not match either of the two previous
  99930. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  99931. ** to the original subexpression content and wtFlags is set up appropriately
  99932. ** but no other fields in the WhereTerm object are meaningful.
  99933. **
  99934. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  99935. ** but they do so indirectly. A single WhereMaskSet structure translates
  99936. ** cursor number into bits and the translated bit is stored in the prereq
  99937. ** fields. The translation is used in order to maximize the number of
  99938. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  99939. ** spread out over the non-negative integers. For example, the cursor
  99940. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  99941. ** translates these sparse cursor numbers into consecutive integers
  99942. ** beginning with 0 in order to make the best possible use of the available
  99943. ** bits in the Bitmask. So, in the example above, the cursor numbers
  99944. ** would be mapped into integers 0 through 7.
  99945. **
  99946. ** The number of terms in a join is limited by the number of bits
  99947. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  99948. ** is only able to process joins with 64 or fewer tables.
  99949. */
  99950. struct WhereTerm {
  99951. Expr *pExpr; /* Pointer to the subexpression that is this term */
  99952. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  99953. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  99954. union {
  99955. int leftColumn; /* Column number of X in "X <op> <expr>" */
  99956. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  99957. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  99958. } u;
  99959. LogEst truthProb; /* Probability of truth for this expression */
  99960. u16 eOperator; /* A WO_xx value describing <op> */
  99961. u8 wtFlags; /* TERM_xxx bit flags. See below */
  99962. u8 nChild; /* Number of children that must disable us */
  99963. WhereClause *pWC; /* The clause this term is part of */
  99964. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  99965. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  99966. };
  99967. /*
  99968. ** Allowed values of WhereTerm.wtFlags
  99969. */
  99970. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  99971. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  99972. #define TERM_CODED 0x04 /* This term is already coded */
  99973. #define TERM_COPIED 0x08 /* Has a child */
  99974. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  99975. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  99976. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  99977. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99978. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  99979. #else
  99980. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  99981. #endif
  99982. /*
  99983. ** An instance of the WhereScan object is used as an iterator for locating
  99984. ** terms in the WHERE clause that are useful to the query planner.
  99985. */
  99986. struct WhereScan {
  99987. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  99988. WhereClause *pWC; /* WhereClause currently being scanned */
  99989. char *zCollName; /* Required collating sequence, if not NULL */
  99990. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  99991. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  99992. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  99993. u32 opMask; /* Acceptable operators */
  99994. int k; /* Resume scanning at this->pWC->a[this->k] */
  99995. int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
  99996. };
  99997. /*
  99998. ** An instance of the following structure holds all information about a
  99999. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  100000. **
  100001. ** Explanation of pOuter: For a WHERE clause of the form
  100002. **
  100003. ** a AND ((b AND c) OR (d AND e)) AND f
  100004. **
  100005. ** There are separate WhereClause objects for the whole clause and for
  100006. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  100007. ** subclauses points to the WhereClause object for the whole clause.
  100008. */
  100009. struct WhereClause {
  100010. WhereInfo *pWInfo; /* WHERE clause processing context */
  100011. WhereClause *pOuter; /* Outer conjunction */
  100012. u8 op; /* Split operator. TK_AND or TK_OR */
  100013. int nTerm; /* Number of terms */
  100014. int nSlot; /* Number of entries in a[] */
  100015. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  100016. #if defined(SQLITE_SMALL_STACK)
  100017. WhereTerm aStatic[1]; /* Initial static space for a[] */
  100018. #else
  100019. WhereTerm aStatic[8]; /* Initial static space for a[] */
  100020. #endif
  100021. };
  100022. /*
  100023. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  100024. ** a dynamically allocated instance of the following structure.
  100025. */
  100026. struct WhereOrInfo {
  100027. WhereClause wc; /* Decomposition into subterms */
  100028. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  100029. };
  100030. /*
  100031. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  100032. ** a dynamically allocated instance of the following structure.
  100033. */
  100034. struct WhereAndInfo {
  100035. WhereClause wc; /* The subexpression broken out */
  100036. };
  100037. /*
  100038. ** An instance of the following structure keeps track of a mapping
  100039. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  100040. **
  100041. ** The VDBE cursor numbers are small integers contained in
  100042. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  100043. ** clause, the cursor numbers might not begin with 0 and they might
  100044. ** contain gaps in the numbering sequence. But we want to make maximum
  100045. ** use of the bits in our bitmasks. This structure provides a mapping
  100046. ** from the sparse cursor numbers into consecutive integers beginning
  100047. ** with 0.
  100048. **
  100049. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  100050. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  100051. **
  100052. ** For example, if the WHERE clause expression used these VDBE
  100053. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  100054. ** would map those cursor numbers into bits 0 through 5.
  100055. **
  100056. ** Note that the mapping is not necessarily ordered. In the example
  100057. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  100058. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  100059. ** does not really matter. What is important is that sparse cursor
  100060. ** numbers all get mapped into bit numbers that begin with 0 and contain
  100061. ** no gaps.
  100062. */
  100063. struct WhereMaskSet {
  100064. int n; /* Number of assigned cursor values */
  100065. int ix[BMS]; /* Cursor assigned to each bit */
  100066. };
  100067. /*
  100068. ** This object is a convenience wrapper holding all information needed
  100069. ** to construct WhereLoop objects for a particular query.
  100070. */
  100071. struct WhereLoopBuilder {
  100072. WhereInfo *pWInfo; /* Information about this WHERE */
  100073. WhereClause *pWC; /* WHERE clause terms */
  100074. ExprList *pOrderBy; /* ORDER BY clause */
  100075. WhereLoop *pNew; /* Template WhereLoop */
  100076. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  100077. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  100078. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  100079. int nRecValid; /* Number of valid fields currently in pRec */
  100080. #endif
  100081. };
  100082. /*
  100083. ** The WHERE clause processing routine has two halves. The
  100084. ** first part does the start of the WHERE loop and the second
  100085. ** half does the tail of the WHERE loop. An instance of
  100086. ** this structure is returned by the first half and passed
  100087. ** into the second half to give some continuity.
  100088. **
  100089. ** An instance of this object holds the complete state of the query
  100090. ** planner.
  100091. */
  100092. struct WhereInfo {
  100093. Parse *pParse; /* Parsing and code generating context */
  100094. SrcList *pTabList; /* List of tables in the join */
  100095. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  100096. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  100097. WhereLoop *pLoops; /* List of all WhereLoop objects */
  100098. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  100099. LogEst nRowOut; /* Estimated number of output rows */
  100100. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  100101. u8 bOBSat; /* ORDER BY satisfied by indices */
  100102. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  100103. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  100104. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  100105. u8 nLevel; /* Number of nested loop */
  100106. int iTop; /* The very beginning of the WHERE loop */
  100107. int iContinue; /* Jump here to continue with next record */
  100108. int iBreak; /* Jump here to break out of the loop */
  100109. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  100110. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  100111. WhereClause sWC; /* Decomposition of the WHERE clause */
  100112. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  100113. };
  100114. /*
  100115. ** Bitmasks for the operators on WhereTerm objects. These are all
  100116. ** operators that are of interest to the query planner. An
  100117. ** OR-ed combination of these values can be used when searching for
  100118. ** particular WhereTerms within a WhereClause.
  100119. */
  100120. #define WO_IN 0x001
  100121. #define WO_EQ 0x002
  100122. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  100123. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  100124. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  100125. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  100126. #define WO_MATCH 0x040
  100127. #define WO_ISNULL 0x080
  100128. #define WO_OR 0x100 /* Two or more OR-connected terms */
  100129. #define WO_AND 0x200 /* Two or more AND-connected terms */
  100130. #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
  100131. #define WO_NOOP 0x800 /* This term does not restrict search space */
  100132. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  100133. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  100134. /*
  100135. ** These are definitions of bits in the WhereLoop.wsFlags field.
  100136. ** The particular combination of bits in each WhereLoop help to
  100137. ** determine the algorithm that WhereLoop represents.
  100138. */
  100139. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  100140. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  100141. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  100142. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  100143. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  100144. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  100145. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  100146. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  100147. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  100148. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  100149. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  100150. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  100151. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  100152. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  100153. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  100154. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  100155. /*
  100156. ** Return the estimated number of output rows from a WHERE clause
  100157. */
  100158. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  100159. return sqlite3LogEstToInt(pWInfo->nRowOut);
  100160. }
  100161. /*
  100162. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  100163. ** WHERE clause returns outputs for DISTINCT processing.
  100164. */
  100165. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  100166. return pWInfo->eDistinct;
  100167. }
  100168. /*
  100169. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  100170. ** Return FALSE if the output needs to be sorted.
  100171. */
  100172. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  100173. return pWInfo->bOBSat!=0;
  100174. }
  100175. /*
  100176. ** Return the VDBE address or label to jump to in order to continue
  100177. ** immediately with the next row of a WHERE clause.
  100178. */
  100179. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  100180. return pWInfo->iContinue;
  100181. }
  100182. /*
  100183. ** Return the VDBE address or label to jump to in order to break
  100184. ** out of a WHERE loop.
  100185. */
  100186. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  100187. return pWInfo->iBreak;
  100188. }
  100189. /*
  100190. ** Return TRUE if an UPDATE or DELETE statement can operate directly on
  100191. ** the rowids returned by a WHERE clause. Return FALSE if doing an
  100192. ** UPDATE or DELETE might change subsequent WHERE clause results.
  100193. */
  100194. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
  100195. return pWInfo->okOnePass;
  100196. }
  100197. /*
  100198. ** Move the content of pSrc into pDest
  100199. */
  100200. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  100201. pDest->n = pSrc->n;
  100202. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  100203. }
  100204. /*
  100205. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  100206. **
  100207. ** The new entry might overwrite an existing entry, or it might be
  100208. ** appended, or it might be discarded. Do whatever is the right thing
  100209. ** so that pSet keeps the N_OR_COST best entries seen so far.
  100210. */
  100211. static int whereOrInsert(
  100212. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  100213. Bitmask prereq, /* Prerequisites of the new entry */
  100214. LogEst rRun, /* Run-cost of the new entry */
  100215. LogEst nOut /* Number of outputs for the new entry */
  100216. ){
  100217. u16 i;
  100218. WhereOrCost *p;
  100219. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  100220. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  100221. goto whereOrInsert_done;
  100222. }
  100223. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  100224. return 0;
  100225. }
  100226. }
  100227. if( pSet->n<N_OR_COST ){
  100228. p = &pSet->a[pSet->n++];
  100229. p->nOut = nOut;
  100230. }else{
  100231. p = pSet->a;
  100232. for(i=1; i<pSet->n; i++){
  100233. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  100234. }
  100235. if( p->rRun<=rRun ) return 0;
  100236. }
  100237. whereOrInsert_done:
  100238. p->prereq = prereq;
  100239. p->rRun = rRun;
  100240. if( p->nOut>nOut ) p->nOut = nOut;
  100241. return 1;
  100242. }
  100243. /*
  100244. ** Initialize a preallocated WhereClause structure.
  100245. */
  100246. static void whereClauseInit(
  100247. WhereClause *pWC, /* The WhereClause to be initialized */
  100248. WhereInfo *pWInfo /* The WHERE processing context */
  100249. ){
  100250. pWC->pWInfo = pWInfo;
  100251. pWC->pOuter = 0;
  100252. pWC->nTerm = 0;
  100253. pWC->nSlot = ArraySize(pWC->aStatic);
  100254. pWC->a = pWC->aStatic;
  100255. }
  100256. /* Forward reference */
  100257. static void whereClauseClear(WhereClause*);
  100258. /*
  100259. ** Deallocate all memory associated with a WhereOrInfo object.
  100260. */
  100261. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  100262. whereClauseClear(&p->wc);
  100263. sqlite3DbFree(db, p);
  100264. }
  100265. /*
  100266. ** Deallocate all memory associated with a WhereAndInfo object.
  100267. */
  100268. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  100269. whereClauseClear(&p->wc);
  100270. sqlite3DbFree(db, p);
  100271. }
  100272. /*
  100273. ** Deallocate a WhereClause structure. The WhereClause structure
  100274. ** itself is not freed. This routine is the inverse of whereClauseInit().
  100275. */
  100276. static void whereClauseClear(WhereClause *pWC){
  100277. int i;
  100278. WhereTerm *a;
  100279. sqlite3 *db = pWC->pWInfo->pParse->db;
  100280. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  100281. if( a->wtFlags & TERM_DYNAMIC ){
  100282. sqlite3ExprDelete(db, a->pExpr);
  100283. }
  100284. if( a->wtFlags & TERM_ORINFO ){
  100285. whereOrInfoDelete(db, a->u.pOrInfo);
  100286. }else if( a->wtFlags & TERM_ANDINFO ){
  100287. whereAndInfoDelete(db, a->u.pAndInfo);
  100288. }
  100289. }
  100290. if( pWC->a!=pWC->aStatic ){
  100291. sqlite3DbFree(db, pWC->a);
  100292. }
  100293. }
  100294. /*
  100295. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  100296. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  100297. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  100298. ** 0 is returned if the new WhereTerm could not be added due to a memory
  100299. ** allocation error. The memory allocation failure will be recorded in
  100300. ** the db->mallocFailed flag so that higher-level functions can detect it.
  100301. **
  100302. ** This routine will increase the size of the pWC->a[] array as necessary.
  100303. **
  100304. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  100305. ** for freeing the expression p is assumed by the WhereClause object pWC.
  100306. ** This is true even if this routine fails to allocate a new WhereTerm.
  100307. **
  100308. ** WARNING: This routine might reallocate the space used to store
  100309. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  100310. ** calling this routine. Such pointers may be reinitialized by referencing
  100311. ** the pWC->a[] array.
  100312. */
  100313. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  100314. WhereTerm *pTerm;
  100315. int idx;
  100316. testcase( wtFlags & TERM_VIRTUAL );
  100317. if( pWC->nTerm>=pWC->nSlot ){
  100318. WhereTerm *pOld = pWC->a;
  100319. sqlite3 *db = pWC->pWInfo->pParse->db;
  100320. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  100321. if( pWC->a==0 ){
  100322. if( wtFlags & TERM_DYNAMIC ){
  100323. sqlite3ExprDelete(db, p);
  100324. }
  100325. pWC->a = pOld;
  100326. return 0;
  100327. }
  100328. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  100329. if( pOld!=pWC->aStatic ){
  100330. sqlite3DbFree(db, pOld);
  100331. }
  100332. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  100333. }
  100334. pTerm = &pWC->a[idx = pWC->nTerm++];
  100335. if( p && ExprHasProperty(p, EP_Unlikely) ){
  100336. pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
  100337. }else{
  100338. pTerm->truthProb = -1;
  100339. }
  100340. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  100341. pTerm->wtFlags = wtFlags;
  100342. pTerm->pWC = pWC;
  100343. pTerm->iParent = -1;
  100344. return idx;
  100345. }
  100346. /*
  100347. ** This routine identifies subexpressions in the WHERE clause where
  100348. ** each subexpression is separated by the AND operator or some other
  100349. ** operator specified in the op parameter. The WhereClause structure
  100350. ** is filled with pointers to subexpressions. For example:
  100351. **
  100352. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  100353. ** \________/ \_______________/ \________________/
  100354. ** slot[0] slot[1] slot[2]
  100355. **
  100356. ** The original WHERE clause in pExpr is unaltered. All this routine
  100357. ** does is make slot[] entries point to substructure within pExpr.
  100358. **
  100359. ** In the previous sentence and in the diagram, "slot[]" refers to
  100360. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  100361. ** all terms of the WHERE clause.
  100362. */
  100363. static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  100364. pWC->op = op;
  100365. if( pExpr==0 ) return;
  100366. if( pExpr->op!=op ){
  100367. whereClauseInsert(pWC, pExpr, 0);
  100368. }else{
  100369. whereSplit(pWC, pExpr->pLeft, op);
  100370. whereSplit(pWC, pExpr->pRight, op);
  100371. }
  100372. }
  100373. /*
  100374. ** Initialize a WhereMaskSet object
  100375. */
  100376. #define initMaskSet(P) (P)->n=0
  100377. /*
  100378. ** Return the bitmask for the given cursor number. Return 0 if
  100379. ** iCursor is not in the set.
  100380. */
  100381. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  100382. int i;
  100383. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  100384. for(i=0; i<pMaskSet->n; i++){
  100385. if( pMaskSet->ix[i]==iCursor ){
  100386. return MASKBIT(i);
  100387. }
  100388. }
  100389. return 0;
  100390. }
  100391. /*
  100392. ** Create a new mask for cursor iCursor.
  100393. **
  100394. ** There is one cursor per table in the FROM clause. The number of
  100395. ** tables in the FROM clause is limited by a test early in the
  100396. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  100397. ** array will never overflow.
  100398. */
  100399. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  100400. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  100401. pMaskSet->ix[pMaskSet->n++] = iCursor;
  100402. }
  100403. /*
  100404. ** These routines walk (recursively) an expression tree and generate
  100405. ** a bitmask indicating which tables are used in that expression
  100406. ** tree.
  100407. */
  100408. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  100409. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  100410. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  100411. Bitmask mask = 0;
  100412. if( p==0 ) return 0;
  100413. if( p->op==TK_COLUMN ){
  100414. mask = getMask(pMaskSet, p->iTable);
  100415. return mask;
  100416. }
  100417. mask = exprTableUsage(pMaskSet, p->pRight);
  100418. mask |= exprTableUsage(pMaskSet, p->pLeft);
  100419. if( ExprHasProperty(p, EP_xIsSelect) ){
  100420. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  100421. }else{
  100422. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  100423. }
  100424. return mask;
  100425. }
  100426. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  100427. int i;
  100428. Bitmask mask = 0;
  100429. if( pList ){
  100430. for(i=0; i<pList->nExpr; i++){
  100431. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  100432. }
  100433. }
  100434. return mask;
  100435. }
  100436. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  100437. Bitmask mask = 0;
  100438. while( pS ){
  100439. SrcList *pSrc = pS->pSrc;
  100440. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  100441. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  100442. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  100443. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  100444. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  100445. if( ALWAYS(pSrc!=0) ){
  100446. int i;
  100447. for(i=0; i<pSrc->nSrc; i++){
  100448. mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
  100449. mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
  100450. }
  100451. }
  100452. pS = pS->pPrior;
  100453. }
  100454. return mask;
  100455. }
  100456. /*
  100457. ** Return TRUE if the given operator is one of the operators that is
  100458. ** allowed for an indexable WHERE clause term. The allowed operators are
  100459. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  100460. */
  100461. static int allowedOp(int op){
  100462. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  100463. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  100464. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  100465. assert( TK_GE==TK_EQ+4 );
  100466. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  100467. }
  100468. /*
  100469. ** Swap two objects of type TYPE.
  100470. */
  100471. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  100472. /*
  100473. ** Commute a comparison operator. Expressions of the form "X op Y"
  100474. ** are converted into "Y op X".
  100475. **
  100476. ** If left/right precedence rules come into play when determining the
  100477. ** collating sequence, then COLLATE operators are adjusted to ensure
  100478. ** that the collating sequence does not change. For example:
  100479. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  100480. ** the left hand side of a comparison overrides any collation sequence
  100481. ** attached to the right. For the same reason the EP_Collate flag
  100482. ** is not commuted.
  100483. */
  100484. static void exprCommute(Parse *pParse, Expr *pExpr){
  100485. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  100486. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  100487. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  100488. if( expRight==expLeft ){
  100489. /* Either X and Y both have COLLATE operator or neither do */
  100490. if( expRight ){
  100491. /* Both X and Y have COLLATE operators. Make sure X is always
  100492. ** used by clearing the EP_Collate flag from Y. */
  100493. pExpr->pRight->flags &= ~EP_Collate;
  100494. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  100495. /* Neither X nor Y have COLLATE operators, but X has a non-default
  100496. ** collating sequence. So add the EP_Collate marker on X to cause
  100497. ** it to be searched first. */
  100498. pExpr->pLeft->flags |= EP_Collate;
  100499. }
  100500. }
  100501. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  100502. if( pExpr->op>=TK_GT ){
  100503. assert( TK_LT==TK_GT+2 );
  100504. assert( TK_GE==TK_LE+2 );
  100505. assert( TK_GT>TK_EQ );
  100506. assert( TK_GT<TK_LE );
  100507. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  100508. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  100509. }
  100510. }
  100511. /*
  100512. ** Translate from TK_xx operator to WO_xx bitmask.
  100513. */
  100514. static u16 operatorMask(int op){
  100515. u16 c;
  100516. assert( allowedOp(op) );
  100517. if( op==TK_IN ){
  100518. c = WO_IN;
  100519. }else if( op==TK_ISNULL ){
  100520. c = WO_ISNULL;
  100521. }else{
  100522. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  100523. c = (u16)(WO_EQ<<(op-TK_EQ));
  100524. }
  100525. assert( op!=TK_ISNULL || c==WO_ISNULL );
  100526. assert( op!=TK_IN || c==WO_IN );
  100527. assert( op!=TK_EQ || c==WO_EQ );
  100528. assert( op!=TK_LT || c==WO_LT );
  100529. assert( op!=TK_LE || c==WO_LE );
  100530. assert( op!=TK_GT || c==WO_GT );
  100531. assert( op!=TK_GE || c==WO_GE );
  100532. return c;
  100533. }
  100534. /*
  100535. ** Advance to the next WhereTerm that matches according to the criteria
  100536. ** established when the pScan object was initialized by whereScanInit().
  100537. ** Return NULL if there are no more matching WhereTerms.
  100538. */
  100539. static WhereTerm *whereScanNext(WhereScan *pScan){
  100540. int iCur; /* The cursor on the LHS of the term */
  100541. int iColumn; /* The column on the LHS of the term. -1 for IPK */
  100542. Expr *pX; /* An expression being tested */
  100543. WhereClause *pWC; /* Shorthand for pScan->pWC */
  100544. WhereTerm *pTerm; /* The term being tested */
  100545. int k = pScan->k; /* Where to start scanning */
  100546. while( pScan->iEquiv<=pScan->nEquiv ){
  100547. iCur = pScan->aEquiv[pScan->iEquiv-2];
  100548. iColumn = pScan->aEquiv[pScan->iEquiv-1];
  100549. while( (pWC = pScan->pWC)!=0 ){
  100550. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  100551. if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
  100552. if( (pTerm->eOperator & WO_EQUIV)!=0
  100553. && pScan->nEquiv<ArraySize(pScan->aEquiv)
  100554. ){
  100555. int j;
  100556. pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
  100557. assert( pX->op==TK_COLUMN );
  100558. for(j=0; j<pScan->nEquiv; j+=2){
  100559. if( pScan->aEquiv[j]==pX->iTable
  100560. && pScan->aEquiv[j+1]==pX->iColumn ){
  100561. break;
  100562. }
  100563. }
  100564. if( j==pScan->nEquiv ){
  100565. pScan->aEquiv[j] = pX->iTable;
  100566. pScan->aEquiv[j+1] = pX->iColumn;
  100567. pScan->nEquiv += 2;
  100568. }
  100569. }
  100570. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  100571. /* Verify the affinity and collating sequence match */
  100572. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  100573. CollSeq *pColl;
  100574. Parse *pParse = pWC->pWInfo->pParse;
  100575. pX = pTerm->pExpr;
  100576. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  100577. continue;
  100578. }
  100579. assert(pX->pLeft);
  100580. pColl = sqlite3BinaryCompareCollSeq(pParse,
  100581. pX->pLeft, pX->pRight);
  100582. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  100583. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  100584. continue;
  100585. }
  100586. }
  100587. if( (pTerm->eOperator & WO_EQ)!=0
  100588. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  100589. && pX->iTable==pScan->aEquiv[0]
  100590. && pX->iColumn==pScan->aEquiv[1]
  100591. ){
  100592. continue;
  100593. }
  100594. pScan->k = k+1;
  100595. return pTerm;
  100596. }
  100597. }
  100598. }
  100599. pScan->pWC = pScan->pWC->pOuter;
  100600. k = 0;
  100601. }
  100602. pScan->pWC = pScan->pOrigWC;
  100603. k = 0;
  100604. pScan->iEquiv += 2;
  100605. }
  100606. return 0;
  100607. }
  100608. /*
  100609. ** Initialize a WHERE clause scanner object. Return a pointer to the
  100610. ** first match. Return NULL if there are no matches.
  100611. **
  100612. ** The scanner will be searching the WHERE clause pWC. It will look
  100613. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  100614. ** iCur. The <op> must be one of the operators described by opMask.
  100615. **
  100616. ** If the search is for X and the WHERE clause contains terms of the
  100617. ** form X=Y then this routine might also return terms of the form
  100618. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  100619. ** but is enough to handle most commonly occurring SQL statements.
  100620. **
  100621. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  100622. ** index pIdx.
  100623. */
  100624. static WhereTerm *whereScanInit(
  100625. WhereScan *pScan, /* The WhereScan object being initialized */
  100626. WhereClause *pWC, /* The WHERE clause to be scanned */
  100627. int iCur, /* Cursor to scan for */
  100628. int iColumn, /* Column to scan for */
  100629. u32 opMask, /* Operator(s) to scan for */
  100630. Index *pIdx /* Must be compatible with this index */
  100631. ){
  100632. int j;
  100633. /* memset(pScan, 0, sizeof(*pScan)); */
  100634. pScan->pOrigWC = pWC;
  100635. pScan->pWC = pWC;
  100636. if( pIdx && iColumn>=0 ){
  100637. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  100638. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  100639. if( NEVER(j>=pIdx->nColumn) ) return 0;
  100640. }
  100641. pScan->zCollName = pIdx->azColl[j];
  100642. }else{
  100643. pScan->idxaff = 0;
  100644. pScan->zCollName = 0;
  100645. }
  100646. pScan->opMask = opMask;
  100647. pScan->k = 0;
  100648. pScan->aEquiv[0] = iCur;
  100649. pScan->aEquiv[1] = iColumn;
  100650. pScan->nEquiv = 2;
  100651. pScan->iEquiv = 2;
  100652. return whereScanNext(pScan);
  100653. }
  100654. /*
  100655. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  100656. ** where X is a reference to the iColumn of table iCur and <op> is one of
  100657. ** the WO_xx operator codes specified by the op parameter.
  100658. ** Return a pointer to the term. Return 0 if not found.
  100659. **
  100660. ** The term returned might by Y=<expr> if there is another constraint in
  100661. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  100662. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  100663. ** aEquiv[] array holds X and all its equivalents, with each SQL variable
  100664. ** taking up two slots in aEquiv[]. The first slot is for the cursor number
  100665. ** and the second is for the column number. There are 22 slots in aEquiv[]
  100666. ** so that means we can look for X plus up to 10 other equivalent values.
  100667. ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
  100668. ** and ... and A9=A10 and A10=<expr>.
  100669. **
  100670. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  100671. ** then try for the one with no dependencies on <expr> - in other words where
  100672. ** <expr> is a constant expression of some kind. Only return entries of
  100673. ** the form "X <op> Y" where Y is a column in another table if no terms of
  100674. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  100675. ** exist, try to return a term that does not use WO_EQUIV.
  100676. */
  100677. static WhereTerm *findTerm(
  100678. WhereClause *pWC, /* The WHERE clause to be searched */
  100679. int iCur, /* Cursor number of LHS */
  100680. int iColumn, /* Column number of LHS */
  100681. Bitmask notReady, /* RHS must not overlap with this mask */
  100682. u32 op, /* Mask of WO_xx values describing operator */
  100683. Index *pIdx /* Must be compatible with this index, if not NULL */
  100684. ){
  100685. WhereTerm *pResult = 0;
  100686. WhereTerm *p;
  100687. WhereScan scan;
  100688. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  100689. while( p ){
  100690. if( (p->prereqRight & notReady)==0 ){
  100691. if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
  100692. return p;
  100693. }
  100694. if( pResult==0 ) pResult = p;
  100695. }
  100696. p = whereScanNext(&scan);
  100697. }
  100698. return pResult;
  100699. }
  100700. /* Forward reference */
  100701. static void exprAnalyze(SrcList*, WhereClause*, int);
  100702. /*
  100703. ** Call exprAnalyze on all terms in a WHERE clause.
  100704. */
  100705. static void exprAnalyzeAll(
  100706. SrcList *pTabList, /* the FROM clause */
  100707. WhereClause *pWC /* the WHERE clause to be analyzed */
  100708. ){
  100709. int i;
  100710. for(i=pWC->nTerm-1; i>=0; i--){
  100711. exprAnalyze(pTabList, pWC, i);
  100712. }
  100713. }
  100714. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  100715. /*
  100716. ** Check to see if the given expression is a LIKE or GLOB operator that
  100717. ** can be optimized using inequality constraints. Return TRUE if it is
  100718. ** so and false if not.
  100719. **
  100720. ** In order for the operator to be optimizible, the RHS must be a string
  100721. ** literal that does not begin with a wildcard.
  100722. */
  100723. static int isLikeOrGlob(
  100724. Parse *pParse, /* Parsing and code generating context */
  100725. Expr *pExpr, /* Test this expression */
  100726. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  100727. int *pisComplete, /* True if the only wildcard is % in the last character */
  100728. int *pnoCase /* True if uppercase is equivalent to lowercase */
  100729. ){
  100730. const char *z = 0; /* String on RHS of LIKE operator */
  100731. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  100732. ExprList *pList; /* List of operands to the LIKE operator */
  100733. int c; /* One character in z[] */
  100734. int cnt; /* Number of non-wildcard prefix characters */
  100735. char wc[3]; /* Wildcard characters */
  100736. sqlite3 *db = pParse->db; /* Database connection */
  100737. sqlite3_value *pVal = 0;
  100738. int op; /* Opcode of pRight */
  100739. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  100740. return 0;
  100741. }
  100742. #ifdef SQLITE_EBCDIC
  100743. if( *pnoCase ) return 0;
  100744. #endif
  100745. pList = pExpr->x.pList;
  100746. pLeft = pList->a[1].pExpr;
  100747. if( pLeft->op!=TK_COLUMN
  100748. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  100749. || IsVirtual(pLeft->pTab)
  100750. ){
  100751. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  100752. ** be the name of an indexed column with TEXT affinity. */
  100753. return 0;
  100754. }
  100755. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  100756. pRight = pList->a[0].pExpr;
  100757. op = pRight->op;
  100758. if( op==TK_REGISTER ){
  100759. op = pRight->op2;
  100760. }
  100761. if( op==TK_VARIABLE ){
  100762. Vdbe *pReprepare = pParse->pReprepare;
  100763. int iCol = pRight->iColumn;
  100764. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
  100765. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  100766. z = (char *)sqlite3_value_text(pVal);
  100767. }
  100768. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  100769. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  100770. }else if( op==TK_STRING ){
  100771. z = pRight->u.zToken;
  100772. }
  100773. if( z ){
  100774. cnt = 0;
  100775. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  100776. cnt++;
  100777. }
  100778. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  100779. Expr *pPrefix;
  100780. *pisComplete = c==wc[0] && z[cnt+1]==0;
  100781. pPrefix = sqlite3Expr(db, TK_STRING, z);
  100782. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  100783. *ppPrefix = pPrefix;
  100784. if( op==TK_VARIABLE ){
  100785. Vdbe *v = pParse->pVdbe;
  100786. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  100787. if( *pisComplete && pRight->u.zToken[1] ){
  100788. /* If the rhs of the LIKE expression is a variable, and the current
  100789. ** value of the variable means there is no need to invoke the LIKE
  100790. ** function, then no OP_Variable will be added to the program.
  100791. ** This causes problems for the sqlite3_bind_parameter_name()
  100792. ** API. To workaround them, add a dummy OP_Variable here.
  100793. */
  100794. int r1 = sqlite3GetTempReg(pParse);
  100795. sqlite3ExprCodeTarget(pParse, pRight, r1);
  100796. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  100797. sqlite3ReleaseTempReg(pParse, r1);
  100798. }
  100799. }
  100800. }else{
  100801. z = 0;
  100802. }
  100803. }
  100804. sqlite3ValueFree(pVal);
  100805. return (z!=0);
  100806. }
  100807. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  100808. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100809. /*
  100810. ** Check to see if the given expression is of the form
  100811. **
  100812. ** column MATCH expr
  100813. **
  100814. ** If it is then return TRUE. If not, return FALSE.
  100815. */
  100816. static int isMatchOfColumn(
  100817. Expr *pExpr /* Test this expression */
  100818. ){
  100819. ExprList *pList;
  100820. if( pExpr->op!=TK_FUNCTION ){
  100821. return 0;
  100822. }
  100823. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  100824. return 0;
  100825. }
  100826. pList = pExpr->x.pList;
  100827. if( pList->nExpr!=2 ){
  100828. return 0;
  100829. }
  100830. if( pList->a[1].pExpr->op != TK_COLUMN ){
  100831. return 0;
  100832. }
  100833. return 1;
  100834. }
  100835. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  100836. /*
  100837. ** If the pBase expression originated in the ON or USING clause of
  100838. ** a join, then transfer the appropriate markings over to derived.
  100839. */
  100840. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  100841. if( pDerived ){
  100842. pDerived->flags |= pBase->flags & EP_FromJoin;
  100843. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  100844. }
  100845. }
  100846. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  100847. /*
  100848. ** Analyze a term that consists of two or more OR-connected
  100849. ** subterms. So in:
  100850. **
  100851. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  100852. ** ^^^^^^^^^^^^^^^^^^^^
  100853. **
  100854. ** This routine analyzes terms such as the middle term in the above example.
  100855. ** A WhereOrTerm object is computed and attached to the term under
  100856. ** analysis, regardless of the outcome of the analysis. Hence:
  100857. **
  100858. ** WhereTerm.wtFlags |= TERM_ORINFO
  100859. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  100860. **
  100861. ** The term being analyzed must have two or more of OR-connected subterms.
  100862. ** A single subterm might be a set of AND-connected sub-subterms.
  100863. ** Examples of terms under analysis:
  100864. **
  100865. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  100866. ** (B) x=expr1 OR expr2=x OR x=expr3
  100867. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  100868. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  100869. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  100870. **
  100871. ** CASE 1:
  100872. **
  100873. ** If all subterms are of the form T.C=expr for some single column of C and
  100874. ** a single table T (as shown in example B above) then create a new virtual
  100875. ** term that is an equivalent IN expression. In other words, if the term
  100876. ** being analyzed is:
  100877. **
  100878. ** x = expr1 OR expr2 = x OR x = expr3
  100879. **
  100880. ** then create a new virtual term like this:
  100881. **
  100882. ** x IN (expr1,expr2,expr3)
  100883. **
  100884. ** CASE 2:
  100885. **
  100886. ** If all subterms are indexable by a single table T, then set
  100887. **
  100888. ** WhereTerm.eOperator = WO_OR
  100889. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  100890. **
  100891. ** A subterm is "indexable" if it is of the form
  100892. ** "T.C <op> <expr>" where C is any column of table T and
  100893. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  100894. ** A subterm is also indexable if it is an AND of two or more
  100895. ** subsubterms at least one of which is indexable. Indexable AND
  100896. ** subterms have their eOperator set to WO_AND and they have
  100897. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  100898. **
  100899. ** From another point of view, "indexable" means that the subterm could
  100900. ** potentially be used with an index if an appropriate index exists.
  100901. ** This analysis does not consider whether or not the index exists; that
  100902. ** is decided elsewhere. This analysis only looks at whether subterms
  100903. ** appropriate for indexing exist.
  100904. **
  100905. ** All examples A through E above satisfy case 2. But if a term
  100906. ** also statisfies case 1 (such as B) we know that the optimizer will
  100907. ** always prefer case 1, so in that case we pretend that case 2 is not
  100908. ** satisfied.
  100909. **
  100910. ** It might be the case that multiple tables are indexable. For example,
  100911. ** (E) above is indexable on tables P, Q, and R.
  100912. **
  100913. ** Terms that satisfy case 2 are candidates for lookup by using
  100914. ** separate indices to find rowids for each subterm and composing
  100915. ** the union of all rowids using a RowSet object. This is similar
  100916. ** to "bitmap indices" in other database engines.
  100917. **
  100918. ** OTHERWISE:
  100919. **
  100920. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  100921. ** zero. This term is not useful for search.
  100922. */
  100923. static void exprAnalyzeOrTerm(
  100924. SrcList *pSrc, /* the FROM clause */
  100925. WhereClause *pWC, /* the complete WHERE clause */
  100926. int idxTerm /* Index of the OR-term to be analyzed */
  100927. ){
  100928. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  100929. Parse *pParse = pWInfo->pParse; /* Parser context */
  100930. sqlite3 *db = pParse->db; /* Database connection */
  100931. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  100932. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  100933. int i; /* Loop counters */
  100934. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  100935. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  100936. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  100937. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  100938. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  100939. /*
  100940. ** Break the OR clause into its separate subterms. The subterms are
  100941. ** stored in a WhereClause structure containing within the WhereOrInfo
  100942. ** object that is attached to the original OR clause term.
  100943. */
  100944. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  100945. assert( pExpr->op==TK_OR );
  100946. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  100947. if( pOrInfo==0 ) return;
  100948. pTerm->wtFlags |= TERM_ORINFO;
  100949. pOrWc = &pOrInfo->wc;
  100950. whereClauseInit(pOrWc, pWInfo);
  100951. whereSplit(pOrWc, pExpr, TK_OR);
  100952. exprAnalyzeAll(pSrc, pOrWc);
  100953. if( db->mallocFailed ) return;
  100954. assert( pOrWc->nTerm>=2 );
  100955. /*
  100956. ** Compute the set of tables that might satisfy cases 1 or 2.
  100957. */
  100958. indexable = ~(Bitmask)0;
  100959. chngToIN = ~(Bitmask)0;
  100960. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  100961. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  100962. WhereAndInfo *pAndInfo;
  100963. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  100964. chngToIN = 0;
  100965. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  100966. if( pAndInfo ){
  100967. WhereClause *pAndWC;
  100968. WhereTerm *pAndTerm;
  100969. int j;
  100970. Bitmask b = 0;
  100971. pOrTerm->u.pAndInfo = pAndInfo;
  100972. pOrTerm->wtFlags |= TERM_ANDINFO;
  100973. pOrTerm->eOperator = WO_AND;
  100974. pAndWC = &pAndInfo->wc;
  100975. whereClauseInit(pAndWC, pWC->pWInfo);
  100976. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  100977. exprAnalyzeAll(pSrc, pAndWC);
  100978. pAndWC->pOuter = pWC;
  100979. testcase( db->mallocFailed );
  100980. if( !db->mallocFailed ){
  100981. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  100982. assert( pAndTerm->pExpr );
  100983. if( allowedOp(pAndTerm->pExpr->op) ){
  100984. b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  100985. }
  100986. }
  100987. }
  100988. indexable &= b;
  100989. }
  100990. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  100991. /* Skip this term for now. We revisit it when we process the
  100992. ** corresponding TERM_VIRTUAL term */
  100993. }else{
  100994. Bitmask b;
  100995. b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  100996. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  100997. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  100998. b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
  100999. }
  101000. indexable &= b;
  101001. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  101002. chngToIN = 0;
  101003. }else{
  101004. chngToIN &= b;
  101005. }
  101006. }
  101007. }
  101008. /*
  101009. ** Record the set of tables that satisfy case 2. The set might be
  101010. ** empty.
  101011. */
  101012. pOrInfo->indexable = indexable;
  101013. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  101014. /*
  101015. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  101016. ** we have to do some additional checking to see if case 1 really
  101017. ** is satisfied.
  101018. **
  101019. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  101020. ** that there is no possibility of transforming the OR clause into an
  101021. ** IN operator because one or more terms in the OR clause contain
  101022. ** something other than == on a column in the single table. The 1-bit
  101023. ** case means that every term of the OR clause is of the form
  101024. ** "table.column=expr" for some single table. The one bit that is set
  101025. ** will correspond to the common table. We still need to check to make
  101026. ** sure the same column is used on all terms. The 2-bit case is when
  101027. ** the all terms are of the form "table1.column=table2.column". It
  101028. ** might be possible to form an IN operator with either table1.column
  101029. ** or table2.column as the LHS if either is common to every term of
  101030. ** the OR clause.
  101031. **
  101032. ** Note that terms of the form "table.column1=table.column2" (the
  101033. ** same table on both sizes of the ==) cannot be optimized.
  101034. */
  101035. if( chngToIN ){
  101036. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  101037. int iColumn = -1; /* Column index on lhs of IN operator */
  101038. int iCursor = -1; /* Table cursor common to all terms */
  101039. int j = 0; /* Loop counter */
  101040. /* Search for a table and column that appears on one side or the
  101041. ** other of the == operator in every subterm. That table and column
  101042. ** will be recorded in iCursor and iColumn. There might not be any
  101043. ** such table and column. Set okToChngToIN if an appropriate table
  101044. ** and column is found but leave okToChngToIN false if not found.
  101045. */
  101046. for(j=0; j<2 && !okToChngToIN; j++){
  101047. pOrTerm = pOrWc->a;
  101048. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  101049. assert( pOrTerm->eOperator & WO_EQ );
  101050. pOrTerm->wtFlags &= ~TERM_OR_OK;
  101051. if( pOrTerm->leftCursor==iCursor ){
  101052. /* This is the 2-bit case and we are on the second iteration and
  101053. ** current term is from the first iteration. So skip this term. */
  101054. assert( j==1 );
  101055. continue;
  101056. }
  101057. if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
  101058. /* This term must be of the form t1.a==t2.b where t2 is in the
  101059. ** chngToIN set but t1 is not. This term will be either preceeded
  101060. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  101061. ** and use its inversion. */
  101062. testcase( pOrTerm->wtFlags & TERM_COPIED );
  101063. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  101064. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  101065. continue;
  101066. }
  101067. iColumn = pOrTerm->u.leftColumn;
  101068. iCursor = pOrTerm->leftCursor;
  101069. break;
  101070. }
  101071. if( i<0 ){
  101072. /* No candidate table+column was found. This can only occur
  101073. ** on the second iteration */
  101074. assert( j==1 );
  101075. assert( IsPowerOfTwo(chngToIN) );
  101076. assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
  101077. break;
  101078. }
  101079. testcase( j==1 );
  101080. /* We have found a candidate table and column. Check to see if that
  101081. ** table and column is common to every term in the OR clause */
  101082. okToChngToIN = 1;
  101083. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  101084. assert( pOrTerm->eOperator & WO_EQ );
  101085. if( pOrTerm->leftCursor!=iCursor ){
  101086. pOrTerm->wtFlags &= ~TERM_OR_OK;
  101087. }else if( pOrTerm->u.leftColumn!=iColumn ){
  101088. okToChngToIN = 0;
  101089. }else{
  101090. int affLeft, affRight;
  101091. /* If the right-hand side is also a column, then the affinities
  101092. ** of both right and left sides must be such that no type
  101093. ** conversions are required on the right. (Ticket #2249)
  101094. */
  101095. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  101096. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  101097. if( affRight!=0 && affRight!=affLeft ){
  101098. okToChngToIN = 0;
  101099. }else{
  101100. pOrTerm->wtFlags |= TERM_OR_OK;
  101101. }
  101102. }
  101103. }
  101104. }
  101105. /* At this point, okToChngToIN is true if original pTerm satisfies
  101106. ** case 1. In that case, construct a new virtual term that is
  101107. ** pTerm converted into an IN operator.
  101108. */
  101109. if( okToChngToIN ){
  101110. Expr *pDup; /* A transient duplicate expression */
  101111. ExprList *pList = 0; /* The RHS of the IN operator */
  101112. Expr *pLeft = 0; /* The LHS of the IN operator */
  101113. Expr *pNew; /* The complete IN operator */
  101114. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  101115. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  101116. assert( pOrTerm->eOperator & WO_EQ );
  101117. assert( pOrTerm->leftCursor==iCursor );
  101118. assert( pOrTerm->u.leftColumn==iColumn );
  101119. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  101120. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  101121. pLeft = pOrTerm->pExpr->pLeft;
  101122. }
  101123. assert( pLeft!=0 );
  101124. pDup = sqlite3ExprDup(db, pLeft, 0);
  101125. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  101126. if( pNew ){
  101127. int idxNew;
  101128. transferJoinMarkings(pNew, pExpr);
  101129. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  101130. pNew->x.pList = pList;
  101131. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  101132. testcase( idxNew==0 );
  101133. exprAnalyze(pSrc, pWC, idxNew);
  101134. pTerm = &pWC->a[idxTerm];
  101135. pWC->a[idxNew].iParent = idxTerm;
  101136. pTerm->nChild = 1;
  101137. }else{
  101138. sqlite3ExprListDelete(db, pList);
  101139. }
  101140. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
  101141. }
  101142. }
  101143. }
  101144. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  101145. /*
  101146. ** The input to this routine is an WhereTerm structure with only the
  101147. ** "pExpr" field filled in. The job of this routine is to analyze the
  101148. ** subexpression and populate all the other fields of the WhereTerm
  101149. ** structure.
  101150. **
  101151. ** If the expression is of the form "<expr> <op> X" it gets commuted
  101152. ** to the standard form of "X <op> <expr>".
  101153. **
  101154. ** If the expression is of the form "X <op> Y" where both X and Y are
  101155. ** columns, then the original expression is unchanged and a new virtual
  101156. ** term of the form "Y <op> X" is added to the WHERE clause and
  101157. ** analyzed separately. The original term is marked with TERM_COPIED
  101158. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  101159. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  101160. ** is a commuted copy of a prior term.) The original term has nChild=1
  101161. ** and the copy has idxParent set to the index of the original term.
  101162. */
  101163. static void exprAnalyze(
  101164. SrcList *pSrc, /* the FROM clause */
  101165. WhereClause *pWC, /* the WHERE clause */
  101166. int idxTerm /* Index of the term to be analyzed */
  101167. ){
  101168. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  101169. WhereTerm *pTerm; /* The term to be analyzed */
  101170. WhereMaskSet *pMaskSet; /* Set of table index masks */
  101171. Expr *pExpr; /* The expression to be analyzed */
  101172. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  101173. Bitmask prereqAll; /* Prerequesites of pExpr */
  101174. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  101175. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  101176. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  101177. int noCase = 0; /* LIKE/GLOB distinguishes case */
  101178. int op; /* Top-level operator. pExpr->op */
  101179. Parse *pParse = pWInfo->pParse; /* Parsing context */
  101180. sqlite3 *db = pParse->db; /* Database connection */
  101181. if( db->mallocFailed ){
  101182. return;
  101183. }
  101184. pTerm = &pWC->a[idxTerm];
  101185. pMaskSet = &pWInfo->sMaskSet;
  101186. pExpr = pTerm->pExpr;
  101187. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  101188. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  101189. op = pExpr->op;
  101190. if( op==TK_IN ){
  101191. assert( pExpr->pRight==0 );
  101192. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  101193. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  101194. }else{
  101195. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  101196. }
  101197. }else if( op==TK_ISNULL ){
  101198. pTerm->prereqRight = 0;
  101199. }else{
  101200. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  101201. }
  101202. prereqAll = exprTableUsage(pMaskSet, pExpr);
  101203. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  101204. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  101205. prereqAll |= x;
  101206. extraRight = x-1; /* ON clause terms may not be used with an index
  101207. ** on left table of a LEFT JOIN. Ticket #3015 */
  101208. }
  101209. pTerm->prereqAll = prereqAll;
  101210. pTerm->leftCursor = -1;
  101211. pTerm->iParent = -1;
  101212. pTerm->eOperator = 0;
  101213. if( allowedOp(op) ){
  101214. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  101215. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  101216. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  101217. if( pLeft->op==TK_COLUMN ){
  101218. pTerm->leftCursor = pLeft->iTable;
  101219. pTerm->u.leftColumn = pLeft->iColumn;
  101220. pTerm->eOperator = operatorMask(op) & opMask;
  101221. }
  101222. if( pRight && pRight->op==TK_COLUMN ){
  101223. WhereTerm *pNew;
  101224. Expr *pDup;
  101225. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  101226. if( pTerm->leftCursor>=0 ){
  101227. int idxNew;
  101228. pDup = sqlite3ExprDup(db, pExpr, 0);
  101229. if( db->mallocFailed ){
  101230. sqlite3ExprDelete(db, pDup);
  101231. return;
  101232. }
  101233. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  101234. if( idxNew==0 ) return;
  101235. pNew = &pWC->a[idxNew];
  101236. pNew->iParent = idxTerm;
  101237. pTerm = &pWC->a[idxTerm];
  101238. pTerm->nChild = 1;
  101239. pTerm->wtFlags |= TERM_COPIED;
  101240. if( pExpr->op==TK_EQ
  101241. && !ExprHasProperty(pExpr, EP_FromJoin)
  101242. && OptimizationEnabled(db, SQLITE_Transitive)
  101243. ){
  101244. pTerm->eOperator |= WO_EQUIV;
  101245. eExtraOp = WO_EQUIV;
  101246. }
  101247. }else{
  101248. pDup = pExpr;
  101249. pNew = pTerm;
  101250. }
  101251. exprCommute(pParse, pDup);
  101252. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  101253. pNew->leftCursor = pLeft->iTable;
  101254. pNew->u.leftColumn = pLeft->iColumn;
  101255. testcase( (prereqLeft | extraRight) != prereqLeft );
  101256. pNew->prereqRight = prereqLeft | extraRight;
  101257. pNew->prereqAll = prereqAll;
  101258. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  101259. }
  101260. }
  101261. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  101262. /* If a term is the BETWEEN operator, create two new virtual terms
  101263. ** that define the range that the BETWEEN implements. For example:
  101264. **
  101265. ** a BETWEEN b AND c
  101266. **
  101267. ** is converted into:
  101268. **
  101269. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  101270. **
  101271. ** The two new terms are added onto the end of the WhereClause object.
  101272. ** The new terms are "dynamic" and are children of the original BETWEEN
  101273. ** term. That means that if the BETWEEN term is coded, the children are
  101274. ** skipped. Or, if the children are satisfied by an index, the original
  101275. ** BETWEEN term is skipped.
  101276. */
  101277. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  101278. ExprList *pList = pExpr->x.pList;
  101279. int i;
  101280. static const u8 ops[] = {TK_GE, TK_LE};
  101281. assert( pList!=0 );
  101282. assert( pList->nExpr==2 );
  101283. for(i=0; i<2; i++){
  101284. Expr *pNewExpr;
  101285. int idxNew;
  101286. pNewExpr = sqlite3PExpr(pParse, ops[i],
  101287. sqlite3ExprDup(db, pExpr->pLeft, 0),
  101288. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  101289. transferJoinMarkings(pNewExpr, pExpr);
  101290. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  101291. testcase( idxNew==0 );
  101292. exprAnalyze(pSrc, pWC, idxNew);
  101293. pTerm = &pWC->a[idxTerm];
  101294. pWC->a[idxNew].iParent = idxTerm;
  101295. }
  101296. pTerm->nChild = 2;
  101297. }
  101298. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  101299. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  101300. /* Analyze a term that is composed of two or more subterms connected by
  101301. ** an OR operator.
  101302. */
  101303. else if( pExpr->op==TK_OR ){
  101304. assert( pWC->op==TK_AND );
  101305. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  101306. pTerm = &pWC->a[idxTerm];
  101307. }
  101308. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  101309. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  101310. /* Add constraints to reduce the search space on a LIKE or GLOB
  101311. ** operator.
  101312. **
  101313. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  101314. **
  101315. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  101316. **
  101317. ** The last character of the prefix "abc" is incremented to form the
  101318. ** termination condition "abd".
  101319. */
  101320. if( pWC->op==TK_AND
  101321. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  101322. ){
  101323. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  101324. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  101325. Expr *pNewExpr1;
  101326. Expr *pNewExpr2;
  101327. int idxNew1;
  101328. int idxNew2;
  101329. Token sCollSeqName; /* Name of collating sequence */
  101330. pLeft = pExpr->x.pList->a[1].pExpr;
  101331. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  101332. if( !db->mallocFailed ){
  101333. u8 c, *pC; /* Last character before the first wildcard */
  101334. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  101335. c = *pC;
  101336. if( noCase ){
  101337. /* The point is to increment the last character before the first
  101338. ** wildcard. But if we increment '@', that will push it into the
  101339. ** alphabetic range where case conversions will mess up the
  101340. ** inequality. To avoid this, make sure to also run the full
  101341. ** LIKE on all candidate expressions by clearing the isComplete flag
  101342. */
  101343. if( c=='A'-1 ) isComplete = 0;
  101344. c = sqlite3UpperToLower[c];
  101345. }
  101346. *pC = c + 1;
  101347. }
  101348. sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
  101349. sCollSeqName.n = 6;
  101350. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  101351. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  101352. sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
  101353. pStr1, 0);
  101354. transferJoinMarkings(pNewExpr1, pExpr);
  101355. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  101356. testcase( idxNew1==0 );
  101357. exprAnalyze(pSrc, pWC, idxNew1);
  101358. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  101359. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  101360. sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
  101361. pStr2, 0);
  101362. transferJoinMarkings(pNewExpr2, pExpr);
  101363. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  101364. testcase( idxNew2==0 );
  101365. exprAnalyze(pSrc, pWC, idxNew2);
  101366. pTerm = &pWC->a[idxTerm];
  101367. if( isComplete ){
  101368. pWC->a[idxNew1].iParent = idxTerm;
  101369. pWC->a[idxNew2].iParent = idxTerm;
  101370. pTerm->nChild = 2;
  101371. }
  101372. }
  101373. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  101374. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101375. /* Add a WO_MATCH auxiliary term to the constraint set if the
  101376. ** current expression is of the form: column MATCH expr.
  101377. ** This information is used by the xBestIndex methods of
  101378. ** virtual tables. The native query optimizer does not attempt
  101379. ** to do anything with MATCH functions.
  101380. */
  101381. if( isMatchOfColumn(pExpr) ){
  101382. int idxNew;
  101383. Expr *pRight, *pLeft;
  101384. WhereTerm *pNewTerm;
  101385. Bitmask prereqColumn, prereqExpr;
  101386. pRight = pExpr->x.pList->a[0].pExpr;
  101387. pLeft = pExpr->x.pList->a[1].pExpr;
  101388. prereqExpr = exprTableUsage(pMaskSet, pRight);
  101389. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  101390. if( (prereqExpr & prereqColumn)==0 ){
  101391. Expr *pNewExpr;
  101392. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  101393. 0, sqlite3ExprDup(db, pRight, 0), 0);
  101394. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  101395. testcase( idxNew==0 );
  101396. pNewTerm = &pWC->a[idxNew];
  101397. pNewTerm->prereqRight = prereqExpr;
  101398. pNewTerm->leftCursor = pLeft->iTable;
  101399. pNewTerm->u.leftColumn = pLeft->iColumn;
  101400. pNewTerm->eOperator = WO_MATCH;
  101401. pNewTerm->iParent = idxTerm;
  101402. pTerm = &pWC->a[idxTerm];
  101403. pTerm->nChild = 1;
  101404. pTerm->wtFlags |= TERM_COPIED;
  101405. pNewTerm->prereqAll = pTerm->prereqAll;
  101406. }
  101407. }
  101408. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  101409. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  101410. /* When sqlite_stat3 histogram data is available an operator of the
  101411. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  101412. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  101413. ** virtual term of that form.
  101414. **
  101415. ** Note that the virtual term must be tagged with TERM_VNULL. This
  101416. ** TERM_VNULL tag will suppress the not-null check at the beginning
  101417. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  101418. ** the start of the loop will prevent any results from being returned.
  101419. */
  101420. if( pExpr->op==TK_NOTNULL
  101421. && pExpr->pLeft->op==TK_COLUMN
  101422. && pExpr->pLeft->iColumn>=0
  101423. && OptimizationEnabled(db, SQLITE_Stat3)
  101424. ){
  101425. Expr *pNewExpr;
  101426. Expr *pLeft = pExpr->pLeft;
  101427. int idxNew;
  101428. WhereTerm *pNewTerm;
  101429. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  101430. sqlite3ExprDup(db, pLeft, 0),
  101431. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  101432. idxNew = whereClauseInsert(pWC, pNewExpr,
  101433. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  101434. if( idxNew ){
  101435. pNewTerm = &pWC->a[idxNew];
  101436. pNewTerm->prereqRight = 0;
  101437. pNewTerm->leftCursor = pLeft->iTable;
  101438. pNewTerm->u.leftColumn = pLeft->iColumn;
  101439. pNewTerm->eOperator = WO_GT;
  101440. pNewTerm->iParent = idxTerm;
  101441. pTerm = &pWC->a[idxTerm];
  101442. pTerm->nChild = 1;
  101443. pTerm->wtFlags |= TERM_COPIED;
  101444. pNewTerm->prereqAll = pTerm->prereqAll;
  101445. }
  101446. }
  101447. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  101448. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  101449. ** an index for tables to the left of the join.
  101450. */
  101451. pTerm->prereqRight |= extraRight;
  101452. }
  101453. /*
  101454. ** This function searches pList for a entry that matches the iCol-th column
  101455. ** of index pIdx.
  101456. **
  101457. ** If such an expression is found, its index in pList->a[] is returned. If
  101458. ** no expression is found, -1 is returned.
  101459. */
  101460. static int findIndexCol(
  101461. Parse *pParse, /* Parse context */
  101462. ExprList *pList, /* Expression list to search */
  101463. int iBase, /* Cursor for table associated with pIdx */
  101464. Index *pIdx, /* Index to match column of */
  101465. int iCol /* Column of index to match */
  101466. ){
  101467. int i;
  101468. const char *zColl = pIdx->azColl[iCol];
  101469. for(i=0; i<pList->nExpr; i++){
  101470. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  101471. if( p->op==TK_COLUMN
  101472. && p->iColumn==pIdx->aiColumn[iCol]
  101473. && p->iTable==iBase
  101474. ){
  101475. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  101476. if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  101477. return i;
  101478. }
  101479. }
  101480. }
  101481. return -1;
  101482. }
  101483. /*
  101484. ** Return true if the DISTINCT expression-list passed as the third argument
  101485. ** is redundant.
  101486. **
  101487. ** A DISTINCT list is redundant if the database contains some subset of
  101488. ** columns that are unique and non-null.
  101489. */
  101490. static int isDistinctRedundant(
  101491. Parse *pParse, /* Parsing context */
  101492. SrcList *pTabList, /* The FROM clause */
  101493. WhereClause *pWC, /* The WHERE clause */
  101494. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  101495. ){
  101496. Table *pTab;
  101497. Index *pIdx;
  101498. int i;
  101499. int iBase;
  101500. /* If there is more than one table or sub-select in the FROM clause of
  101501. ** this query, then it will not be possible to show that the DISTINCT
  101502. ** clause is redundant. */
  101503. if( pTabList->nSrc!=1 ) return 0;
  101504. iBase = pTabList->a[0].iCursor;
  101505. pTab = pTabList->a[0].pTab;
  101506. /* If any of the expressions is an IPK column on table iBase, then return
  101507. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  101508. ** current SELECT is a correlated sub-query.
  101509. */
  101510. for(i=0; i<pDistinct->nExpr; i++){
  101511. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  101512. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  101513. }
  101514. /* Loop through all indices on the table, checking each to see if it makes
  101515. ** the DISTINCT qualifier redundant. It does so if:
  101516. **
  101517. ** 1. The index is itself UNIQUE, and
  101518. **
  101519. ** 2. All of the columns in the index are either part of the pDistinct
  101520. ** list, or else the WHERE clause contains a term of the form "col=X",
  101521. ** where X is a constant value. The collation sequences of the
  101522. ** comparison and select-list expressions must match those of the index.
  101523. **
  101524. ** 3. All of those index columns for which the WHERE clause does not
  101525. ** contain a "col=X" term are subject to a NOT NULL constraint.
  101526. */
  101527. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  101528. if( pIdx->onError==OE_None ) continue;
  101529. for(i=0; i<pIdx->nColumn; i++){
  101530. int iCol = pIdx->aiColumn[i];
  101531. if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  101532. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  101533. if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
  101534. break;
  101535. }
  101536. }
  101537. }
  101538. if( i==pIdx->nColumn ){
  101539. /* This index implies that the DISTINCT qualifier is redundant. */
  101540. return 1;
  101541. }
  101542. }
  101543. return 0;
  101544. }
  101545. /*
  101546. ** Estimate the logarithm of the input value to base 2.
  101547. */
  101548. static LogEst estLog(LogEst N){
  101549. LogEst x = sqlite3LogEst(N);
  101550. return x>33 ? x - 33 : 0;
  101551. }
  101552. /*
  101553. ** Two routines for printing the content of an sqlite3_index_info
  101554. ** structure. Used for testing and debugging only. If neither
  101555. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  101556. ** are no-ops.
  101557. */
  101558. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  101559. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  101560. int i;
  101561. if( !sqlite3WhereTrace ) return;
  101562. for(i=0; i<p->nConstraint; i++){
  101563. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  101564. i,
  101565. p->aConstraint[i].iColumn,
  101566. p->aConstraint[i].iTermOffset,
  101567. p->aConstraint[i].op,
  101568. p->aConstraint[i].usable);
  101569. }
  101570. for(i=0; i<p->nOrderBy; i++){
  101571. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  101572. i,
  101573. p->aOrderBy[i].iColumn,
  101574. p->aOrderBy[i].desc);
  101575. }
  101576. }
  101577. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  101578. int i;
  101579. if( !sqlite3WhereTrace ) return;
  101580. for(i=0; i<p->nConstraint; i++){
  101581. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  101582. i,
  101583. p->aConstraintUsage[i].argvIndex,
  101584. p->aConstraintUsage[i].omit);
  101585. }
  101586. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  101587. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  101588. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  101589. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  101590. }
  101591. #else
  101592. #define TRACE_IDX_INPUTS(A)
  101593. #define TRACE_IDX_OUTPUTS(A)
  101594. #endif
  101595. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  101596. /*
  101597. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  101598. ** could be used with an index to access pSrc, assuming an appropriate
  101599. ** index existed.
  101600. */
  101601. static int termCanDriveIndex(
  101602. WhereTerm *pTerm, /* WHERE clause term to check */
  101603. struct SrcList_item *pSrc, /* Table we are trying to access */
  101604. Bitmask notReady /* Tables in outer loops of the join */
  101605. ){
  101606. char aff;
  101607. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  101608. if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
  101609. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  101610. if( pTerm->u.leftColumn<0 ) return 0;
  101611. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  101612. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  101613. return 1;
  101614. }
  101615. #endif
  101616. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  101617. /*
  101618. ** Generate code to construct the Index object for an automatic index
  101619. ** and to set up the WhereLevel object pLevel so that the code generator
  101620. ** makes use of the automatic index.
  101621. */
  101622. static void constructAutomaticIndex(
  101623. Parse *pParse, /* The parsing context */
  101624. WhereClause *pWC, /* The WHERE clause */
  101625. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  101626. Bitmask notReady, /* Mask of cursors that are not available */
  101627. WhereLevel *pLevel /* Write new index here */
  101628. ){
  101629. int nColumn; /* Number of columns in the constructed index */
  101630. WhereTerm *pTerm; /* A single term of the WHERE clause */
  101631. WhereTerm *pWCEnd; /* End of pWC->a[] */
  101632. int nByte; /* Byte of memory needed for pIdx */
  101633. Index *pIdx; /* Object describing the transient index */
  101634. Vdbe *v; /* Prepared statement under construction */
  101635. int addrInit; /* Address of the initialization bypass jump */
  101636. Table *pTable; /* The table being indexed */
  101637. KeyInfo *pKeyinfo; /* Key information for the index */
  101638. int addrTop; /* Top of the index fill loop */
  101639. int regRecord; /* Register holding an index record */
  101640. int n; /* Column counter */
  101641. int i; /* Loop counter */
  101642. int mxBitCol; /* Maximum column in pSrc->colUsed */
  101643. CollSeq *pColl; /* Collating sequence to on a column */
  101644. WhereLoop *pLoop; /* The Loop object */
  101645. Bitmask idxCols; /* Bitmap of columns used for indexing */
  101646. Bitmask extraCols; /* Bitmap of additional columns */
  101647. u8 sentWarning = 0; /* True if a warnning has been issued */
  101648. /* Generate code to skip over the creation and initialization of the
  101649. ** transient index on 2nd and subsequent iterations of the loop. */
  101650. v = pParse->pVdbe;
  101651. assert( v!=0 );
  101652. addrInit = sqlite3CodeOnce(pParse);
  101653. /* Count the number of columns that will be added to the index
  101654. ** and used to match WHERE clause constraints */
  101655. nColumn = 0;
  101656. pTable = pSrc->pTab;
  101657. pWCEnd = &pWC->a[pWC->nTerm];
  101658. pLoop = pLevel->pWLoop;
  101659. idxCols = 0;
  101660. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  101661. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  101662. int iCol = pTerm->u.leftColumn;
  101663. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  101664. testcase( iCol==BMS );
  101665. testcase( iCol==BMS-1 );
  101666. if( !sentWarning ){
  101667. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  101668. "automatic index on %s(%s)", pTable->zName,
  101669. pTable->aCol[iCol].zName);
  101670. sentWarning = 1;
  101671. }
  101672. if( (idxCols & cMask)==0 ){
  101673. if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
  101674. pLoop->aLTerm[nColumn++] = pTerm;
  101675. idxCols |= cMask;
  101676. }
  101677. }
  101678. }
  101679. assert( nColumn>0 );
  101680. pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
  101681. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  101682. | WHERE_AUTO_INDEX;
  101683. /* Count the number of additional columns needed to create a
  101684. ** covering index. A "covering index" is an index that contains all
  101685. ** columns that are needed by the query. With a covering index, the
  101686. ** original table never needs to be accessed. Automatic indices must
  101687. ** be a covering index because the index will not be updated if the
  101688. ** original table changes and the index and table cannot both be used
  101689. ** if they go out of sync.
  101690. */
  101691. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  101692. mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
  101693. testcase( pTable->nCol==BMS-1 );
  101694. testcase( pTable->nCol==BMS-2 );
  101695. for(i=0; i<mxBitCol; i++){
  101696. if( extraCols & MASKBIT(i) ) nColumn++;
  101697. }
  101698. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  101699. nColumn += pTable->nCol - BMS + 1;
  101700. }
  101701. pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
  101702. /* Construct the Index object to describe this index */
  101703. nByte = sizeof(Index);
  101704. nByte += nColumn*sizeof(int); /* Index.aiColumn */
  101705. nByte += nColumn*sizeof(char*); /* Index.azColl */
  101706. nByte += nColumn; /* Index.aSortOrder */
  101707. pIdx = sqlite3DbMallocZero(pParse->db, nByte);
  101708. if( pIdx==0 ) return;
  101709. pLoop->u.btree.pIndex = pIdx;
  101710. pIdx->azColl = (char**)&pIdx[1];
  101711. pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
  101712. pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
  101713. pIdx->zName = "auto-index";
  101714. pIdx->nColumn = nColumn;
  101715. pIdx->pTable = pTable;
  101716. n = 0;
  101717. idxCols = 0;
  101718. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  101719. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  101720. int iCol = pTerm->u.leftColumn;
  101721. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  101722. testcase( iCol==BMS-1 );
  101723. testcase( iCol==BMS );
  101724. if( (idxCols & cMask)==0 ){
  101725. Expr *pX = pTerm->pExpr;
  101726. idxCols |= cMask;
  101727. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  101728. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  101729. pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
  101730. n++;
  101731. }
  101732. }
  101733. }
  101734. assert( (u32)n==pLoop->u.btree.nEq );
  101735. /* Add additional columns needed to make the automatic index into
  101736. ** a covering index */
  101737. for(i=0; i<mxBitCol; i++){
  101738. if( extraCols & MASKBIT(i) ){
  101739. pIdx->aiColumn[n] = i;
  101740. pIdx->azColl[n] = "BINARY";
  101741. n++;
  101742. }
  101743. }
  101744. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  101745. for(i=BMS-1; i<pTable->nCol; i++){
  101746. pIdx->aiColumn[n] = i;
  101747. pIdx->azColl[n] = "BINARY";
  101748. n++;
  101749. }
  101750. }
  101751. assert( n==nColumn );
  101752. /* Create the automatic index */
  101753. pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
  101754. assert( pLevel->iIdxCur>=0 );
  101755. pLevel->iIdxCur = pParse->nTab++;
  101756. sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
  101757. (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
  101758. VdbeComment((v, "for %s", pTable->zName));
  101759. /* Fill the automatic index with content */
  101760. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
  101761. regRecord = sqlite3GetTempReg(pParse);
  101762. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0);
  101763. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  101764. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  101765. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
  101766. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  101767. sqlite3VdbeJumpHere(v, addrTop);
  101768. sqlite3ReleaseTempReg(pParse, regRecord);
  101769. /* Jump here when skipping the initialization */
  101770. sqlite3VdbeJumpHere(v, addrInit);
  101771. }
  101772. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  101773. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101774. /*
  101775. ** Allocate and populate an sqlite3_index_info structure. It is the
  101776. ** responsibility of the caller to eventually release the structure
  101777. ** by passing the pointer returned by this function to sqlite3_free().
  101778. */
  101779. static sqlite3_index_info *allocateIndexInfo(
  101780. Parse *pParse,
  101781. WhereClause *pWC,
  101782. struct SrcList_item *pSrc,
  101783. ExprList *pOrderBy
  101784. ){
  101785. int i, j;
  101786. int nTerm;
  101787. struct sqlite3_index_constraint *pIdxCons;
  101788. struct sqlite3_index_orderby *pIdxOrderBy;
  101789. struct sqlite3_index_constraint_usage *pUsage;
  101790. WhereTerm *pTerm;
  101791. int nOrderBy;
  101792. sqlite3_index_info *pIdxInfo;
  101793. /* Count the number of possible WHERE clause constraints referring
  101794. ** to this virtual table */
  101795. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  101796. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  101797. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  101798. testcase( pTerm->eOperator & WO_IN );
  101799. testcase( pTerm->eOperator & WO_ISNULL );
  101800. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  101801. if( pTerm->wtFlags & TERM_VNULL ) continue;
  101802. nTerm++;
  101803. }
  101804. /* If the ORDER BY clause contains only columns in the current
  101805. ** virtual table then allocate space for the aOrderBy part of
  101806. ** the sqlite3_index_info structure.
  101807. */
  101808. nOrderBy = 0;
  101809. if( pOrderBy ){
  101810. int n = pOrderBy->nExpr;
  101811. for(i=0; i<n; i++){
  101812. Expr *pExpr = pOrderBy->a[i].pExpr;
  101813. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  101814. }
  101815. if( i==n){
  101816. nOrderBy = n;
  101817. }
  101818. }
  101819. /* Allocate the sqlite3_index_info structure
  101820. */
  101821. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  101822. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  101823. + sizeof(*pIdxOrderBy)*nOrderBy );
  101824. if( pIdxInfo==0 ){
  101825. sqlite3ErrorMsg(pParse, "out of memory");
  101826. return 0;
  101827. }
  101828. /* Initialize the structure. The sqlite3_index_info structure contains
  101829. ** many fields that are declared "const" to prevent xBestIndex from
  101830. ** changing them. We have to do some funky casting in order to
  101831. ** initialize those fields.
  101832. */
  101833. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  101834. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  101835. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  101836. *(int*)&pIdxInfo->nConstraint = nTerm;
  101837. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  101838. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  101839. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  101840. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  101841. pUsage;
  101842. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  101843. u8 op;
  101844. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  101845. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  101846. testcase( pTerm->eOperator & WO_IN );
  101847. testcase( pTerm->eOperator & WO_ISNULL );
  101848. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  101849. if( pTerm->wtFlags & TERM_VNULL ) continue;
  101850. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  101851. pIdxCons[j].iTermOffset = i;
  101852. op = (u8)pTerm->eOperator & WO_ALL;
  101853. if( op==WO_IN ) op = WO_EQ;
  101854. pIdxCons[j].op = op;
  101855. /* The direct assignment in the previous line is possible only because
  101856. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  101857. ** following asserts verify this fact. */
  101858. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  101859. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  101860. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  101861. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  101862. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  101863. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  101864. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  101865. j++;
  101866. }
  101867. for(i=0; i<nOrderBy; i++){
  101868. Expr *pExpr = pOrderBy->a[i].pExpr;
  101869. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  101870. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  101871. }
  101872. return pIdxInfo;
  101873. }
  101874. /*
  101875. ** The table object reference passed as the second argument to this function
  101876. ** must represent a virtual table. This function invokes the xBestIndex()
  101877. ** method of the virtual table with the sqlite3_index_info object that
  101878. ** comes in as the 3rd argument to this function.
  101879. **
  101880. ** If an error occurs, pParse is populated with an error message and a
  101881. ** non-zero value is returned. Otherwise, 0 is returned and the output
  101882. ** part of the sqlite3_index_info structure is left populated.
  101883. **
  101884. ** Whether or not an error is returned, it is the responsibility of the
  101885. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  101886. ** that this is required.
  101887. */
  101888. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  101889. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  101890. int i;
  101891. int rc;
  101892. TRACE_IDX_INPUTS(p);
  101893. rc = pVtab->pModule->xBestIndex(pVtab, p);
  101894. TRACE_IDX_OUTPUTS(p);
  101895. if( rc!=SQLITE_OK ){
  101896. if( rc==SQLITE_NOMEM ){
  101897. pParse->db->mallocFailed = 1;
  101898. }else if( !pVtab->zErrMsg ){
  101899. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  101900. }else{
  101901. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  101902. }
  101903. }
  101904. sqlite3_free(pVtab->zErrMsg);
  101905. pVtab->zErrMsg = 0;
  101906. for(i=0; i<p->nConstraint; i++){
  101907. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  101908. sqlite3ErrorMsg(pParse,
  101909. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  101910. }
  101911. }
  101912. return pParse->nErr;
  101913. }
  101914. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  101915. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  101916. /*
  101917. ** Estimate the location of a particular key among all keys in an
  101918. ** index. Store the results in aStat as follows:
  101919. **
  101920. ** aStat[0] Est. number of rows less than pVal
  101921. ** aStat[1] Est. number of rows equal to pVal
  101922. **
  101923. ** Return SQLITE_OK on success.
  101924. */
  101925. static void whereKeyStats(
  101926. Parse *pParse, /* Database connection */
  101927. Index *pIdx, /* Index to consider domain of */
  101928. UnpackedRecord *pRec, /* Vector of values to consider */
  101929. int roundUp, /* Round up if true. Round down if false */
  101930. tRowcnt *aStat /* OUT: stats written here */
  101931. ){
  101932. IndexSample *aSample = pIdx->aSample;
  101933. int iCol; /* Index of required stats in anEq[] etc. */
  101934. int iMin = 0; /* Smallest sample not yet tested */
  101935. int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
  101936. int iTest; /* Next sample to test */
  101937. int res; /* Result of comparison operation */
  101938. #ifndef SQLITE_DEBUG
  101939. UNUSED_PARAMETER( pParse );
  101940. #endif
  101941. assert( pRec!=0 || pParse->db->mallocFailed );
  101942. if( pRec==0 ) return;
  101943. iCol = pRec->nField - 1;
  101944. assert( pIdx->nSample>0 );
  101945. assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
  101946. do{
  101947. iTest = (iMin+i)/2;
  101948. res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
  101949. if( res<0 ){
  101950. iMin = iTest+1;
  101951. }else{
  101952. i = iTest;
  101953. }
  101954. }while( res && iMin<i );
  101955. #ifdef SQLITE_DEBUG
  101956. /* The following assert statements check that the binary search code
  101957. ** above found the right answer. This block serves no purpose other
  101958. ** than to invoke the asserts. */
  101959. if( res==0 ){
  101960. /* If (res==0) is true, then sample $i must be equal to pRec */
  101961. assert( i<pIdx->nSample );
  101962. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  101963. || pParse->db->mallocFailed );
  101964. }else{
  101965. /* Otherwise, pRec must be smaller than sample $i and larger than
  101966. ** sample ($i-1). */
  101967. assert( i==pIdx->nSample
  101968. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  101969. || pParse->db->mallocFailed );
  101970. assert( i==0
  101971. || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  101972. || pParse->db->mallocFailed );
  101973. }
  101974. #endif /* ifdef SQLITE_DEBUG */
  101975. /* At this point, aSample[i] is the first sample that is greater than
  101976. ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
  101977. ** than pVal. If aSample[i]==pVal, then res==0.
  101978. */
  101979. if( res==0 ){
  101980. aStat[0] = aSample[i].anLt[iCol];
  101981. aStat[1] = aSample[i].anEq[iCol];
  101982. }else{
  101983. tRowcnt iLower, iUpper, iGap;
  101984. if( i==0 ){
  101985. iLower = 0;
  101986. iUpper = aSample[0].anLt[iCol];
  101987. }else{
  101988. iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
  101989. iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
  101990. }
  101991. aStat[1] = (pIdx->nColumn>iCol ? pIdx->aAvgEq[iCol] : 1);
  101992. if( iLower>=iUpper ){
  101993. iGap = 0;
  101994. }else{
  101995. iGap = iUpper - iLower;
  101996. }
  101997. if( roundUp ){
  101998. iGap = (iGap*2)/3;
  101999. }else{
  102000. iGap = iGap/3;
  102001. }
  102002. aStat[0] = iLower + iGap;
  102003. }
  102004. }
  102005. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  102006. /*
  102007. ** This function is used to estimate the number of rows that will be visited
  102008. ** by scanning an index for a range of values. The range may have an upper
  102009. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  102010. ** and lower bounds are represented by pLower and pUpper respectively. For
  102011. ** example, assuming that index p is on t1(a):
  102012. **
  102013. ** ... FROM t1 WHERE a > ? AND a < ? ...
  102014. ** |_____| |_____|
  102015. ** | |
  102016. ** pLower pUpper
  102017. **
  102018. ** If either of the upper or lower bound is not present, then NULL is passed in
  102019. ** place of the corresponding WhereTerm.
  102020. **
  102021. ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
  102022. ** column subject to the range constraint. Or, equivalently, the number of
  102023. ** equality constraints optimized by the proposed index scan. For example,
  102024. ** assuming index p is on t1(a, b), and the SQL query is:
  102025. **
  102026. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  102027. **
  102028. ** then nEq is set to 1 (as the range restricted column, b, is the second
  102029. ** left-most column of the index). Or, if the query is:
  102030. **
  102031. ** ... FROM t1 WHERE a > ? AND a < ? ...
  102032. **
  102033. ** then nEq is set to 0.
  102034. **
  102035. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  102036. ** number of rows that the index scan is expected to visit without
  102037. ** considering the range constraints. If nEq is 0, this is the number of
  102038. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  102039. ** to account for the range contraints pLower and pUpper.
  102040. **
  102041. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  102042. ** used, each range inequality reduces the search space by a factor of 4.
  102043. ** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
  102044. ** rows visited by a factor of 16.
  102045. */
  102046. static int whereRangeScanEst(
  102047. Parse *pParse, /* Parsing & code generating context */
  102048. WhereLoopBuilder *pBuilder,
  102049. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  102050. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  102051. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  102052. ){
  102053. int rc = SQLITE_OK;
  102054. int nOut = pLoop->nOut;
  102055. LogEst nNew;
  102056. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  102057. Index *p = pLoop->u.btree.pIndex;
  102058. int nEq = pLoop->u.btree.nEq;
  102059. if( p->nSample>0
  102060. && nEq==pBuilder->nRecValid
  102061. && nEq<p->nSampleCol
  102062. && OptimizationEnabled(pParse->db, SQLITE_Stat3)
  102063. ){
  102064. UnpackedRecord *pRec = pBuilder->pRec;
  102065. tRowcnt a[2];
  102066. u8 aff;
  102067. /* Variable iLower will be set to the estimate of the number of rows in
  102068. ** the index that are less than the lower bound of the range query. The
  102069. ** lower bound being the concatenation of $P and $L, where $P is the
  102070. ** key-prefix formed by the nEq values matched against the nEq left-most
  102071. ** columns of the index, and $L is the value in pLower.
  102072. **
  102073. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  102074. ** is not a simple variable or literal value), the lower bound of the
  102075. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  102076. ** if $L is available, whereKeyStats() is called for both ($P) and
  102077. ** ($P:$L) and the larger of the two returned values used.
  102078. **
  102079. ** Similarly, iUpper is to be set to the estimate of the number of rows
  102080. ** less than the upper bound of the range query. Where the upper bound
  102081. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  102082. ** of iUpper are requested of whereKeyStats() and the smaller used.
  102083. */
  102084. tRowcnt iLower;
  102085. tRowcnt iUpper;
  102086. if( nEq==p->nColumn ){
  102087. aff = SQLITE_AFF_INTEGER;
  102088. }else{
  102089. aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
  102090. }
  102091. /* Determine iLower and iUpper using ($P) only. */
  102092. if( nEq==0 ){
  102093. iLower = 0;
  102094. iUpper = p->aiRowEst[0];
  102095. }else{
  102096. /* Note: this call could be optimized away - since the same values must
  102097. ** have been requested when testing key $P in whereEqualScanEst(). */
  102098. whereKeyStats(pParse, p, pRec, 0, a);
  102099. iLower = a[0];
  102100. iUpper = a[0] + a[1];
  102101. }
  102102. /* If possible, improve on the iLower estimate using ($P:$L). */
  102103. if( pLower ){
  102104. int bOk; /* True if value is extracted from pExpr */
  102105. Expr *pExpr = pLower->pExpr->pRight;
  102106. assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  102107. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  102108. if( rc==SQLITE_OK && bOk ){
  102109. tRowcnt iNew;
  102110. whereKeyStats(pParse, p, pRec, 0, a);
  102111. iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
  102112. if( iNew>iLower ) iLower = iNew;
  102113. nOut--;
  102114. }
  102115. }
  102116. /* If possible, improve on the iUpper estimate using ($P:$U). */
  102117. if( pUpper ){
  102118. int bOk; /* True if value is extracted from pExpr */
  102119. Expr *pExpr = pUpper->pExpr->pRight;
  102120. assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  102121. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  102122. if( rc==SQLITE_OK && bOk ){
  102123. tRowcnt iNew;
  102124. whereKeyStats(pParse, p, pRec, 1, a);
  102125. iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
  102126. if( iNew<iUpper ) iUpper = iNew;
  102127. nOut--;
  102128. }
  102129. }
  102130. pBuilder->pRec = pRec;
  102131. if( rc==SQLITE_OK ){
  102132. if( iUpper>iLower ){
  102133. nNew = sqlite3LogEst(iUpper - iLower);
  102134. }else{
  102135. nNew = 10; assert( 10==sqlite3LogEst(2) );
  102136. }
  102137. if( nNew<nOut ){
  102138. nOut = nNew;
  102139. }
  102140. pLoop->nOut = (LogEst)nOut;
  102141. WHERETRACE(0x100, ("range scan regions: %u..%u est=%d\n",
  102142. (u32)iLower, (u32)iUpper, nOut));
  102143. return SQLITE_OK;
  102144. }
  102145. }
  102146. #else
  102147. UNUSED_PARAMETER(pParse);
  102148. UNUSED_PARAMETER(pBuilder);
  102149. #endif
  102150. assert( pLower || pUpper );
  102151. /* TUNING: Each inequality constraint reduces the search space 4-fold.
  102152. ** A BETWEEN operator, therefore, reduces the search space 16-fold */
  102153. nNew = nOut;
  102154. if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
  102155. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  102156. nOut--;
  102157. }
  102158. if( pUpper ){
  102159. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  102160. nOut--;
  102161. }
  102162. if( nNew<10 ) nNew = 10;
  102163. if( nNew<nOut ) nOut = nNew;
  102164. pLoop->nOut = (LogEst)nOut;
  102165. return rc;
  102166. }
  102167. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  102168. /*
  102169. ** Estimate the number of rows that will be returned based on
  102170. ** an equality constraint x=VALUE and where that VALUE occurs in
  102171. ** the histogram data. This only works when x is the left-most
  102172. ** column of an index and sqlite_stat3 histogram data is available
  102173. ** for that index. When pExpr==NULL that means the constraint is
  102174. ** "x IS NULL" instead of "x=VALUE".
  102175. **
  102176. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  102177. ** If unable to make an estimate, leave *pnRow unchanged and return
  102178. ** non-zero.
  102179. **
  102180. ** This routine can fail if it is unable to load a collating sequence
  102181. ** required for string comparison, or if unable to allocate memory
  102182. ** for a UTF conversion required for comparison. The error is stored
  102183. ** in the pParse structure.
  102184. */
  102185. static int whereEqualScanEst(
  102186. Parse *pParse, /* Parsing & code generating context */
  102187. WhereLoopBuilder *pBuilder,
  102188. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  102189. tRowcnt *pnRow /* Write the revised row estimate here */
  102190. ){
  102191. Index *p = pBuilder->pNew->u.btree.pIndex;
  102192. int nEq = pBuilder->pNew->u.btree.nEq;
  102193. UnpackedRecord *pRec = pBuilder->pRec;
  102194. u8 aff; /* Column affinity */
  102195. int rc; /* Subfunction return code */
  102196. tRowcnt a[2]; /* Statistics */
  102197. int bOk;
  102198. assert( nEq>=1 );
  102199. assert( nEq<=(p->nColumn+1) );
  102200. assert( p->aSample!=0 );
  102201. assert( p->nSample>0 );
  102202. assert( pBuilder->nRecValid<nEq );
  102203. /* If values are not available for all fields of the index to the left
  102204. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  102205. if( pBuilder->nRecValid<(nEq-1) ){
  102206. return SQLITE_NOTFOUND;
  102207. }
  102208. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  102209. ** below would return the same value. */
  102210. if( nEq>p->nColumn ){
  102211. *pnRow = 1;
  102212. return SQLITE_OK;
  102213. }
  102214. aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
  102215. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  102216. pBuilder->pRec = pRec;
  102217. if( rc!=SQLITE_OK ) return rc;
  102218. if( bOk==0 ) return SQLITE_NOTFOUND;
  102219. pBuilder->nRecValid = nEq;
  102220. whereKeyStats(pParse, p, pRec, 0, a);
  102221. WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
  102222. *pnRow = a[1];
  102223. return rc;
  102224. }
  102225. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  102226. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  102227. /*
  102228. ** Estimate the number of rows that will be returned based on
  102229. ** an IN constraint where the right-hand side of the IN operator
  102230. ** is a list of values. Example:
  102231. **
  102232. ** WHERE x IN (1,2,3,4)
  102233. **
  102234. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  102235. ** If unable to make an estimate, leave *pnRow unchanged and return
  102236. ** non-zero.
  102237. **
  102238. ** This routine can fail if it is unable to load a collating sequence
  102239. ** required for string comparison, or if unable to allocate memory
  102240. ** for a UTF conversion required for comparison. The error is stored
  102241. ** in the pParse structure.
  102242. */
  102243. static int whereInScanEst(
  102244. Parse *pParse, /* Parsing & code generating context */
  102245. WhereLoopBuilder *pBuilder,
  102246. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  102247. tRowcnt *pnRow /* Write the revised row estimate here */
  102248. ){
  102249. Index *p = pBuilder->pNew->u.btree.pIndex;
  102250. int nRecValid = pBuilder->nRecValid;
  102251. int rc = SQLITE_OK; /* Subfunction return code */
  102252. tRowcnt nEst; /* Number of rows for a single term */
  102253. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  102254. int i; /* Loop counter */
  102255. assert( p->aSample!=0 );
  102256. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  102257. nEst = p->aiRowEst[0];
  102258. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  102259. nRowEst += nEst;
  102260. pBuilder->nRecValid = nRecValid;
  102261. }
  102262. if( rc==SQLITE_OK ){
  102263. if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
  102264. *pnRow = nRowEst;
  102265. WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
  102266. }
  102267. assert( pBuilder->nRecValid==nRecValid );
  102268. return rc;
  102269. }
  102270. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  102271. /*
  102272. ** Disable a term in the WHERE clause. Except, do not disable the term
  102273. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  102274. ** or USING clause of that join.
  102275. **
  102276. ** Consider the term t2.z='ok' in the following queries:
  102277. **
  102278. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  102279. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  102280. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  102281. **
  102282. ** The t2.z='ok' is disabled in the in (2) because it originates
  102283. ** in the ON clause. The term is disabled in (3) because it is not part
  102284. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  102285. **
  102286. ** Disabling a term causes that term to not be tested in the inner loop
  102287. ** of the join. Disabling is an optimization. When terms are satisfied
  102288. ** by indices, we disable them to prevent redundant tests in the inner
  102289. ** loop. We would get the correct results if nothing were ever disabled,
  102290. ** but joins might run a little slower. The trick is to disable as much
  102291. ** as we can without disabling too much. If we disabled in (1), we'd get
  102292. ** the wrong answer. See ticket #813.
  102293. */
  102294. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  102295. if( pTerm
  102296. && (pTerm->wtFlags & TERM_CODED)==0
  102297. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  102298. && (pLevel->notReady & pTerm->prereqAll)==0
  102299. ){
  102300. pTerm->wtFlags |= TERM_CODED;
  102301. if( pTerm->iParent>=0 ){
  102302. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  102303. if( (--pOther->nChild)==0 ){
  102304. disableTerm(pLevel, pOther);
  102305. }
  102306. }
  102307. }
  102308. }
  102309. /*
  102310. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  102311. ** to the n registers starting at base.
  102312. **
  102313. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  102314. ** beginning and end of zAff are ignored. If all entries in zAff are
  102315. ** SQLITE_AFF_NONE, then no code gets generated.
  102316. **
  102317. ** This routine makes its own copy of zAff so that the caller is free
  102318. ** to modify zAff after this routine returns.
  102319. */
  102320. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  102321. Vdbe *v = pParse->pVdbe;
  102322. if( zAff==0 ){
  102323. assert( pParse->db->mallocFailed );
  102324. return;
  102325. }
  102326. assert( v!=0 );
  102327. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  102328. ** and end of the affinity string.
  102329. */
  102330. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  102331. n--;
  102332. base++;
  102333. zAff++;
  102334. }
  102335. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  102336. n--;
  102337. }
  102338. /* Code the OP_Affinity opcode if there is anything left to do. */
  102339. if( n>0 ){
  102340. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  102341. sqlite3VdbeChangeP4(v, -1, zAff, n);
  102342. sqlite3ExprCacheAffinityChange(pParse, base, n);
  102343. }
  102344. }
  102345. /*
  102346. ** Generate code for a single equality term of the WHERE clause. An equality
  102347. ** term can be either X=expr or X IN (...). pTerm is the term to be
  102348. ** coded.
  102349. **
  102350. ** The current value for the constraint is left in register iReg.
  102351. **
  102352. ** For a constraint of the form X=expr, the expression is evaluated and its
  102353. ** result is left on the stack. For constraints of the form X IN (...)
  102354. ** this routine sets up a loop that will iterate over all values of X.
  102355. */
  102356. static int codeEqualityTerm(
  102357. Parse *pParse, /* The parsing context */
  102358. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  102359. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  102360. int iEq, /* Index of the equality term within this level */
  102361. int bRev, /* True for reverse-order IN operations */
  102362. int iTarget /* Attempt to leave results in this register */
  102363. ){
  102364. Expr *pX = pTerm->pExpr;
  102365. Vdbe *v = pParse->pVdbe;
  102366. int iReg; /* Register holding results */
  102367. assert( iTarget>0 );
  102368. if( pX->op==TK_EQ ){
  102369. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  102370. }else if( pX->op==TK_ISNULL ){
  102371. iReg = iTarget;
  102372. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  102373. #ifndef SQLITE_OMIT_SUBQUERY
  102374. }else{
  102375. int eType;
  102376. int iTab;
  102377. struct InLoop *pIn;
  102378. WhereLoop *pLoop = pLevel->pWLoop;
  102379. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  102380. && pLoop->u.btree.pIndex!=0
  102381. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  102382. ){
  102383. testcase( iEq==0 );
  102384. testcase( bRev );
  102385. bRev = !bRev;
  102386. }
  102387. assert( pX->op==TK_IN );
  102388. iReg = iTarget;
  102389. eType = sqlite3FindInIndex(pParse, pX, 0);
  102390. if( eType==IN_INDEX_INDEX_DESC ){
  102391. testcase( bRev );
  102392. bRev = !bRev;
  102393. }
  102394. iTab = pX->iTable;
  102395. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  102396. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  102397. pLoop->wsFlags |= WHERE_IN_ABLE;
  102398. if( pLevel->u.in.nIn==0 ){
  102399. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  102400. }
  102401. pLevel->u.in.nIn++;
  102402. pLevel->u.in.aInLoop =
  102403. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  102404. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  102405. pIn = pLevel->u.in.aInLoop;
  102406. if( pIn ){
  102407. pIn += pLevel->u.in.nIn - 1;
  102408. pIn->iCur = iTab;
  102409. if( eType==IN_INDEX_ROWID ){
  102410. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  102411. }else{
  102412. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  102413. }
  102414. pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
  102415. sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
  102416. }else{
  102417. pLevel->u.in.nIn = 0;
  102418. }
  102419. #endif
  102420. }
  102421. disableTerm(pLevel, pTerm);
  102422. return iReg;
  102423. }
  102424. /*
  102425. ** Generate code that will evaluate all == and IN constraints for an
  102426. ** index.
  102427. **
  102428. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  102429. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  102430. ** The index has as many as three equality constraints, but in this
  102431. ** example, the third "c" value is an inequality. So only two
  102432. ** constraints are coded. This routine will generate code to evaluate
  102433. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  102434. ** in consecutive registers and the index of the first register is returned.
  102435. **
  102436. ** In the example above nEq==2. But this subroutine works for any value
  102437. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  102438. ** The only thing it does is allocate the pLevel->iMem memory cell and
  102439. ** compute the affinity string.
  102440. **
  102441. ** This routine always allocates at least one memory cell and returns
  102442. ** the index of that memory cell. The code that
  102443. ** calls this routine will use that memory cell to store the termination
  102444. ** key value of the loop. If one or more IN operators appear, then
  102445. ** this routine allocates an additional nEq memory cells for internal
  102446. ** use.
  102447. **
  102448. ** Before returning, *pzAff is set to point to a buffer containing a
  102449. ** copy of the column affinity string of the index allocated using
  102450. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  102451. ** with equality constraints that use NONE affinity are set to
  102452. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  102453. **
  102454. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  102455. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  102456. **
  102457. ** In the example above, the index on t1(a) has TEXT affinity. But since
  102458. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  102459. ** no conversion should be attempted before using a t2.b value as part of
  102460. ** a key to search the index. Hence the first byte in the returned affinity
  102461. ** string in this example would be set to SQLITE_AFF_NONE.
  102462. */
  102463. static int codeAllEqualityTerms(
  102464. Parse *pParse, /* Parsing context */
  102465. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  102466. int bRev, /* Reverse the order of IN operators */
  102467. int nExtraReg, /* Number of extra registers to allocate */
  102468. char **pzAff /* OUT: Set to point to affinity string */
  102469. ){
  102470. int nEq; /* The number of == or IN constraints to code */
  102471. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  102472. Index *pIdx; /* The index being used for this loop */
  102473. WhereTerm *pTerm; /* A single constraint term */
  102474. WhereLoop *pLoop; /* The WhereLoop object */
  102475. int j; /* Loop counter */
  102476. int regBase; /* Base register */
  102477. int nReg; /* Number of registers to allocate */
  102478. char *zAff; /* Affinity string to return */
  102479. /* This module is only called on query plans that use an index. */
  102480. pLoop = pLevel->pWLoop;
  102481. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  102482. nEq = pLoop->u.btree.nEq;
  102483. pIdx = pLoop->u.btree.pIndex;
  102484. assert( pIdx!=0 );
  102485. /* Figure out how many memory cells we will need then allocate them.
  102486. */
  102487. regBase = pParse->nMem + 1;
  102488. nReg = pLoop->u.btree.nEq + nExtraReg;
  102489. pParse->nMem += nReg;
  102490. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  102491. if( !zAff ){
  102492. pParse->db->mallocFailed = 1;
  102493. }
  102494. /* Evaluate the equality constraints
  102495. */
  102496. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  102497. for(j=0; j<nEq; j++){
  102498. int r1;
  102499. pTerm = pLoop->aLTerm[j];
  102500. assert( pTerm!=0 );
  102501. /* The following true for indices with redundant columns.
  102502. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  102503. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  102504. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  102505. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  102506. if( r1!=regBase+j ){
  102507. if( nReg==1 ){
  102508. sqlite3ReleaseTempReg(pParse, regBase);
  102509. regBase = r1;
  102510. }else{
  102511. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  102512. }
  102513. }
  102514. testcase( pTerm->eOperator & WO_ISNULL );
  102515. testcase( pTerm->eOperator & WO_IN );
  102516. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  102517. Expr *pRight = pTerm->pExpr->pRight;
  102518. sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
  102519. if( zAff ){
  102520. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  102521. zAff[j] = SQLITE_AFF_NONE;
  102522. }
  102523. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  102524. zAff[j] = SQLITE_AFF_NONE;
  102525. }
  102526. }
  102527. }
  102528. }
  102529. *pzAff = zAff;
  102530. return regBase;
  102531. }
  102532. #ifndef SQLITE_OMIT_EXPLAIN
  102533. /*
  102534. ** This routine is a helper for explainIndexRange() below
  102535. **
  102536. ** pStr holds the text of an expression that we are building up one term
  102537. ** at a time. This routine adds a new term to the end of the expression.
  102538. ** Terms are separated by AND so add the "AND" text for second and subsequent
  102539. ** terms only.
  102540. */
  102541. static void explainAppendTerm(
  102542. StrAccum *pStr, /* The text expression being built */
  102543. int iTerm, /* Index of this term. First is zero */
  102544. const char *zColumn, /* Name of the column */
  102545. const char *zOp /* Name of the operator */
  102546. ){
  102547. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  102548. sqlite3StrAccumAppend(pStr, zColumn, -1);
  102549. sqlite3StrAccumAppend(pStr, zOp, 1);
  102550. sqlite3StrAccumAppend(pStr, "?", 1);
  102551. }
  102552. /*
  102553. ** Argument pLevel describes a strategy for scanning table pTab. This
  102554. ** function returns a pointer to a string buffer containing a description
  102555. ** of the subset of table rows scanned by the strategy in the form of an
  102556. ** SQL expression. Or, if all rows are scanned, NULL is returned.
  102557. **
  102558. ** For example, if the query:
  102559. **
  102560. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  102561. **
  102562. ** is run and there is an index on (a, b), then this function returns a
  102563. ** string similar to:
  102564. **
  102565. ** "a=? AND b>?"
  102566. **
  102567. ** The returned pointer points to memory obtained from sqlite3DbMalloc().
  102568. ** It is the responsibility of the caller to free the buffer when it is
  102569. ** no longer required.
  102570. */
  102571. static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
  102572. Index *pIndex = pLoop->u.btree.pIndex;
  102573. int nEq = pLoop->u.btree.nEq;
  102574. int i, j;
  102575. Column *aCol = pTab->aCol;
  102576. int *aiColumn = pIndex->aiColumn;
  102577. StrAccum txt;
  102578. if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
  102579. return 0;
  102580. }
  102581. sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
  102582. txt.db = db;
  102583. sqlite3StrAccumAppend(&txt, " (", 2);
  102584. for(i=0; i<nEq; i++){
  102585. char *z = (i==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[i]].zName;
  102586. explainAppendTerm(&txt, i, z, "=");
  102587. }
  102588. j = i;
  102589. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  102590. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  102591. explainAppendTerm(&txt, i++, z, ">");
  102592. }
  102593. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  102594. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  102595. explainAppendTerm(&txt, i, z, "<");
  102596. }
  102597. sqlite3StrAccumAppend(&txt, ")", 1);
  102598. return sqlite3StrAccumFinish(&txt);
  102599. }
  102600. /*
  102601. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  102602. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  102603. ** record is added to the output to describe the table scan strategy in
  102604. ** pLevel.
  102605. */
  102606. static void explainOneScan(
  102607. Parse *pParse, /* Parse context */
  102608. SrcList *pTabList, /* Table list this loop refers to */
  102609. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  102610. int iLevel, /* Value for "level" column of output */
  102611. int iFrom, /* Value for "from" column of output */
  102612. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  102613. ){
  102614. if( pParse->explain==2 ){
  102615. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  102616. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  102617. sqlite3 *db = pParse->db; /* Database handle */
  102618. char *zMsg; /* Text to add to EQP output */
  102619. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  102620. int isSearch; /* True for a SEARCH. False for SCAN. */
  102621. WhereLoop *pLoop; /* The controlling WhereLoop object */
  102622. u32 flags; /* Flags that describe this loop */
  102623. pLoop = pLevel->pWLoop;
  102624. flags = pLoop->wsFlags;
  102625. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
  102626. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  102627. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  102628. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  102629. zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
  102630. if( pItem->pSelect ){
  102631. zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
  102632. }else{
  102633. zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
  102634. }
  102635. if( pItem->zAlias ){
  102636. zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
  102637. }
  102638. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
  102639. && ALWAYS(pLoop->u.btree.pIndex!=0)
  102640. ){
  102641. char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
  102642. zMsg = sqlite3MAppendf(db, zMsg,
  102643. ((flags & WHERE_AUTO_INDEX) ?
  102644. "%s USING AUTOMATIC %sINDEX%.0s%s" :
  102645. "%s USING %sINDEX %s%s"),
  102646. zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
  102647. pLoop->u.btree.pIndex->zName, zWhere);
  102648. sqlite3DbFree(db, zWhere);
  102649. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  102650. zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
  102651. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  102652. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
  102653. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  102654. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
  102655. }else if( flags&WHERE_BTM_LIMIT ){
  102656. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
  102657. }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
  102658. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
  102659. }
  102660. }
  102661. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102662. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  102663. zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
  102664. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  102665. }
  102666. #endif
  102667. zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
  102668. sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
  102669. }
  102670. }
  102671. #else
  102672. # define explainOneScan(u,v,w,x,y,z)
  102673. #endif /* SQLITE_OMIT_EXPLAIN */
  102674. /*
  102675. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  102676. ** implementation described by pWInfo.
  102677. */
  102678. static Bitmask codeOneLoopStart(
  102679. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  102680. int iLevel, /* Which level of pWInfo->a[] should be coded */
  102681. Bitmask notReady /* Which tables are currently available */
  102682. ){
  102683. int j, k; /* Loop counters */
  102684. int iCur; /* The VDBE cursor for the table */
  102685. int addrNxt; /* Where to jump to continue with the next IN case */
  102686. int omitTable; /* True if we use the index only */
  102687. int bRev; /* True if we need to scan in reverse order */
  102688. WhereLevel *pLevel; /* The where level to be coded */
  102689. WhereLoop *pLoop; /* The WhereLoop object being coded */
  102690. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  102691. WhereTerm *pTerm; /* A WHERE clause term */
  102692. Parse *pParse; /* Parsing context */
  102693. sqlite3 *db; /* Database connection */
  102694. Vdbe *v; /* The prepared stmt under constructions */
  102695. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  102696. int addrBrk; /* Jump here to break out of the loop */
  102697. int addrCont; /* Jump here to continue with next cycle */
  102698. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  102699. int iReleaseReg = 0; /* Temp register to free before returning */
  102700. pParse = pWInfo->pParse;
  102701. v = pParse->pVdbe;
  102702. pWC = &pWInfo->sWC;
  102703. db = pParse->db;
  102704. pLevel = &pWInfo->a[iLevel];
  102705. pLoop = pLevel->pWLoop;
  102706. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  102707. iCur = pTabItem->iCursor;
  102708. pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
  102709. bRev = (pWInfo->revMask>>iLevel)&1;
  102710. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  102711. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  102712. VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
  102713. /* Create labels for the "break" and "continue" instructions
  102714. ** for the current loop. Jump to addrBrk to break out of a loop.
  102715. ** Jump to cont to go immediately to the next iteration of the
  102716. ** loop.
  102717. **
  102718. ** When there is an IN operator, we also have a "addrNxt" label that
  102719. ** means to continue with the next IN value combination. When
  102720. ** there are no IN operators in the constraints, the "addrNxt" label
  102721. ** is the same as "addrBrk".
  102722. */
  102723. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  102724. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  102725. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  102726. ** initialize a memory cell that records if this table matches any
  102727. ** row of the left table of the join.
  102728. */
  102729. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  102730. pLevel->iLeftJoin = ++pParse->nMem;
  102731. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  102732. VdbeComment((v, "init LEFT JOIN no-match flag"));
  102733. }
  102734. /* Special case of a FROM clause subquery implemented as a co-routine */
  102735. if( pTabItem->viaCoroutine ){
  102736. int regYield = pTabItem->regReturn;
  102737. sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
  102738. pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  102739. VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
  102740. sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
  102741. pLevel->op = OP_Goto;
  102742. }else
  102743. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102744. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  102745. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  102746. ** to access the data.
  102747. */
  102748. int iReg; /* P3 Value for OP_VFilter */
  102749. int addrNotFound;
  102750. int nConstraint = pLoop->nLTerm;
  102751. sqlite3ExprCachePush(pParse);
  102752. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  102753. addrNotFound = pLevel->addrBrk;
  102754. for(j=0; j<nConstraint; j++){
  102755. int iTarget = iReg+j+2;
  102756. pTerm = pLoop->aLTerm[j];
  102757. if( pTerm==0 ) continue;
  102758. if( pTerm->eOperator & WO_IN ){
  102759. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  102760. addrNotFound = pLevel->addrNxt;
  102761. }else{
  102762. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  102763. }
  102764. }
  102765. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  102766. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  102767. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  102768. pLoop->u.vtab.idxStr,
  102769. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  102770. pLoop->u.vtab.needFree = 0;
  102771. for(j=0; j<nConstraint && j<16; j++){
  102772. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  102773. disableTerm(pLevel, pLoop->aLTerm[j]);
  102774. }
  102775. }
  102776. pLevel->op = OP_VNext;
  102777. pLevel->p1 = iCur;
  102778. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  102779. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  102780. sqlite3ExprCachePop(pParse, 1);
  102781. }else
  102782. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  102783. if( (pLoop->wsFlags & WHERE_IPK)!=0
  102784. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  102785. ){
  102786. /* Case 2: We can directly reference a single row using an
  102787. ** equality comparison against the ROWID field. Or
  102788. ** we reference multiple rows using a "rowid IN (...)"
  102789. ** construct.
  102790. */
  102791. assert( pLoop->u.btree.nEq==1 );
  102792. iReleaseReg = sqlite3GetTempReg(pParse);
  102793. pTerm = pLoop->aLTerm[0];
  102794. assert( pTerm!=0 );
  102795. assert( pTerm->pExpr!=0 );
  102796. assert( omitTable==0 );
  102797. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  102798. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  102799. addrNxt = pLevel->addrNxt;
  102800. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
  102801. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  102802. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  102803. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  102804. VdbeComment((v, "pk"));
  102805. pLevel->op = OP_Noop;
  102806. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  102807. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  102808. ){
  102809. /* Case 3: We have an inequality comparison against the ROWID field.
  102810. */
  102811. int testOp = OP_Noop;
  102812. int start;
  102813. int memEndValue = 0;
  102814. WhereTerm *pStart, *pEnd;
  102815. assert( omitTable==0 );
  102816. j = 0;
  102817. pStart = pEnd = 0;
  102818. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  102819. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  102820. assert( pStart!=0 || pEnd!=0 );
  102821. if( bRev ){
  102822. pTerm = pStart;
  102823. pStart = pEnd;
  102824. pEnd = pTerm;
  102825. }
  102826. if( pStart ){
  102827. Expr *pX; /* The expression that defines the start bound */
  102828. int r1, rTemp; /* Registers for holding the start boundary */
  102829. /* The following constant maps TK_xx codes into corresponding
  102830. ** seek opcodes. It depends on a particular ordering of TK_xx
  102831. */
  102832. const u8 aMoveOp[] = {
  102833. /* TK_GT */ OP_SeekGt,
  102834. /* TK_LE */ OP_SeekLe,
  102835. /* TK_LT */ OP_SeekLt,
  102836. /* TK_GE */ OP_SeekGe
  102837. };
  102838. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  102839. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  102840. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  102841. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  102842. testcase( pStart->wtFlags & TERM_VIRTUAL );
  102843. pX = pStart->pExpr;
  102844. assert( pX!=0 );
  102845. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  102846. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  102847. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  102848. VdbeComment((v, "pk"));
  102849. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  102850. sqlite3ReleaseTempReg(pParse, rTemp);
  102851. disableTerm(pLevel, pStart);
  102852. }else{
  102853. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  102854. }
  102855. if( pEnd ){
  102856. Expr *pX;
  102857. pX = pEnd->pExpr;
  102858. assert( pX!=0 );
  102859. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  102860. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  102861. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  102862. memEndValue = ++pParse->nMem;
  102863. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  102864. if( pX->op==TK_LT || pX->op==TK_GT ){
  102865. testOp = bRev ? OP_Le : OP_Ge;
  102866. }else{
  102867. testOp = bRev ? OP_Lt : OP_Gt;
  102868. }
  102869. disableTerm(pLevel, pEnd);
  102870. }
  102871. start = sqlite3VdbeCurrentAddr(v);
  102872. pLevel->op = bRev ? OP_Prev : OP_Next;
  102873. pLevel->p1 = iCur;
  102874. pLevel->p2 = start;
  102875. assert( pLevel->p5==0 );
  102876. if( testOp!=OP_Noop ){
  102877. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  102878. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  102879. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  102880. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  102881. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  102882. }
  102883. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  102884. /* Case 4: A scan using an index.
  102885. **
  102886. ** The WHERE clause may contain zero or more equality
  102887. ** terms ("==" or "IN" operators) that refer to the N
  102888. ** left-most columns of the index. It may also contain
  102889. ** inequality constraints (>, <, >= or <=) on the indexed
  102890. ** column that immediately follows the N equalities. Only
  102891. ** the right-most column can be an inequality - the rest must
  102892. ** use the "==" and "IN" operators. For example, if the
  102893. ** index is on (x,y,z), then the following clauses are all
  102894. ** optimized:
  102895. **
  102896. ** x=5
  102897. ** x=5 AND y=10
  102898. ** x=5 AND y<10
  102899. ** x=5 AND y>5 AND y<10
  102900. ** x=5 AND y=5 AND z<=10
  102901. **
  102902. ** The z<10 term of the following cannot be used, only
  102903. ** the x=5 term:
  102904. **
  102905. ** x=5 AND z<10
  102906. **
  102907. ** N may be zero if there are inequality constraints.
  102908. ** If there are no inequality constraints, then N is at
  102909. ** least one.
  102910. **
  102911. ** This case is also used when there are no WHERE clause
  102912. ** constraints but an index is selected anyway, in order
  102913. ** to force the output order to conform to an ORDER BY.
  102914. */
  102915. static const u8 aStartOp[] = {
  102916. 0,
  102917. 0,
  102918. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  102919. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  102920. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  102921. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  102922. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  102923. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  102924. };
  102925. static const u8 aEndOp[] = {
  102926. OP_Noop, /* 0: (!end_constraints) */
  102927. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  102928. OP_IdxLT /* 2: (end_constraints && bRev) */
  102929. };
  102930. int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  102931. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  102932. int regBase; /* Base register holding constraint values */
  102933. int r1; /* Temp register */
  102934. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  102935. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  102936. int startEq; /* True if range start uses ==, >= or <= */
  102937. int endEq; /* True if range end uses ==, >= or <= */
  102938. int start_constraints; /* Start of range is constrained */
  102939. int nConstraint; /* Number of constraint terms */
  102940. Index *pIdx; /* The index we will be using */
  102941. int iIdxCur; /* The VDBE cursor for the index */
  102942. int nExtraReg = 0; /* Number of extra registers needed */
  102943. int op; /* Instruction opcode */
  102944. char *zStartAff; /* Affinity for start of range constraint */
  102945. char *zEndAff; /* Affinity for end of range constraint */
  102946. pIdx = pLoop->u.btree.pIndex;
  102947. iIdxCur = pLevel->iIdxCur;
  102948. /* If this loop satisfies a sort order (pOrderBy) request that
  102949. ** was passed to this function to implement a "SELECT min(x) ..."
  102950. ** query, then the caller will only allow the loop to run for
  102951. ** a single iteration. This means that the first row returned
  102952. ** should not have a NULL value stored in 'x'. If column 'x' is
  102953. ** the first one after the nEq equality constraints in the index,
  102954. ** this requires some special handling.
  102955. */
  102956. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  102957. && (pWInfo->bOBSat!=0)
  102958. && (pIdx->nColumn>nEq)
  102959. ){
  102960. /* assert( pOrderBy->nExpr==1 ); */
  102961. /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
  102962. isMinQuery = 1;
  102963. nExtraReg = 1;
  102964. }
  102965. /* Find any inequality constraint terms for the start and end
  102966. ** of the range.
  102967. */
  102968. j = nEq;
  102969. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  102970. pRangeStart = pLoop->aLTerm[j++];
  102971. nExtraReg = 1;
  102972. }
  102973. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  102974. pRangeEnd = pLoop->aLTerm[j++];
  102975. nExtraReg = 1;
  102976. }
  102977. /* Generate code to evaluate all constraint terms using == or IN
  102978. ** and store the values of those terms in an array of registers
  102979. ** starting at regBase.
  102980. */
  102981. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  102982. zEndAff = sqlite3DbStrDup(db, zStartAff);
  102983. addrNxt = pLevel->addrNxt;
  102984. /* If we are doing a reverse order scan on an ascending index, or
  102985. ** a forward order scan on a descending index, interchange the
  102986. ** start and end terms (pRangeStart and pRangeEnd).
  102987. */
  102988. if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  102989. || (bRev && pIdx->nColumn==nEq)
  102990. ){
  102991. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  102992. }
  102993. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  102994. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  102995. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  102996. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  102997. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  102998. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  102999. start_constraints = pRangeStart || nEq>0;
  103000. /* Seek the index cursor to the start of the range. */
  103001. nConstraint = nEq;
  103002. if( pRangeStart ){
  103003. Expr *pRight = pRangeStart->pExpr->pRight;
  103004. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  103005. if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
  103006. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  103007. }
  103008. if( zStartAff ){
  103009. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  103010. /* Since the comparison is to be performed with no conversions
  103011. ** applied to the operands, set the affinity to apply to pRight to
  103012. ** SQLITE_AFF_NONE. */
  103013. zStartAff[nEq] = SQLITE_AFF_NONE;
  103014. }
  103015. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  103016. zStartAff[nEq] = SQLITE_AFF_NONE;
  103017. }
  103018. }
  103019. nConstraint++;
  103020. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  103021. }else if( isMinQuery ){
  103022. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  103023. nConstraint++;
  103024. startEq = 0;
  103025. start_constraints = 1;
  103026. }
  103027. codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
  103028. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  103029. assert( op!=0 );
  103030. testcase( op==OP_Rewind );
  103031. testcase( op==OP_Last );
  103032. testcase( op==OP_SeekGt );
  103033. testcase( op==OP_SeekGe );
  103034. testcase( op==OP_SeekLe );
  103035. testcase( op==OP_SeekLt );
  103036. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  103037. /* Load the value for the inequality constraint at the end of the
  103038. ** range (if any).
  103039. */
  103040. nConstraint = nEq;
  103041. if( pRangeEnd ){
  103042. Expr *pRight = pRangeEnd->pExpr->pRight;
  103043. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  103044. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  103045. if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
  103046. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  103047. }
  103048. if( zEndAff ){
  103049. if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
  103050. /* Since the comparison is to be performed with no conversions
  103051. ** applied to the operands, set the affinity to apply to pRight to
  103052. ** SQLITE_AFF_NONE. */
  103053. zEndAff[nEq] = SQLITE_AFF_NONE;
  103054. }
  103055. if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
  103056. zEndAff[nEq] = SQLITE_AFF_NONE;
  103057. }
  103058. }
  103059. codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
  103060. nConstraint++;
  103061. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  103062. }
  103063. sqlite3DbFree(db, zStartAff);
  103064. sqlite3DbFree(db, zEndAff);
  103065. /* Top of the loop body */
  103066. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  103067. /* Check if the index cursor is past the end of the range. */
  103068. op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  103069. testcase( op==OP_Noop );
  103070. testcase( op==OP_IdxGE );
  103071. testcase( op==OP_IdxLT );
  103072. if( op!=OP_Noop ){
  103073. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  103074. sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
  103075. }
  103076. /* If there are inequality constraints, check that the value
  103077. ** of the table column that the inequality contrains is not NULL.
  103078. ** If it is, jump to the next iteration of the loop.
  103079. */
  103080. r1 = sqlite3GetTempReg(pParse);
  103081. testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
  103082. testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
  103083. if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
  103084. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  103085. sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  103086. }
  103087. sqlite3ReleaseTempReg(pParse, r1);
  103088. /* Seek the table cursor, if required */
  103089. disableTerm(pLevel, pRangeStart);
  103090. disableTerm(pLevel, pRangeEnd);
  103091. if( !omitTable ){
  103092. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  103093. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  103094. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  103095. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  103096. }
  103097. /* Record the instruction used to terminate the loop. Disable
  103098. ** WHERE clause terms made redundant by the index range scan.
  103099. */
  103100. if( pLoop->wsFlags & WHERE_ONEROW ){
  103101. pLevel->op = OP_Noop;
  103102. }else if( bRev ){
  103103. pLevel->op = OP_Prev;
  103104. }else{
  103105. pLevel->op = OP_Next;
  103106. }
  103107. pLevel->p1 = iIdxCur;
  103108. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  103109. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  103110. }else{
  103111. assert( pLevel->p5==0 );
  103112. }
  103113. }else
  103114. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  103115. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  103116. /* Case 5: Two or more separately indexed terms connected by OR
  103117. **
  103118. ** Example:
  103119. **
  103120. ** CREATE TABLE t1(a,b,c,d);
  103121. ** CREATE INDEX i1 ON t1(a);
  103122. ** CREATE INDEX i2 ON t1(b);
  103123. ** CREATE INDEX i3 ON t1(c);
  103124. **
  103125. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  103126. **
  103127. ** In the example, there are three indexed terms connected by OR.
  103128. ** The top of the loop looks like this:
  103129. **
  103130. ** Null 1 # Zero the rowset in reg 1
  103131. **
  103132. ** Then, for each indexed term, the following. The arguments to
  103133. ** RowSetTest are such that the rowid of the current row is inserted
  103134. ** into the RowSet. If it is already present, control skips the
  103135. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  103136. **
  103137. ** sqlite3WhereBegin(<term>)
  103138. ** RowSetTest # Insert rowid into rowset
  103139. ** Gosub 2 A
  103140. ** sqlite3WhereEnd()
  103141. **
  103142. ** Following the above, code to terminate the loop. Label A, the target
  103143. ** of the Gosub above, jumps to the instruction right after the Goto.
  103144. **
  103145. ** Null 1 # Zero the rowset in reg 1
  103146. ** Goto B # The loop is finished.
  103147. **
  103148. ** A: <loop body> # Return data, whatever.
  103149. **
  103150. ** Return 2 # Jump back to the Gosub
  103151. **
  103152. ** B: <after the loop>
  103153. **
  103154. */
  103155. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  103156. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  103157. Index *pCov = 0; /* Potential covering index (or NULL) */
  103158. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  103159. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  103160. int regRowset = 0; /* Register for RowSet object */
  103161. int regRowid = 0; /* Register holding rowid */
  103162. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  103163. int iRetInit; /* Address of regReturn init */
  103164. int untestedTerms = 0; /* Some terms not completely tested */
  103165. int ii; /* Loop counter */
  103166. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  103167. pTerm = pLoop->aLTerm[0];
  103168. assert( pTerm!=0 );
  103169. assert( pTerm->eOperator & WO_OR );
  103170. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  103171. pOrWc = &pTerm->u.pOrInfo->wc;
  103172. pLevel->op = OP_Return;
  103173. pLevel->p1 = regReturn;
  103174. /* Set up a new SrcList in pOrTab containing the table being scanned
  103175. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  103176. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  103177. */
  103178. if( pWInfo->nLevel>1 ){
  103179. int nNotReady; /* The number of notReady tables */
  103180. struct SrcList_item *origSrc; /* Original list of tables */
  103181. nNotReady = pWInfo->nLevel - iLevel - 1;
  103182. pOrTab = sqlite3StackAllocRaw(db,
  103183. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  103184. if( pOrTab==0 ) return notReady;
  103185. pOrTab->nAlloc = (u8)(nNotReady + 1);
  103186. pOrTab->nSrc = pOrTab->nAlloc;
  103187. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  103188. origSrc = pWInfo->pTabList->a;
  103189. for(k=1; k<=nNotReady; k++){
  103190. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  103191. }
  103192. }else{
  103193. pOrTab = pWInfo->pTabList;
  103194. }
  103195. /* Initialize the rowset register to contain NULL. An SQL NULL is
  103196. ** equivalent to an empty rowset.
  103197. **
  103198. ** Also initialize regReturn to contain the address of the instruction
  103199. ** immediately following the OP_Return at the bottom of the loop. This
  103200. ** is required in a few obscure LEFT JOIN cases where control jumps
  103201. ** over the top of the loop into the body of it. In this case the
  103202. ** correct response for the end-of-loop code (the OP_Return) is to
  103203. ** fall through to the next instruction, just as an OP_Next does if
  103204. ** called on an uninitialized cursor.
  103205. */
  103206. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  103207. regRowset = ++pParse->nMem;
  103208. regRowid = ++pParse->nMem;
  103209. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  103210. }
  103211. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  103212. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  103213. ** Then for every term xN, evaluate as the subexpression: xN AND z
  103214. ** That way, terms in y that are factored into the disjunction will
  103215. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  103216. **
  103217. ** Actually, each subexpression is converted to "xN AND w" where w is
  103218. ** the "interesting" terms of z - terms that did not originate in the
  103219. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  103220. ** indices.
  103221. **
  103222. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  103223. ** is not contained in the ON clause of a LEFT JOIN.
  103224. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  103225. */
  103226. if( pWC->nTerm>1 ){
  103227. int iTerm;
  103228. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  103229. Expr *pExpr = pWC->a[iTerm].pExpr;
  103230. if( &pWC->a[iTerm] == pTerm ) continue;
  103231. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  103232. if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
  103233. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  103234. pExpr = sqlite3ExprDup(db, pExpr, 0);
  103235. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  103236. }
  103237. if( pAndExpr ){
  103238. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  103239. }
  103240. }
  103241. for(ii=0; ii<pOrWc->nTerm; ii++){
  103242. WhereTerm *pOrTerm = &pOrWc->a[ii];
  103243. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  103244. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  103245. Expr *pOrExpr = pOrTerm->pExpr;
  103246. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  103247. pAndExpr->pLeft = pOrExpr;
  103248. pOrExpr = pAndExpr;
  103249. }
  103250. /* Loop through table entries that match term pOrTerm. */
  103251. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  103252. WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
  103253. WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
  103254. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  103255. if( pSubWInfo ){
  103256. WhereLoop *pSubLoop;
  103257. explainOneScan(
  103258. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  103259. );
  103260. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  103261. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  103262. int r;
  103263. r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
  103264. regRowid, 0);
  103265. sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
  103266. sqlite3VdbeCurrentAddr(v)+2, r, iSet);
  103267. }
  103268. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  103269. /* The pSubWInfo->untestedTerms flag means that this OR term
  103270. ** contained one or more AND term from a notReady table. The
  103271. ** terms from the notReady table could not be tested and will
  103272. ** need to be tested later.
  103273. */
  103274. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  103275. /* If all of the OR-connected terms are optimized using the same
  103276. ** index, and the index is opened using the same cursor number
  103277. ** by each call to sqlite3WhereBegin() made by this loop, it may
  103278. ** be possible to use that index as a covering index.
  103279. **
  103280. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  103281. ** uses an index, and this is either the first OR-connected term
  103282. ** processed or the index is the same as that used by all previous
  103283. ** terms, set pCov to the candidate covering index. Otherwise, set
  103284. ** pCov to NULL to indicate that no candidate covering index will
  103285. ** be available.
  103286. */
  103287. pSubLoop = pSubWInfo->a[0].pWLoop;
  103288. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  103289. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  103290. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  103291. ){
  103292. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  103293. pCov = pSubLoop->u.btree.pIndex;
  103294. }else{
  103295. pCov = 0;
  103296. }
  103297. /* Finish the loop through table entries that match term pOrTerm. */
  103298. sqlite3WhereEnd(pSubWInfo);
  103299. }
  103300. }
  103301. }
  103302. pLevel->u.pCovidx = pCov;
  103303. if( pCov ) pLevel->iIdxCur = iCovCur;
  103304. if( pAndExpr ){
  103305. pAndExpr->pLeft = 0;
  103306. sqlite3ExprDelete(db, pAndExpr);
  103307. }
  103308. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  103309. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  103310. sqlite3VdbeResolveLabel(v, iLoopBody);
  103311. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  103312. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  103313. }else
  103314. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  103315. {
  103316. /* Case 6: There is no usable index. We must do a complete
  103317. ** scan of the entire table.
  103318. */
  103319. static const u8 aStep[] = { OP_Next, OP_Prev };
  103320. static const u8 aStart[] = { OP_Rewind, OP_Last };
  103321. assert( bRev==0 || bRev==1 );
  103322. pLevel->op = aStep[bRev];
  103323. pLevel->p1 = iCur;
  103324. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  103325. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  103326. }
  103327. /* Insert code to test every subexpression that can be completely
  103328. ** computed using the current set of tables.
  103329. */
  103330. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  103331. Expr *pE;
  103332. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  103333. testcase( pTerm->wtFlags & TERM_CODED );
  103334. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  103335. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  103336. testcase( pWInfo->untestedTerms==0
  103337. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  103338. pWInfo->untestedTerms = 1;
  103339. continue;
  103340. }
  103341. pE = pTerm->pExpr;
  103342. assert( pE!=0 );
  103343. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  103344. continue;
  103345. }
  103346. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  103347. pTerm->wtFlags |= TERM_CODED;
  103348. }
  103349. /* Insert code to test for implied constraints based on transitivity
  103350. ** of the "==" operator.
  103351. **
  103352. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  103353. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  103354. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  103355. ** the implied "t1.a=123" constraint.
  103356. */
  103357. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  103358. Expr *pE, *pEAlt;
  103359. WhereTerm *pAlt;
  103360. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  103361. if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
  103362. if( pTerm->leftCursor!=iCur ) continue;
  103363. if( pLevel->iLeftJoin ) continue;
  103364. pE = pTerm->pExpr;
  103365. assert( !ExprHasProperty(pE, EP_FromJoin) );
  103366. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  103367. pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
  103368. if( pAlt==0 ) continue;
  103369. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  103370. testcase( pAlt->eOperator & WO_EQ );
  103371. testcase( pAlt->eOperator & WO_IN );
  103372. VdbeNoopComment((v, "begin transitive constraint"));
  103373. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  103374. if( pEAlt ){
  103375. *pEAlt = *pAlt->pExpr;
  103376. pEAlt->pLeft = pE->pLeft;
  103377. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  103378. sqlite3StackFree(db, pEAlt);
  103379. }
  103380. }
  103381. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  103382. ** at least one row of the right table has matched the left table.
  103383. */
  103384. if( pLevel->iLeftJoin ){
  103385. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  103386. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  103387. VdbeComment((v, "record LEFT JOIN hit"));
  103388. sqlite3ExprCacheClear(pParse);
  103389. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  103390. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  103391. testcase( pTerm->wtFlags & TERM_CODED );
  103392. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  103393. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  103394. assert( pWInfo->untestedTerms );
  103395. continue;
  103396. }
  103397. assert( pTerm->pExpr );
  103398. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  103399. pTerm->wtFlags |= TERM_CODED;
  103400. }
  103401. }
  103402. sqlite3ReleaseTempReg(pParse, iReleaseReg);
  103403. return pLevel->notReady;
  103404. }
  103405. #ifdef WHERETRACE_ENABLED
  103406. /*
  103407. ** Print a WhereLoop object for debugging purposes
  103408. */
  103409. static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
  103410. int nb = 1+(pTabList->nSrc+7)/8;
  103411. struct SrcList_item *pItem = pTabList->a + p->iTab;
  103412. Table *pTab = pItem->pTab;
  103413. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  103414. p->iTab, nb, p->maskSelf, nb, p->prereq);
  103415. sqlite3DebugPrintf(" %12s",
  103416. pItem->zAlias ? pItem->zAlias : pTab->zName);
  103417. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  103418. if( p->u.btree.pIndex ){
  103419. const char *zName = p->u.btree.pIndex->zName;
  103420. if( zName==0 ) zName = "ipk";
  103421. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  103422. int i = sqlite3Strlen30(zName) - 1;
  103423. while( zName[i]!='_' ) i--;
  103424. zName += i;
  103425. }
  103426. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  103427. }else{
  103428. sqlite3DebugPrintf("%20s","");
  103429. }
  103430. }else{
  103431. char *z;
  103432. if( p->u.vtab.idxStr ){
  103433. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  103434. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  103435. }else{
  103436. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  103437. }
  103438. sqlite3DebugPrintf(" %-19s", z);
  103439. sqlite3_free(z);
  103440. }
  103441. sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
  103442. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  103443. }
  103444. #endif
  103445. /*
  103446. ** Convert bulk memory into a valid WhereLoop that can be passed
  103447. ** to whereLoopClear harmlessly.
  103448. */
  103449. static void whereLoopInit(WhereLoop *p){
  103450. p->aLTerm = p->aLTermSpace;
  103451. p->nLTerm = 0;
  103452. p->nLSlot = ArraySize(p->aLTermSpace);
  103453. p->wsFlags = 0;
  103454. }
  103455. /*
  103456. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  103457. */
  103458. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  103459. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  103460. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  103461. sqlite3_free(p->u.vtab.idxStr);
  103462. p->u.vtab.needFree = 0;
  103463. p->u.vtab.idxStr = 0;
  103464. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  103465. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  103466. sqlite3DbFree(db, p->u.btree.pIndex);
  103467. p->u.btree.pIndex = 0;
  103468. }
  103469. }
  103470. }
  103471. /*
  103472. ** Deallocate internal memory used by a WhereLoop object
  103473. */
  103474. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  103475. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  103476. whereLoopClearUnion(db, p);
  103477. whereLoopInit(p);
  103478. }
  103479. /*
  103480. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  103481. */
  103482. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  103483. WhereTerm **paNew;
  103484. if( p->nLSlot>=n ) return SQLITE_OK;
  103485. n = (n+7)&~7;
  103486. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  103487. if( paNew==0 ) return SQLITE_NOMEM;
  103488. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  103489. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  103490. p->aLTerm = paNew;
  103491. p->nLSlot = n;
  103492. return SQLITE_OK;
  103493. }
  103494. /*
  103495. ** Transfer content from the second pLoop into the first.
  103496. */
  103497. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  103498. whereLoopClearUnion(db, pTo);
  103499. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  103500. memset(&pTo->u, 0, sizeof(pTo->u));
  103501. return SQLITE_NOMEM;
  103502. }
  103503. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  103504. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  103505. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  103506. pFrom->u.vtab.needFree = 0;
  103507. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  103508. pFrom->u.btree.pIndex = 0;
  103509. }
  103510. return SQLITE_OK;
  103511. }
  103512. /*
  103513. ** Delete a WhereLoop object
  103514. */
  103515. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  103516. whereLoopClear(db, p);
  103517. sqlite3DbFree(db, p);
  103518. }
  103519. /*
  103520. ** Free a WhereInfo structure
  103521. */
  103522. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  103523. if( ALWAYS(pWInfo) ){
  103524. whereClauseClear(&pWInfo->sWC);
  103525. while( pWInfo->pLoops ){
  103526. WhereLoop *p = pWInfo->pLoops;
  103527. pWInfo->pLoops = p->pNextLoop;
  103528. whereLoopDelete(db, p);
  103529. }
  103530. sqlite3DbFree(db, pWInfo);
  103531. }
  103532. }
  103533. /*
  103534. ** Insert or replace a WhereLoop entry using the template supplied.
  103535. **
  103536. ** An existing WhereLoop entry might be overwritten if the new template
  103537. ** is better and has fewer dependencies. Or the template will be ignored
  103538. ** and no insert will occur if an existing WhereLoop is faster and has
  103539. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  103540. ** added based on the template.
  103541. **
  103542. ** If pBuilder->pOrSet is not NULL then we only care about only the
  103543. ** prerequisites and rRun and nOut costs of the N best loops. That
  103544. ** information is gathered in the pBuilder->pOrSet object. This special
  103545. ** processing mode is used only for OR clause processing.
  103546. **
  103547. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  103548. ** still might overwrite similar loops with the new template if the
  103549. ** template is better. Loops may be overwritten if the following
  103550. ** conditions are met:
  103551. **
  103552. ** (1) They have the same iTab.
  103553. ** (2) They have the same iSortIdx.
  103554. ** (3) The template has same or fewer dependencies than the current loop
  103555. ** (4) The template has the same or lower cost than the current loop
  103556. ** (5) The template uses more terms of the same index but has no additional
  103557. ** dependencies
  103558. */
  103559. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  103560. WhereLoop **ppPrev, *p, *pNext = 0;
  103561. WhereInfo *pWInfo = pBuilder->pWInfo;
  103562. sqlite3 *db = pWInfo->pParse->db;
  103563. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  103564. ** and prereqs.
  103565. */
  103566. if( pBuilder->pOrSet!=0 ){
  103567. #if WHERETRACE_ENABLED
  103568. u16 n = pBuilder->pOrSet->n;
  103569. int x =
  103570. #endif
  103571. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  103572. pTemplate->nOut);
  103573. #if WHERETRACE_ENABLED
  103574. if( sqlite3WhereTrace & 0x8 ){
  103575. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  103576. whereLoopPrint(pTemplate, pWInfo->pTabList);
  103577. }
  103578. #endif
  103579. return SQLITE_OK;
  103580. }
  103581. /* Search for an existing WhereLoop to overwrite, or which takes
  103582. ** priority over pTemplate.
  103583. */
  103584. for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
  103585. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  103586. /* If either the iTab or iSortIdx values for two WhereLoop are different
  103587. ** then those WhereLoops need to be considered separately. Neither is
  103588. ** a candidate to replace the other. */
  103589. continue;
  103590. }
  103591. /* In the current implementation, the rSetup value is either zero
  103592. ** or the cost of building an automatic index (NlogN) and the NlogN
  103593. ** is the same for compatible WhereLoops. */
  103594. assert( p->rSetup==0 || pTemplate->rSetup==0
  103595. || p->rSetup==pTemplate->rSetup );
  103596. /* whereLoopAddBtree() always generates and inserts the automatic index
  103597. ** case first. Hence compatible candidate WhereLoops never have a larger
  103598. ** rSetup. Call this SETUP-INVARIANT */
  103599. assert( p->rSetup>=pTemplate->rSetup );
  103600. if( (p->prereq & pTemplate->prereq)==p->prereq
  103601. && p->rSetup<=pTemplate->rSetup
  103602. && p->rRun<=pTemplate->rRun
  103603. && p->nOut<=pTemplate->nOut
  103604. ){
  103605. /* This branch taken when p is equal or better than pTemplate in
  103606. ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
  103607. ** (4) number of output rows. */
  103608. assert( p->rSetup==pTemplate->rSetup );
  103609. if( p->prereq==pTemplate->prereq
  103610. && p->nLTerm<pTemplate->nLTerm
  103611. && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
  103612. && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
  103613. || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
  103614. ){
  103615. /* Overwrite an existing WhereLoop with an similar one that uses
  103616. ** more terms of the index */
  103617. pNext = p->pNextLoop;
  103618. break;
  103619. }else{
  103620. /* pTemplate is not helpful.
  103621. ** Return without changing or adding anything */
  103622. goto whereLoopInsert_noop;
  103623. }
  103624. }
  103625. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
  103626. && p->rRun>=pTemplate->rRun
  103627. && p->nOut>=pTemplate->nOut
  103628. ){
  103629. /* Overwrite an existing WhereLoop with a better one: one that is
  103630. ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
  103631. ** or (4) number of output rows, and is no worse in any of those
  103632. ** categories. */
  103633. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  103634. pNext = p->pNextLoop;
  103635. break;
  103636. }
  103637. }
  103638. /* If we reach this point it means that either p[] should be overwritten
  103639. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  103640. ** WhereLoop and insert it.
  103641. */
  103642. #if WHERETRACE_ENABLED
  103643. if( sqlite3WhereTrace & 0x8 ){
  103644. if( p!=0 ){
  103645. sqlite3DebugPrintf("ins-del: ");
  103646. whereLoopPrint(p, pWInfo->pTabList);
  103647. }
  103648. sqlite3DebugPrintf("ins-new: ");
  103649. whereLoopPrint(pTemplate, pWInfo->pTabList);
  103650. }
  103651. #endif
  103652. if( p==0 ){
  103653. p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  103654. if( p==0 ) return SQLITE_NOMEM;
  103655. whereLoopInit(p);
  103656. }
  103657. whereLoopXfer(db, p, pTemplate);
  103658. p->pNextLoop = pNext;
  103659. *ppPrev = p;
  103660. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  103661. Index *pIndex = p->u.btree.pIndex;
  103662. if( pIndex && pIndex->tnum==0 ){
  103663. p->u.btree.pIndex = 0;
  103664. }
  103665. }
  103666. return SQLITE_OK;
  103667. /* Jump here if the insert is a no-op */
  103668. whereLoopInsert_noop:
  103669. #if WHERETRACE_ENABLED
  103670. if( sqlite3WhereTrace & 0x8 ){
  103671. sqlite3DebugPrintf("ins-noop: ");
  103672. whereLoopPrint(pTemplate, pWInfo->pTabList);
  103673. }
  103674. #endif
  103675. return SQLITE_OK;
  103676. }
  103677. /*
  103678. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  103679. ** WHERE clause that reference the loop but which are not used by an
  103680. ** index.
  103681. **
  103682. ** In the current implementation, the first extra WHERE clause term reduces
  103683. ** the number of output rows by a factor of 10 and each additional term
  103684. ** reduces the number of output rows by sqrt(2).
  103685. */
  103686. static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
  103687. WhereTerm *pTerm, *pX;
  103688. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  103689. int i, j;
  103690. if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
  103691. return;
  103692. }
  103693. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  103694. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  103695. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  103696. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  103697. for(j=pLoop->nLTerm-1; j>=0; j--){
  103698. pX = pLoop->aLTerm[j];
  103699. if( pX==pTerm ) break;
  103700. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  103701. }
  103702. if( j<0 ) pLoop->nOut += pTerm->truthProb;
  103703. }
  103704. }
  103705. /*
  103706. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
  103707. ** Try to match one more.
  103708. **
  103709. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  103710. ** INTEGER PRIMARY KEY.
  103711. */
  103712. static int whereLoopAddBtreeIndex(
  103713. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  103714. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  103715. Index *pProbe, /* An index on pSrc */
  103716. LogEst nInMul /* log(Number of iterations due to IN) */
  103717. ){
  103718. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  103719. Parse *pParse = pWInfo->pParse; /* Parsing context */
  103720. sqlite3 *db = pParse->db; /* Database connection malloc context */
  103721. WhereLoop *pNew; /* Template WhereLoop under construction */
  103722. WhereTerm *pTerm; /* A WhereTerm under consideration */
  103723. int opMask; /* Valid operators for constraints */
  103724. WhereScan scan; /* Iterator for WHERE terms */
  103725. Bitmask saved_prereq; /* Original value of pNew->prereq */
  103726. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  103727. int saved_nEq; /* Original value of pNew->u.btree.nEq */
  103728. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  103729. LogEst saved_nOut; /* Original value of pNew->nOut */
  103730. int iCol; /* Index of the column in the table */
  103731. int rc = SQLITE_OK; /* Return code */
  103732. LogEst nRowEst; /* Estimated index selectivity */
  103733. LogEst rLogSize; /* Logarithm of table size */
  103734. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  103735. pNew = pBuilder->pNew;
  103736. if( db->mallocFailed ) return SQLITE_NOMEM;
  103737. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  103738. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  103739. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  103740. opMask = WO_LT|WO_LE;
  103741. }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
  103742. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  103743. }else{
  103744. opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
  103745. }
  103746. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  103747. assert( pNew->u.btree.nEq<=pProbe->nColumn );
  103748. if( pNew->u.btree.nEq < pProbe->nColumn ){
  103749. iCol = pProbe->aiColumn[pNew->u.btree.nEq];
  103750. nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
  103751. if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
  103752. }else{
  103753. iCol = -1;
  103754. nRowEst = 0;
  103755. }
  103756. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
  103757. opMask, pProbe);
  103758. saved_nEq = pNew->u.btree.nEq;
  103759. saved_nLTerm = pNew->nLTerm;
  103760. saved_wsFlags = pNew->wsFlags;
  103761. saved_prereq = pNew->prereq;
  103762. saved_nOut = pNew->nOut;
  103763. pNew->rSetup = 0;
  103764. rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
  103765. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  103766. int nIn = 0;
  103767. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  103768. int nRecValid = pBuilder->nRecValid;
  103769. #endif
  103770. if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  103771. && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
  103772. ){
  103773. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  103774. }
  103775. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  103776. assert( pNew->nOut==saved_nOut );
  103777. pNew->wsFlags = saved_wsFlags;
  103778. pNew->u.btree.nEq = saved_nEq;
  103779. pNew->nLTerm = saved_nLTerm;
  103780. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  103781. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  103782. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  103783. pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
  103784. if( pTerm->eOperator & WO_IN ){
  103785. Expr *pExpr = pTerm->pExpr;
  103786. pNew->wsFlags |= WHERE_COLUMN_IN;
  103787. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  103788. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  103789. nIn = 46; assert( 46==sqlite3LogEst(25) );
  103790. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  103791. /* "x IN (value, value, ...)" */
  103792. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  103793. }
  103794. pNew->rRun += nIn;
  103795. pNew->u.btree.nEq++;
  103796. pNew->nOut = nRowEst + nInMul + nIn;
  103797. }else if( pTerm->eOperator & (WO_EQ) ){
  103798. assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
  103799. || nInMul==0 );
  103800. pNew->wsFlags |= WHERE_COLUMN_EQ;
  103801. if( iCol<0
  103802. || (pProbe->onError!=OE_None && nInMul==0
  103803. && pNew->u.btree.nEq==pProbe->nColumn-1)
  103804. ){
  103805. assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
  103806. pNew->wsFlags |= WHERE_ONEROW;
  103807. }
  103808. pNew->u.btree.nEq++;
  103809. pNew->nOut = nRowEst + nInMul;
  103810. }else if( pTerm->eOperator & (WO_ISNULL) ){
  103811. pNew->wsFlags |= WHERE_COLUMN_NULL;
  103812. pNew->u.btree.nEq++;
  103813. /* TUNING: IS NULL selects 2 rows */
  103814. nIn = 10; assert( 10==sqlite3LogEst(2) );
  103815. pNew->nOut = nRowEst + nInMul + nIn;
  103816. }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
  103817. testcase( pTerm->eOperator & WO_GT );
  103818. testcase( pTerm->eOperator & WO_GE );
  103819. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  103820. pBtm = pTerm;
  103821. pTop = 0;
  103822. }else{
  103823. assert( pTerm->eOperator & (WO_LT|WO_LE) );
  103824. testcase( pTerm->eOperator & WO_LT );
  103825. testcase( pTerm->eOperator & WO_LE );
  103826. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  103827. pTop = pTerm;
  103828. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  103829. pNew->aLTerm[pNew->nLTerm-2] : 0;
  103830. }
  103831. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  103832. /* Adjust nOut and rRun for STAT3 range values */
  103833. assert( pNew->nOut==saved_nOut );
  103834. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  103835. }
  103836. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  103837. if( nInMul==0
  103838. && pProbe->nSample
  103839. && pNew->u.btree.nEq<=pProbe->nSampleCol
  103840. && OptimizationEnabled(db, SQLITE_Stat3)
  103841. ){
  103842. Expr *pExpr = pTerm->pExpr;
  103843. tRowcnt nOut = 0;
  103844. if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
  103845. testcase( pTerm->eOperator & WO_EQ );
  103846. testcase( pTerm->eOperator & WO_ISNULL );
  103847. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  103848. }else if( (pTerm->eOperator & WO_IN)
  103849. && !ExprHasProperty(pExpr, EP_xIsSelect) ){
  103850. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  103851. }
  103852. assert( nOut==0 || rc==SQLITE_OK );
  103853. if( nOut ){
  103854. pNew->nOut = sqlite3LogEst(nOut);
  103855. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  103856. }
  103857. }
  103858. #endif
  103859. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  103860. /* Each row involves a step of the index, then a binary search of
  103861. ** the main table */
  103862. pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
  103863. }
  103864. /* Step cost for each output row */
  103865. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
  103866. whereLoopOutputAdjust(pBuilder->pWC, pNew);
  103867. rc = whereLoopInsert(pBuilder, pNew);
  103868. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  103869. && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
  103870. ){
  103871. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  103872. }
  103873. pNew->nOut = saved_nOut;
  103874. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  103875. pBuilder->nRecValid = nRecValid;
  103876. #endif
  103877. }
  103878. pNew->prereq = saved_prereq;
  103879. pNew->u.btree.nEq = saved_nEq;
  103880. pNew->wsFlags = saved_wsFlags;
  103881. pNew->nOut = saved_nOut;
  103882. pNew->nLTerm = saved_nLTerm;
  103883. return rc;
  103884. }
  103885. /*
  103886. ** Return True if it is possible that pIndex might be useful in
  103887. ** implementing the ORDER BY clause in pBuilder.
  103888. **
  103889. ** Return False if pBuilder does not contain an ORDER BY clause or
  103890. ** if there is no way for pIndex to be useful in implementing that
  103891. ** ORDER BY clause.
  103892. */
  103893. static int indexMightHelpWithOrderBy(
  103894. WhereLoopBuilder *pBuilder,
  103895. Index *pIndex,
  103896. int iCursor
  103897. ){
  103898. ExprList *pOB;
  103899. int ii, jj;
  103900. if( pIndex->bUnordered ) return 0;
  103901. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  103902. for(ii=0; ii<pOB->nExpr; ii++){
  103903. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  103904. if( pExpr->op!=TK_COLUMN ) return 0;
  103905. if( pExpr->iTable==iCursor ){
  103906. for(jj=0; jj<pIndex->nColumn; jj++){
  103907. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  103908. }
  103909. }
  103910. }
  103911. return 0;
  103912. }
  103913. /*
  103914. ** Return a bitmask where 1s indicate that the corresponding column of
  103915. ** the table is used by an index. Only the first 63 columns are considered.
  103916. */
  103917. static Bitmask columnsInIndex(Index *pIdx){
  103918. Bitmask m = 0;
  103919. int j;
  103920. for(j=pIdx->nColumn-1; j>=0; j--){
  103921. int x = pIdx->aiColumn[j];
  103922. assert( x>=0 );
  103923. testcase( x==BMS-1 );
  103924. testcase( x==BMS-2 );
  103925. if( x<BMS-1 ) m |= MASKBIT(x);
  103926. }
  103927. return m;
  103928. }
  103929. /* Check to see if a partial index with pPartIndexWhere can be used
  103930. ** in the current query. Return true if it can be and false if not.
  103931. */
  103932. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  103933. int i;
  103934. WhereTerm *pTerm;
  103935. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  103936. if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
  103937. }
  103938. return 0;
  103939. }
  103940. /*
  103941. ** Add all WhereLoop objects for a single table of the join where the table
  103942. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  103943. ** a b-tree table, not a virtual table.
  103944. */
  103945. static int whereLoopAddBtree(
  103946. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  103947. Bitmask mExtra /* Extra prerequesites for using this table */
  103948. ){
  103949. WhereInfo *pWInfo; /* WHERE analysis context */
  103950. Index *pProbe; /* An index we are evaluating */
  103951. Index sPk; /* A fake index object for the primary key */
  103952. tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
  103953. int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  103954. SrcList *pTabList; /* The FROM clause */
  103955. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  103956. WhereLoop *pNew; /* Template WhereLoop object */
  103957. int rc = SQLITE_OK; /* Return code */
  103958. int iSortIdx = 1; /* Index number */
  103959. int b; /* A boolean value */
  103960. LogEst rSize; /* number of rows in the table */
  103961. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  103962. WhereClause *pWC; /* The parsed WHERE clause */
  103963. Table *pTab; /* Table being queried */
  103964. pNew = pBuilder->pNew;
  103965. pWInfo = pBuilder->pWInfo;
  103966. pTabList = pWInfo->pTabList;
  103967. pSrc = pTabList->a + pNew->iTab;
  103968. pTab = pSrc->pTab;
  103969. pWC = pBuilder->pWC;
  103970. assert( !IsVirtual(pSrc->pTab) );
  103971. if( pSrc->pIndex ){
  103972. /* An INDEXED BY clause specifies a particular index to use */
  103973. pProbe = pSrc->pIndex;
  103974. }else{
  103975. /* There is no INDEXED BY clause. Create a fake Index object in local
  103976. ** variable sPk to represent the rowid primary key index. Make this
  103977. ** fake index the first in a chain of Index objects with all of the real
  103978. ** indices to follow */
  103979. Index *pFirst; /* First of real indices on the table */
  103980. memset(&sPk, 0, sizeof(Index));
  103981. sPk.nColumn = 1;
  103982. sPk.aiColumn = &aiColumnPk;
  103983. sPk.aiRowEst = aiRowEstPk;
  103984. sPk.onError = OE_Replace;
  103985. sPk.pTable = pTab;
  103986. aiRowEstPk[0] = pTab->nRowEst;
  103987. aiRowEstPk[1] = 1;
  103988. pFirst = pSrc->pTab->pIndex;
  103989. if( pSrc->notIndexed==0 ){
  103990. /* The real indices of the table are only considered if the
  103991. ** NOT INDEXED qualifier is omitted from the FROM clause */
  103992. sPk.pNext = pFirst;
  103993. }
  103994. pProbe = &sPk;
  103995. }
  103996. rSize = sqlite3LogEst(pTab->nRowEst);
  103997. rLogSize = estLog(rSize);
  103998. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  103999. /* Automatic indexes */
  104000. if( !pBuilder->pOrSet
  104001. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  104002. && pSrc->pIndex==0
  104003. && !pSrc->viaCoroutine
  104004. && !pSrc->notIndexed
  104005. && !pSrc->isCorrelated
  104006. ){
  104007. /* Generate auto-index WhereLoops */
  104008. WhereTerm *pTerm;
  104009. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  104010. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  104011. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  104012. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  104013. pNew->u.btree.nEq = 1;
  104014. pNew->u.btree.pIndex = 0;
  104015. pNew->nLTerm = 1;
  104016. pNew->aLTerm[0] = pTerm;
  104017. /* TUNING: One-time cost for computing the automatic index is
  104018. ** approximately 7*N*log2(N) where N is the number of rows in
  104019. ** the table being indexed. */
  104020. pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) );
  104021. /* TUNING: Each index lookup yields 20 rows in the table. This
  104022. ** is more than the usual guess of 10 rows, since we have no way
  104023. ** of knowning how selective the index will ultimately be. It would
  104024. ** not be unreasonable to make this value much larger. */
  104025. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  104026. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  104027. pNew->wsFlags = WHERE_AUTO_INDEX;
  104028. pNew->prereq = mExtra | pTerm->prereqRight;
  104029. rc = whereLoopInsert(pBuilder, pNew);
  104030. }
  104031. }
  104032. }
  104033. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  104034. /* Loop over all indices
  104035. */
  104036. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  104037. if( pProbe->pPartIdxWhere!=0
  104038. && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
  104039. continue; /* Partial index inappropriate for this query */
  104040. }
  104041. pNew->u.btree.nEq = 0;
  104042. pNew->nLTerm = 0;
  104043. pNew->iSortIdx = 0;
  104044. pNew->rSetup = 0;
  104045. pNew->prereq = mExtra;
  104046. pNew->nOut = rSize;
  104047. pNew->u.btree.pIndex = pProbe;
  104048. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  104049. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  104050. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  104051. if( pProbe->tnum<=0 ){
  104052. /* Integer primary key index */
  104053. pNew->wsFlags = WHERE_IPK;
  104054. /* Full table scan */
  104055. pNew->iSortIdx = b ? iSortIdx : 0;
  104056. /* TUNING: Cost of full table scan is 3*(N + log2(N)).
  104057. ** + The extra 3 factor is to encourage the use of indexed lookups
  104058. ** over full scans. FIXME */
  104059. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
  104060. whereLoopOutputAdjust(pWC, pNew);
  104061. rc = whereLoopInsert(pBuilder, pNew);
  104062. pNew->nOut = rSize;
  104063. if( rc ) break;
  104064. }else{
  104065. Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
  104066. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  104067. /* Full scan via index */
  104068. if( b
  104069. || ( m==0
  104070. && pProbe->bUnordered==0
  104071. && pProbe->szIdxRow<pTab->szTabRow
  104072. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  104073. && sqlite3GlobalConfig.bUseCis
  104074. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  104075. )
  104076. ){
  104077. pNew->iSortIdx = b ? iSortIdx : 0;
  104078. if( m==0 ){
  104079. /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
  104080. ** + The extra factor K of between 1.1 and 3.0 that depends
  104081. ** on the relative sizes of the table and the index. K
  104082. ** is smaller for smaller indices, thus favoring them.
  104083. */
  104084. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
  104085. (15*pProbe->szIdxRow)/pTab->szTabRow;
  104086. }else{
  104087. assert( b!=0 );
  104088. /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
  104089. ** which we will simplify to just N*log2(N) */
  104090. pNew->rRun = rSize + rLogSize;
  104091. }
  104092. whereLoopOutputAdjust(pWC, pNew);
  104093. rc = whereLoopInsert(pBuilder, pNew);
  104094. pNew->nOut = rSize;
  104095. if( rc ) break;
  104096. }
  104097. }
  104098. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  104099. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  104100. sqlite3Stat4ProbeFree(pBuilder->pRec);
  104101. pBuilder->nRecValid = 0;
  104102. pBuilder->pRec = 0;
  104103. #endif
  104104. /* If there was an INDEXED BY clause, then only that one index is
  104105. ** considered. */
  104106. if( pSrc->pIndex ) break;
  104107. }
  104108. return rc;
  104109. }
  104110. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104111. /*
  104112. ** Add all WhereLoop objects for a table of the join identified by
  104113. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  104114. */
  104115. static int whereLoopAddVirtual(
  104116. WhereLoopBuilder *pBuilder /* WHERE clause information */
  104117. ){
  104118. WhereInfo *pWInfo; /* WHERE analysis context */
  104119. Parse *pParse; /* The parsing context */
  104120. WhereClause *pWC; /* The WHERE clause */
  104121. struct SrcList_item *pSrc; /* The FROM clause term to search */
  104122. Table *pTab;
  104123. sqlite3 *db;
  104124. sqlite3_index_info *pIdxInfo;
  104125. struct sqlite3_index_constraint *pIdxCons;
  104126. struct sqlite3_index_constraint_usage *pUsage;
  104127. WhereTerm *pTerm;
  104128. int i, j;
  104129. int iTerm, mxTerm;
  104130. int nConstraint;
  104131. int seenIn = 0; /* True if an IN operator is seen */
  104132. int seenVar = 0; /* True if a non-constant constraint is seen */
  104133. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  104134. WhereLoop *pNew;
  104135. int rc = SQLITE_OK;
  104136. pWInfo = pBuilder->pWInfo;
  104137. pParse = pWInfo->pParse;
  104138. db = pParse->db;
  104139. pWC = pBuilder->pWC;
  104140. pNew = pBuilder->pNew;
  104141. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  104142. pTab = pSrc->pTab;
  104143. assert( IsVirtual(pTab) );
  104144. pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
  104145. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  104146. pNew->prereq = 0;
  104147. pNew->rSetup = 0;
  104148. pNew->wsFlags = WHERE_VIRTUALTABLE;
  104149. pNew->nLTerm = 0;
  104150. pNew->u.vtab.needFree = 0;
  104151. pUsage = pIdxInfo->aConstraintUsage;
  104152. nConstraint = pIdxInfo->nConstraint;
  104153. if( whereLoopResize(db, pNew, nConstraint) ){
  104154. sqlite3DbFree(db, pIdxInfo);
  104155. return SQLITE_NOMEM;
  104156. }
  104157. for(iPhase=0; iPhase<=3; iPhase++){
  104158. if( !seenIn && (iPhase&1)!=0 ){
  104159. iPhase++;
  104160. if( iPhase>3 ) break;
  104161. }
  104162. if( !seenVar && iPhase>1 ) break;
  104163. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  104164. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  104165. j = pIdxCons->iTermOffset;
  104166. pTerm = &pWC->a[j];
  104167. switch( iPhase ){
  104168. case 0: /* Constants without IN operator */
  104169. pIdxCons->usable = 0;
  104170. if( (pTerm->eOperator & WO_IN)!=0 ){
  104171. seenIn = 1;
  104172. }
  104173. if( pTerm->prereqRight!=0 ){
  104174. seenVar = 1;
  104175. }else if( (pTerm->eOperator & WO_IN)==0 ){
  104176. pIdxCons->usable = 1;
  104177. }
  104178. break;
  104179. case 1: /* Constants with IN operators */
  104180. assert( seenIn );
  104181. pIdxCons->usable = (pTerm->prereqRight==0);
  104182. break;
  104183. case 2: /* Variables without IN */
  104184. assert( seenVar );
  104185. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  104186. break;
  104187. default: /* Variables with IN */
  104188. assert( seenVar && seenIn );
  104189. pIdxCons->usable = 1;
  104190. break;
  104191. }
  104192. }
  104193. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  104194. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  104195. pIdxInfo->idxStr = 0;
  104196. pIdxInfo->idxNum = 0;
  104197. pIdxInfo->needToFreeIdxStr = 0;
  104198. pIdxInfo->orderByConsumed = 0;
  104199. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  104200. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  104201. if( rc ) goto whereLoopAddVtab_exit;
  104202. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  104203. pNew->prereq = 0;
  104204. mxTerm = -1;
  104205. assert( pNew->nLSlot>=nConstraint );
  104206. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  104207. pNew->u.vtab.omitMask = 0;
  104208. for(i=0; i<nConstraint; i++, pIdxCons++){
  104209. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  104210. j = pIdxCons->iTermOffset;
  104211. if( iTerm>=nConstraint
  104212. || j<0
  104213. || j>=pWC->nTerm
  104214. || pNew->aLTerm[iTerm]!=0
  104215. ){
  104216. rc = SQLITE_ERROR;
  104217. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  104218. goto whereLoopAddVtab_exit;
  104219. }
  104220. testcase( iTerm==nConstraint-1 );
  104221. testcase( j==0 );
  104222. testcase( j==pWC->nTerm-1 );
  104223. pTerm = &pWC->a[j];
  104224. pNew->prereq |= pTerm->prereqRight;
  104225. assert( iTerm<pNew->nLSlot );
  104226. pNew->aLTerm[iTerm] = pTerm;
  104227. if( iTerm>mxTerm ) mxTerm = iTerm;
  104228. testcase( iTerm==15 );
  104229. testcase( iTerm==16 );
  104230. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  104231. if( (pTerm->eOperator & WO_IN)!=0 ){
  104232. if( pUsage[i].omit==0 ){
  104233. /* Do not attempt to use an IN constraint if the virtual table
  104234. ** says that the equivalent EQ constraint cannot be safely omitted.
  104235. ** If we do attempt to use such a constraint, some rows might be
  104236. ** repeated in the output. */
  104237. break;
  104238. }
  104239. /* A virtual table that is constrained by an IN clause may not
  104240. ** consume the ORDER BY clause because (1) the order of IN terms
  104241. ** is not necessarily related to the order of output terms and
  104242. ** (2) Multiple outputs from a single IN value will not merge
  104243. ** together. */
  104244. pIdxInfo->orderByConsumed = 0;
  104245. }
  104246. }
  104247. }
  104248. if( i>=nConstraint ){
  104249. pNew->nLTerm = mxTerm+1;
  104250. assert( pNew->nLTerm<=pNew->nLSlot );
  104251. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  104252. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  104253. pIdxInfo->needToFreeIdxStr = 0;
  104254. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  104255. pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
  104256. && pIdxInfo->orderByConsumed);
  104257. pNew->rSetup = 0;
  104258. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  104259. /* TUNING: Every virtual table query returns 25 rows */
  104260. pNew->nOut = 46; assert( 46==sqlite3LogEst(25) );
  104261. whereLoopInsert(pBuilder, pNew);
  104262. if( pNew->u.vtab.needFree ){
  104263. sqlite3_free(pNew->u.vtab.idxStr);
  104264. pNew->u.vtab.needFree = 0;
  104265. }
  104266. }
  104267. }
  104268. whereLoopAddVtab_exit:
  104269. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  104270. sqlite3DbFree(db, pIdxInfo);
  104271. return rc;
  104272. }
  104273. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  104274. /*
  104275. ** Add WhereLoop entries to handle OR terms. This works for either
  104276. ** btrees or virtual tables.
  104277. */
  104278. static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
  104279. WhereInfo *pWInfo = pBuilder->pWInfo;
  104280. WhereClause *pWC;
  104281. WhereLoop *pNew;
  104282. WhereTerm *pTerm, *pWCEnd;
  104283. int rc = SQLITE_OK;
  104284. int iCur;
  104285. WhereClause tempWC;
  104286. WhereLoopBuilder sSubBuild;
  104287. WhereOrSet sSum, sCur, sPrev;
  104288. struct SrcList_item *pItem;
  104289. pWC = pBuilder->pWC;
  104290. if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
  104291. pWCEnd = pWC->a + pWC->nTerm;
  104292. pNew = pBuilder->pNew;
  104293. memset(&sSum, 0, sizeof(sSum));
  104294. pItem = pWInfo->pTabList->a + pNew->iTab;
  104295. iCur = pItem->iCursor;
  104296. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  104297. if( (pTerm->eOperator & WO_OR)!=0
  104298. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  104299. ){
  104300. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  104301. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  104302. WhereTerm *pOrTerm;
  104303. int once = 1;
  104304. int i, j;
  104305. sSubBuild = *pBuilder;
  104306. sSubBuild.pOrderBy = 0;
  104307. sSubBuild.pOrSet = &sCur;
  104308. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  104309. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  104310. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  104311. }else if( pOrTerm->leftCursor==iCur ){
  104312. tempWC.pWInfo = pWC->pWInfo;
  104313. tempWC.pOuter = pWC;
  104314. tempWC.op = TK_AND;
  104315. tempWC.nTerm = 1;
  104316. tempWC.a = pOrTerm;
  104317. sSubBuild.pWC = &tempWC;
  104318. }else{
  104319. continue;
  104320. }
  104321. sCur.n = 0;
  104322. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104323. if( IsVirtual(pItem->pTab) ){
  104324. rc = whereLoopAddVirtual(&sSubBuild);
  104325. for(i=0; i<sCur.n; i++) sCur.a[i].prereq |= mExtra;
  104326. }else
  104327. #endif
  104328. {
  104329. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  104330. }
  104331. assert( rc==SQLITE_OK || sCur.n==0 );
  104332. if( sCur.n==0 ){
  104333. sSum.n = 0;
  104334. break;
  104335. }else if( once ){
  104336. whereOrMove(&sSum, &sCur);
  104337. once = 0;
  104338. }else{
  104339. whereOrMove(&sPrev, &sSum);
  104340. sSum.n = 0;
  104341. for(i=0; i<sPrev.n; i++){
  104342. for(j=0; j<sCur.n; j++){
  104343. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  104344. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  104345. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  104346. }
  104347. }
  104348. }
  104349. }
  104350. pNew->nLTerm = 1;
  104351. pNew->aLTerm[0] = pTerm;
  104352. pNew->wsFlags = WHERE_MULTI_OR;
  104353. pNew->rSetup = 0;
  104354. pNew->iSortIdx = 0;
  104355. memset(&pNew->u, 0, sizeof(pNew->u));
  104356. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  104357. /* TUNING: Multiple by 3.5 for the secondary table lookup */
  104358. pNew->rRun = sSum.a[i].rRun + 18;
  104359. pNew->nOut = sSum.a[i].nOut;
  104360. pNew->prereq = sSum.a[i].prereq;
  104361. rc = whereLoopInsert(pBuilder, pNew);
  104362. }
  104363. }
  104364. }
  104365. return rc;
  104366. }
  104367. /*
  104368. ** Add all WhereLoop objects for all tables
  104369. */
  104370. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  104371. WhereInfo *pWInfo = pBuilder->pWInfo;
  104372. Bitmask mExtra = 0;
  104373. Bitmask mPrior = 0;
  104374. int iTab;
  104375. SrcList *pTabList = pWInfo->pTabList;
  104376. struct SrcList_item *pItem;
  104377. sqlite3 *db = pWInfo->pParse->db;
  104378. int nTabList = pWInfo->nLevel;
  104379. int rc = SQLITE_OK;
  104380. u8 priorJoinType = 0;
  104381. WhereLoop *pNew;
  104382. /* Loop over the tables in the join, from left to right */
  104383. pNew = pBuilder->pNew;
  104384. whereLoopInit(pNew);
  104385. for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
  104386. pNew->iTab = iTab;
  104387. pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
  104388. if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
  104389. mExtra = mPrior;
  104390. }
  104391. priorJoinType = pItem->jointype;
  104392. if( IsVirtual(pItem->pTab) ){
  104393. rc = whereLoopAddVirtual(pBuilder);
  104394. }else{
  104395. rc = whereLoopAddBtree(pBuilder, mExtra);
  104396. }
  104397. if( rc==SQLITE_OK ){
  104398. rc = whereLoopAddOr(pBuilder, mExtra);
  104399. }
  104400. mPrior |= pNew->maskSelf;
  104401. if( rc || db->mallocFailed ) break;
  104402. }
  104403. whereLoopClear(db, pNew);
  104404. return rc;
  104405. }
  104406. /*
  104407. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  104408. ** parameters) to see if it outputs rows in the requested ORDER BY
  104409. ** (or GROUP BY) without requiring a separate sort operation. Return:
  104410. **
  104411. ** 0: ORDER BY is not satisfied. Sorting required
  104412. ** 1: ORDER BY is satisfied. Omit sorting
  104413. ** -1: Unknown at this time
  104414. **
  104415. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  104416. ** strict. With GROUP BY and DISTINCT the only requirement is that
  104417. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  104418. ** and DISTINT do not require rows to appear in any particular order as long
  104419. ** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
  104420. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  104421. ** pOrderBy terms must be matched in strict left-to-right order.
  104422. */
  104423. static int wherePathSatisfiesOrderBy(
  104424. WhereInfo *pWInfo, /* The WHERE clause */
  104425. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  104426. WherePath *pPath, /* The WherePath to check */
  104427. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  104428. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  104429. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  104430. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  104431. ){
  104432. u8 revSet; /* True if rev is known */
  104433. u8 rev; /* Composite sort order */
  104434. u8 revIdx; /* Index sort order */
  104435. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  104436. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  104437. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  104438. u16 nColumn; /* Number of columns in pIndex */
  104439. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  104440. int iLoop; /* Index of WhereLoop in pPath being processed */
  104441. int i, j; /* Loop counters */
  104442. int iCur; /* Cursor number for current WhereLoop */
  104443. int iColumn; /* A column number within table iCur */
  104444. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  104445. WhereTerm *pTerm; /* A single term of the WHERE clause */
  104446. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  104447. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  104448. Index *pIndex; /* The index associated with pLoop */
  104449. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  104450. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  104451. Bitmask obDone; /* Mask of all ORDER BY terms */
  104452. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  104453. Bitmask ready; /* Mask of inner loops */
  104454. /*
  104455. ** We say the WhereLoop is "one-row" if it generates no more than one
  104456. ** row of output. A WhereLoop is one-row if all of the following are true:
  104457. ** (a) All index columns match with WHERE_COLUMN_EQ.
  104458. ** (b) The index is unique
  104459. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  104460. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  104461. **
  104462. ** We say the WhereLoop is "order-distinct" if the set of columns from
  104463. ** that WhereLoop that are in the ORDER BY clause are different for every
  104464. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  104465. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  104466. ** is not order-distinct. To be order-distinct is not quite the same as being
  104467. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  104468. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  104469. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  104470. **
  104471. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  104472. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  104473. ** automatically order-distinct.
  104474. */
  104475. assert( pOrderBy!=0 );
  104476. /* Sortability of virtual tables is determined by the xBestIndex method
  104477. ** of the virtual table itself */
  104478. if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
  104479. testcase( nLoop>0 ); /* True when outer loops are one-row and match
  104480. ** no ORDER BY terms */
  104481. return pLast->u.vtab.isOrdered;
  104482. }
  104483. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  104484. nOrderBy = pOrderBy->nExpr;
  104485. testcase( nOrderBy==BMS-1 );
  104486. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  104487. isOrderDistinct = 1;
  104488. obDone = MASKBIT(nOrderBy)-1;
  104489. orderDistinctMask = 0;
  104490. ready = 0;
  104491. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  104492. if( iLoop>0 ) ready |= pLoop->maskSelf;
  104493. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  104494. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  104495. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  104496. /* Mark off any ORDER BY term X that is a column in the table of
  104497. ** the current loop for which there is term in the WHERE
  104498. ** clause of the form X IS NULL or X=? that reference only outer
  104499. ** loops.
  104500. */
  104501. for(i=0; i<nOrderBy; i++){
  104502. if( MASKBIT(i) & obSat ) continue;
  104503. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  104504. if( pOBExpr->op!=TK_COLUMN ) continue;
  104505. if( pOBExpr->iTable!=iCur ) continue;
  104506. pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  104507. ~ready, WO_EQ|WO_ISNULL, 0);
  104508. if( pTerm==0 ) continue;
  104509. if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
  104510. const char *z1, *z2;
  104511. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  104512. if( !pColl ) pColl = db->pDfltColl;
  104513. z1 = pColl->zName;
  104514. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  104515. if( !pColl ) pColl = db->pDfltColl;
  104516. z2 = pColl->zName;
  104517. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  104518. }
  104519. obSat |= MASKBIT(i);
  104520. }
  104521. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  104522. if( pLoop->wsFlags & WHERE_IPK ){
  104523. pIndex = 0;
  104524. nColumn = 0;
  104525. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  104526. return 0;
  104527. }else{
  104528. nColumn = pIndex->nColumn;
  104529. isOrderDistinct = pIndex->onError!=OE_None;
  104530. }
  104531. /* Loop through all columns of the index and deal with the ones
  104532. ** that are not constrained by == or IN.
  104533. */
  104534. rev = revSet = 0;
  104535. distinctColumns = 0;
  104536. for(j=0; j<=nColumn; j++){
  104537. u8 bOnce; /* True to run the ORDER BY search loop */
  104538. /* Skip over == and IS NULL terms */
  104539. if( j<pLoop->u.btree.nEq
  104540. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
  104541. ){
  104542. if( i & WO_ISNULL ){
  104543. testcase( isOrderDistinct );
  104544. isOrderDistinct = 0;
  104545. }
  104546. continue;
  104547. }
  104548. /* Get the column number in the table (iColumn) and sort order
  104549. ** (revIdx) for the j-th column of the index.
  104550. */
  104551. if( j<nColumn ){
  104552. /* Normal index columns */
  104553. iColumn = pIndex->aiColumn[j];
  104554. revIdx = pIndex->aSortOrder[j];
  104555. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  104556. }else{
  104557. /* The ROWID column at the end */
  104558. assert( j==nColumn );
  104559. iColumn = -1;
  104560. revIdx = 0;
  104561. }
  104562. /* An unconstrained column that might be NULL means that this
  104563. ** WhereLoop is not well-ordered
  104564. */
  104565. if( isOrderDistinct
  104566. && iColumn>=0
  104567. && j>=pLoop->u.btree.nEq
  104568. && pIndex->pTable->aCol[iColumn].notNull==0
  104569. ){
  104570. isOrderDistinct = 0;
  104571. }
  104572. /* Find the ORDER BY term that corresponds to the j-th column
  104573. ** of the index and and mark that ORDER BY term off
  104574. */
  104575. bOnce = 1;
  104576. isMatch = 0;
  104577. for(i=0; bOnce && i<nOrderBy; i++){
  104578. if( MASKBIT(i) & obSat ) continue;
  104579. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  104580. testcase( wctrlFlags & WHERE_GROUPBY );
  104581. testcase( wctrlFlags & WHERE_DISTINCTBY );
  104582. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  104583. if( pOBExpr->op!=TK_COLUMN ) continue;
  104584. if( pOBExpr->iTable!=iCur ) continue;
  104585. if( pOBExpr->iColumn!=iColumn ) continue;
  104586. if( iColumn>=0 ){
  104587. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  104588. if( !pColl ) pColl = db->pDfltColl;
  104589. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  104590. }
  104591. isMatch = 1;
  104592. break;
  104593. }
  104594. if( isMatch ){
  104595. if( iColumn<0 ){
  104596. testcase( distinctColumns==0 );
  104597. distinctColumns = 1;
  104598. }
  104599. obSat |= MASKBIT(i);
  104600. if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
  104601. /* Make sure the sort order is compatible in an ORDER BY clause.
  104602. ** Sort order is irrelevant for a GROUP BY clause. */
  104603. if( revSet ){
  104604. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
  104605. }else{
  104606. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  104607. if( rev ) *pRevMask |= MASKBIT(iLoop);
  104608. revSet = 1;
  104609. }
  104610. }
  104611. }else{
  104612. /* No match found */
  104613. if( j==0 || j<nColumn ){
  104614. testcase( isOrderDistinct!=0 );
  104615. isOrderDistinct = 0;
  104616. }
  104617. break;
  104618. }
  104619. } /* end Loop over all index columns */
  104620. if( distinctColumns ){
  104621. testcase( isOrderDistinct==0 );
  104622. isOrderDistinct = 1;
  104623. }
  104624. } /* end-if not one-row */
  104625. /* Mark off any other ORDER BY terms that reference pLoop */
  104626. if( isOrderDistinct ){
  104627. orderDistinctMask |= pLoop->maskSelf;
  104628. for(i=0; i<nOrderBy; i++){
  104629. Expr *p;
  104630. if( MASKBIT(i) & obSat ) continue;
  104631. p = pOrderBy->a[i].pExpr;
  104632. if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
  104633. obSat |= MASKBIT(i);
  104634. }
  104635. }
  104636. }
  104637. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  104638. if( obSat==obDone ) return 1;
  104639. if( !isOrderDistinct ) return 0;
  104640. return -1;
  104641. }
  104642. #ifdef WHERETRACE_ENABLED
  104643. /* For debugging use only: */
  104644. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  104645. static char zName[65];
  104646. int i;
  104647. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  104648. if( pLast ) zName[i++] = pLast->cId;
  104649. zName[i] = 0;
  104650. return zName;
  104651. }
  104652. #endif
  104653. /*
  104654. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  104655. ** attempts to find the lowest cost path that visits each WhereLoop
  104656. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  104657. **
  104658. ** Assume that the total number of output rows that will need to be sorted
  104659. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  104660. ** costs if nRowEst==0.
  104661. **
  104662. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  104663. ** error occurs.
  104664. */
  104665. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  104666. int mxChoice; /* Maximum number of simultaneous paths tracked */
  104667. int nLoop; /* Number of terms in the join */
  104668. Parse *pParse; /* Parsing context */
  104669. sqlite3 *db; /* The database connection */
  104670. int iLoop; /* Loop counter over the terms of the join */
  104671. int ii, jj; /* Loop counters */
  104672. int mxI = 0; /* Index of next entry to replace */
  104673. LogEst rCost; /* Cost of a path */
  104674. LogEst nOut; /* Number of outputs */
  104675. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  104676. LogEst mxOut = 0; /* Maximum nOut value on the set of paths */
  104677. LogEst rSortCost; /* Cost to do a sort */
  104678. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  104679. WherePath *aFrom; /* All nFrom paths at the previous level */
  104680. WherePath *aTo; /* The nTo best paths at the current level */
  104681. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  104682. WherePath *pTo; /* An element of aTo[] that we are working on */
  104683. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  104684. WhereLoop **pX; /* Used to divy up the pSpace memory */
  104685. char *pSpace; /* Temporary memory used by this routine */
  104686. pParse = pWInfo->pParse;
  104687. db = pParse->db;
  104688. nLoop = pWInfo->nLevel;
  104689. /* TUNING: For simple queries, only the best path is tracked.
  104690. ** For 2-way joins, the 5 best paths are followed.
  104691. ** For joins of 3 or more tables, track the 10 best paths */
  104692. mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
  104693. assert( nLoop<=pWInfo->pTabList->nSrc );
  104694. WHERETRACE(0x002, ("---- begin solver\n"));
  104695. /* Allocate and initialize space for aTo and aFrom */
  104696. ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  104697. pSpace = sqlite3DbMallocRaw(db, ii);
  104698. if( pSpace==0 ) return SQLITE_NOMEM;
  104699. aTo = (WherePath*)pSpace;
  104700. aFrom = aTo+mxChoice;
  104701. memset(aFrom, 0, sizeof(aFrom[0]));
  104702. pX = (WhereLoop**)(aFrom+mxChoice);
  104703. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  104704. pFrom->aLoop = pX;
  104705. }
  104706. /* Seed the search with a single WherePath containing zero WhereLoops.
  104707. **
  104708. ** TUNING: Do not let the number of iterations go above 25. If the cost
  104709. ** of computing an automatic index is not paid back within the first 25
  104710. ** rows, then do not use the automatic index. */
  104711. aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
  104712. nFrom = 1;
  104713. /* Precompute the cost of sorting the final result set, if the caller
  104714. ** to sqlite3WhereBegin() was concerned about sorting */
  104715. rSortCost = 0;
  104716. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  104717. aFrom[0].isOrderedValid = 1;
  104718. }else{
  104719. /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
  104720. ** number of output rows. The 48 is the expected size of a row to sort.
  104721. ** FIXME: compute a better estimate of the 48 multiplier based on the
  104722. ** result set expressions. */
  104723. rSortCost = nRowEst + estLog(nRowEst);
  104724. WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
  104725. }
  104726. /* Compute successively longer WherePaths using the previous generation
  104727. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  104728. ** best paths at each generation */
  104729. for(iLoop=0; iLoop<nLoop; iLoop++){
  104730. nTo = 0;
  104731. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  104732. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  104733. Bitmask maskNew;
  104734. Bitmask revMask = 0;
  104735. u8 isOrderedValid = pFrom->isOrderedValid;
  104736. u8 isOrdered = pFrom->isOrdered;
  104737. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  104738. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  104739. /* At this point, pWLoop is a candidate to be the next loop.
  104740. ** Compute its cost */
  104741. rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  104742. rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
  104743. nOut = pFrom->nRow + pWLoop->nOut;
  104744. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  104745. if( !isOrderedValid ){
  104746. switch( wherePathSatisfiesOrderBy(pWInfo,
  104747. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  104748. iLoop, pWLoop, &revMask) ){
  104749. case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
  104750. isOrdered = 1;
  104751. isOrderedValid = 1;
  104752. break;
  104753. case 0: /* No. pFrom+pWLoop will require a separate sort */
  104754. isOrdered = 0;
  104755. isOrderedValid = 1;
  104756. rCost = sqlite3LogEstAdd(rCost, rSortCost);
  104757. break;
  104758. default: /* Cannot tell yet. Try again on the next iteration */
  104759. break;
  104760. }
  104761. }else{
  104762. revMask = pFrom->revLoop;
  104763. }
  104764. /* Check to see if pWLoop should be added to the mxChoice best so far */
  104765. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  104766. if( pTo->maskLoop==maskNew
  104767. && pTo->isOrderedValid==isOrderedValid
  104768. && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
  104769. (pTo->rCost>=rCost && pTo->nRow>=nOut))
  104770. ){
  104771. testcase( jj==nTo-1 );
  104772. break;
  104773. }
  104774. }
  104775. if( jj>=nTo ){
  104776. if( nTo>=mxChoice && rCost>=mxCost ){
  104777. #ifdef WHERETRACE_ENABLED
  104778. if( sqlite3WhereTrace&0x4 ){
  104779. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  104780. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  104781. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  104782. }
  104783. #endif
  104784. continue;
  104785. }
  104786. /* Add a new Path to the aTo[] set */
  104787. if( nTo<mxChoice ){
  104788. /* Increase the size of the aTo set by one */
  104789. jj = nTo++;
  104790. }else{
  104791. /* New path replaces the prior worst to keep count below mxChoice */
  104792. jj = mxI;
  104793. }
  104794. pTo = &aTo[jj];
  104795. #ifdef WHERETRACE_ENABLED
  104796. if( sqlite3WhereTrace&0x4 ){
  104797. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  104798. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  104799. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  104800. }
  104801. #endif
  104802. }else{
  104803. if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
  104804. #ifdef WHERETRACE_ENABLED
  104805. if( sqlite3WhereTrace&0x4 ){
  104806. sqlite3DebugPrintf(
  104807. "Skip %s cost=%-3d,%3d order=%c",
  104808. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  104809. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  104810. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  104811. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  104812. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  104813. }
  104814. #endif
  104815. testcase( pTo->rCost==rCost );
  104816. continue;
  104817. }
  104818. testcase( pTo->rCost==rCost+1 );
  104819. /* A new and better score for a previously created equivalent path */
  104820. #ifdef WHERETRACE_ENABLED
  104821. if( sqlite3WhereTrace&0x4 ){
  104822. sqlite3DebugPrintf(
  104823. "Update %s cost=%-3d,%3d order=%c",
  104824. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  104825. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  104826. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  104827. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  104828. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  104829. }
  104830. #endif
  104831. }
  104832. /* pWLoop is a winner. Add it to the set of best so far */
  104833. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  104834. pTo->revLoop = revMask;
  104835. pTo->nRow = nOut;
  104836. pTo->rCost = rCost;
  104837. pTo->isOrderedValid = isOrderedValid;
  104838. pTo->isOrdered = isOrdered;
  104839. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  104840. pTo->aLoop[iLoop] = pWLoop;
  104841. if( nTo>=mxChoice ){
  104842. mxI = 0;
  104843. mxCost = aTo[0].rCost;
  104844. mxOut = aTo[0].nRow;
  104845. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  104846. if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
  104847. mxCost = pTo->rCost;
  104848. mxOut = pTo->nRow;
  104849. mxI = jj;
  104850. }
  104851. }
  104852. }
  104853. }
  104854. }
  104855. #ifdef WHERETRACE_ENABLED
  104856. if( sqlite3WhereTrace>=2 ){
  104857. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  104858. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  104859. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  104860. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  104861. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  104862. if( pTo->isOrderedValid && pTo->isOrdered ){
  104863. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  104864. }else{
  104865. sqlite3DebugPrintf("\n");
  104866. }
  104867. }
  104868. }
  104869. #endif
  104870. /* Swap the roles of aFrom and aTo for the next generation */
  104871. pFrom = aTo;
  104872. aTo = aFrom;
  104873. aFrom = pFrom;
  104874. nFrom = nTo;
  104875. }
  104876. if( nFrom==0 ){
  104877. sqlite3ErrorMsg(pParse, "no query solution");
  104878. sqlite3DbFree(db, pSpace);
  104879. return SQLITE_ERROR;
  104880. }
  104881. /* Find the lowest cost path. pFrom will be left pointing to that path */
  104882. pFrom = aFrom;
  104883. for(ii=1; ii<nFrom; ii++){
  104884. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  104885. }
  104886. assert( pWInfo->nLevel==nLoop );
  104887. /* Load the lowest cost path into pWInfo */
  104888. for(iLoop=0; iLoop<nLoop; iLoop++){
  104889. WhereLevel *pLevel = pWInfo->a + iLoop;
  104890. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  104891. pLevel->iFrom = pWLoop->iTab;
  104892. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  104893. }
  104894. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  104895. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  104896. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  104897. && nRowEst
  104898. ){
  104899. Bitmask notUsed;
  104900. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  104901. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  104902. if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  104903. }
  104904. if( pFrom->isOrdered ){
  104905. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  104906. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  104907. }else{
  104908. pWInfo->bOBSat = 1;
  104909. pWInfo->revMask = pFrom->revLoop;
  104910. }
  104911. }
  104912. pWInfo->nRowOut = pFrom->nRow;
  104913. /* Free temporary memory and return success */
  104914. sqlite3DbFree(db, pSpace);
  104915. return SQLITE_OK;
  104916. }
  104917. /*
  104918. ** Most queries use only a single table (they are not joins) and have
  104919. ** simple == constraints against indexed fields. This routine attempts
  104920. ** to plan those simple cases using much less ceremony than the
  104921. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  104922. ** times for the common case.
  104923. **
  104924. ** Return non-zero on success, if this query can be handled by this
  104925. ** no-frills query planner. Return zero if this query needs the
  104926. ** general-purpose query planner.
  104927. */
  104928. static int whereShortCut(WhereLoopBuilder *pBuilder){
  104929. WhereInfo *pWInfo;
  104930. struct SrcList_item *pItem;
  104931. WhereClause *pWC;
  104932. WhereTerm *pTerm;
  104933. WhereLoop *pLoop;
  104934. int iCur;
  104935. int j;
  104936. Table *pTab;
  104937. Index *pIdx;
  104938. pWInfo = pBuilder->pWInfo;
  104939. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  104940. assert( pWInfo->pTabList->nSrc>=1 );
  104941. pItem = pWInfo->pTabList->a;
  104942. pTab = pItem->pTab;
  104943. if( IsVirtual(pTab) ) return 0;
  104944. if( pItem->zIndex ) return 0;
  104945. iCur = pItem->iCursor;
  104946. pWC = &pWInfo->sWC;
  104947. pLoop = pBuilder->pNew;
  104948. pLoop->wsFlags = 0;
  104949. pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
  104950. if( pTerm ){
  104951. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  104952. pLoop->aLTerm[0] = pTerm;
  104953. pLoop->nLTerm = 1;
  104954. pLoop->u.btree.nEq = 1;
  104955. /* TUNING: Cost of a rowid lookup is 10 */
  104956. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  104957. }else{
  104958. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  104959. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  104960. assert( ArraySize(pLoop->aLTermSpace)==4 );
  104961. if( pIdx->onError==OE_None
  104962. || pIdx->pPartIdxWhere!=0
  104963. || pIdx->nColumn>ArraySize(pLoop->aLTermSpace)
  104964. ) continue;
  104965. for(j=0; j<pIdx->nColumn; j++){
  104966. pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
  104967. if( pTerm==0 ) break;
  104968. pLoop->aLTerm[j] = pTerm;
  104969. }
  104970. if( j!=pIdx->nColumn ) continue;
  104971. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  104972. if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  104973. pLoop->wsFlags |= WHERE_IDX_ONLY;
  104974. }
  104975. pLoop->nLTerm = j;
  104976. pLoop->u.btree.nEq = j;
  104977. pLoop->u.btree.pIndex = pIdx;
  104978. /* TUNING: Cost of a unique index lookup is 15 */
  104979. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  104980. break;
  104981. }
  104982. }
  104983. if( pLoop->wsFlags ){
  104984. pLoop->nOut = (LogEst)1;
  104985. pWInfo->a[0].pWLoop = pLoop;
  104986. pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
  104987. pWInfo->a[0].iTabCur = iCur;
  104988. pWInfo->nRowOut = 1;
  104989. if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
  104990. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  104991. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  104992. }
  104993. #ifdef SQLITE_DEBUG
  104994. pLoop->cId = '0';
  104995. #endif
  104996. return 1;
  104997. }
  104998. return 0;
  104999. }
  105000. /*
  105001. ** Generate the beginning of the loop used for WHERE clause processing.
  105002. ** The return value is a pointer to an opaque structure that contains
  105003. ** information needed to terminate the loop. Later, the calling routine
  105004. ** should invoke sqlite3WhereEnd() with the return value of this function
  105005. ** in order to complete the WHERE clause processing.
  105006. **
  105007. ** If an error occurs, this routine returns NULL.
  105008. **
  105009. ** The basic idea is to do a nested loop, one loop for each table in
  105010. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  105011. ** same as a SELECT with only a single table in the FROM clause.) For
  105012. ** example, if the SQL is this:
  105013. **
  105014. ** SELECT * FROM t1, t2, t3 WHERE ...;
  105015. **
  105016. ** Then the code generated is conceptually like the following:
  105017. **
  105018. ** foreach row1 in t1 do \ Code generated
  105019. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  105020. ** foreach row3 in t3 do /
  105021. ** ...
  105022. ** end \ Code generated
  105023. ** end |-- by sqlite3WhereEnd()
  105024. ** end /
  105025. **
  105026. ** Note that the loops might not be nested in the order in which they
  105027. ** appear in the FROM clause if a different order is better able to make
  105028. ** use of indices. Note also that when the IN operator appears in
  105029. ** the WHERE clause, it might result in additional nested loops for
  105030. ** scanning through all values on the right-hand side of the IN.
  105031. **
  105032. ** There are Btree cursors associated with each table. t1 uses cursor
  105033. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  105034. ** And so forth. This routine generates code to open those VDBE cursors
  105035. ** and sqlite3WhereEnd() generates the code to close them.
  105036. **
  105037. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  105038. ** in pTabList pointing at their appropriate entries. The [...] code
  105039. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  105040. ** data from the various tables of the loop.
  105041. **
  105042. ** If the WHERE clause is empty, the foreach loops must each scan their
  105043. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  105044. ** the tables have indices and there are terms in the WHERE clause that
  105045. ** refer to those indices, a complete table scan can be avoided and the
  105046. ** code will run much faster. Most of the work of this routine is checking
  105047. ** to see if there are indices that can be used to speed up the loop.
  105048. **
  105049. ** Terms of the WHERE clause are also used to limit which rows actually
  105050. ** make it to the "..." in the middle of the loop. After each "foreach",
  105051. ** terms of the WHERE clause that use only terms in that loop and outer
  105052. ** loops are evaluated and if false a jump is made around all subsequent
  105053. ** inner loops (or around the "..." if the test occurs within the inner-
  105054. ** most loop)
  105055. **
  105056. ** OUTER JOINS
  105057. **
  105058. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  105059. **
  105060. ** foreach row1 in t1 do
  105061. ** flag = 0
  105062. ** foreach row2 in t2 do
  105063. ** start:
  105064. ** ...
  105065. ** flag = 1
  105066. ** end
  105067. ** if flag==0 then
  105068. ** move the row2 cursor to a null row
  105069. ** goto start
  105070. ** fi
  105071. ** end
  105072. **
  105073. ** ORDER BY CLAUSE PROCESSING
  105074. **
  105075. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  105076. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  105077. ** if there is one. If there is no ORDER BY clause or if this routine
  105078. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  105079. */
  105080. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  105081. Parse *pParse, /* The parser context */
  105082. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  105083. Expr *pWhere, /* The WHERE clause */
  105084. ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
  105085. ExprList *pResultSet, /* Result set of the query */
  105086. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  105087. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  105088. ){
  105089. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  105090. int nTabList; /* Number of elements in pTabList */
  105091. WhereInfo *pWInfo; /* Will become the return value of this function */
  105092. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  105093. Bitmask notReady; /* Cursors that are not yet positioned */
  105094. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  105095. WhereMaskSet *pMaskSet; /* The expression mask set */
  105096. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  105097. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  105098. int ii; /* Loop counter */
  105099. sqlite3 *db; /* Database connection */
  105100. int rc; /* Return code */
  105101. /* Variable initialization */
  105102. db = pParse->db;
  105103. memset(&sWLB, 0, sizeof(sWLB));
  105104. sWLB.pOrderBy = pOrderBy;
  105105. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  105106. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  105107. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  105108. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  105109. }
  105110. /* The number of tables in the FROM clause is limited by the number of
  105111. ** bits in a Bitmask
  105112. */
  105113. testcase( pTabList->nSrc==BMS );
  105114. if( pTabList->nSrc>BMS ){
  105115. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  105116. return 0;
  105117. }
  105118. /* This function normally generates a nested loop for all tables in
  105119. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  105120. ** only generate code for the first table in pTabList and assume that
  105121. ** any cursors associated with subsequent tables are uninitialized.
  105122. */
  105123. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  105124. /* Allocate and initialize the WhereInfo structure that will become the
  105125. ** return value. A single allocation is used to store the WhereInfo
  105126. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  105127. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  105128. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  105129. ** some architectures. Hence the ROUND8() below.
  105130. */
  105131. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  105132. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  105133. if( db->mallocFailed ){
  105134. sqlite3DbFree(db, pWInfo);
  105135. pWInfo = 0;
  105136. goto whereBeginError;
  105137. }
  105138. pWInfo->nLevel = nTabList;
  105139. pWInfo->pParse = pParse;
  105140. pWInfo->pTabList = pTabList;
  105141. pWInfo->pOrderBy = pOrderBy;
  105142. pWInfo->pResultSet = pResultSet;
  105143. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  105144. pWInfo->wctrlFlags = wctrlFlags;
  105145. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  105146. pMaskSet = &pWInfo->sMaskSet;
  105147. sWLB.pWInfo = pWInfo;
  105148. sWLB.pWC = &pWInfo->sWC;
  105149. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  105150. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  105151. whereLoopInit(sWLB.pNew);
  105152. #ifdef SQLITE_DEBUG
  105153. sWLB.pNew->cId = '*';
  105154. #endif
  105155. /* Split the WHERE clause into separate subexpressions where each
  105156. ** subexpression is separated by an AND operator.
  105157. */
  105158. initMaskSet(pMaskSet);
  105159. whereClauseInit(&pWInfo->sWC, pWInfo);
  105160. sqlite3ExprCodeConstants(pParse, pWhere);
  105161. whereSplit(&pWInfo->sWC, pWhere, TK_AND);
  105162. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  105163. /* Special case: a WHERE clause that is constant. Evaluate the
  105164. ** expression and either jump over all of the code or fall thru.
  105165. */
  105166. if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  105167. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  105168. pWhere = 0;
  105169. }
  105170. /* Special case: No FROM clause
  105171. */
  105172. if( nTabList==0 ){
  105173. if( pOrderBy ) pWInfo->bOBSat = 1;
  105174. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  105175. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  105176. }
  105177. }
  105178. /* Assign a bit from the bitmask to every term in the FROM clause.
  105179. **
  105180. ** When assigning bitmask values to FROM clause cursors, it must be
  105181. ** the case that if X is the bitmask for the N-th FROM clause term then
  105182. ** the bitmask for all FROM clause terms to the left of the N-th term
  105183. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  105184. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  105185. ** of the join. Subtracting one from the right table bitmask gives a
  105186. ** bitmask for all tables to the left of the join. Knowing the bitmask
  105187. ** for all tables to the left of a left join is important. Ticket #3015.
  105188. **
  105189. ** Note that bitmasks are created for all pTabList->nSrc tables in
  105190. ** pTabList, not just the first nTabList tables. nTabList is normally
  105191. ** equal to pTabList->nSrc but might be shortened to 1 if the
  105192. ** WHERE_ONETABLE_ONLY flag is set.
  105193. */
  105194. for(ii=0; ii<pTabList->nSrc; ii++){
  105195. createMask(pMaskSet, pTabList->a[ii].iCursor);
  105196. }
  105197. #ifndef NDEBUG
  105198. {
  105199. Bitmask toTheLeft = 0;
  105200. for(ii=0; ii<pTabList->nSrc; ii++){
  105201. Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
  105202. assert( (m-1)==toTheLeft );
  105203. toTheLeft |= m;
  105204. }
  105205. }
  105206. #endif
  105207. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  105208. ** add new virtual terms onto the end of the WHERE clause. We do not
  105209. ** want to analyze these virtual terms, so start analyzing at the end
  105210. ** and work forward so that the added virtual terms are never processed.
  105211. */
  105212. exprAnalyzeAll(pTabList, &pWInfo->sWC);
  105213. if( db->mallocFailed ){
  105214. goto whereBeginError;
  105215. }
  105216. /* If the ORDER BY (or GROUP BY) clause contains references to general
  105217. ** expressions, then we won't be able to satisfy it using indices, so
  105218. ** go ahead and disable it now.
  105219. */
  105220. if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
  105221. for(ii=0; ii<pOrderBy->nExpr; ii++){
  105222. Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
  105223. if( pExpr->op!=TK_COLUMN ){
  105224. pWInfo->pOrderBy = pOrderBy = 0;
  105225. break;
  105226. }else if( pExpr->iColumn<0 ){
  105227. break;
  105228. }
  105229. }
  105230. }
  105231. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  105232. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  105233. /* The DISTINCT marking is pointless. Ignore it. */
  105234. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  105235. }else if( pOrderBy==0 ){
  105236. /* Try to ORDER BY the result set to make distinct processing easier */
  105237. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  105238. pWInfo->pOrderBy = pResultSet;
  105239. }
  105240. }
  105241. /* Construct the WhereLoop objects */
  105242. WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
  105243. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  105244. rc = whereLoopAddAll(&sWLB);
  105245. if( rc ) goto whereBeginError;
  105246. /* Display all of the WhereLoop objects if wheretrace is enabled */
  105247. #ifdef WHERETRACE_ENABLED
  105248. if( sqlite3WhereTrace ){
  105249. WhereLoop *p;
  105250. int i;
  105251. static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  105252. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  105253. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  105254. p->cId = zLabel[i%sizeof(zLabel)];
  105255. whereLoopPrint(p, pTabList);
  105256. }
  105257. }
  105258. #endif
  105259. wherePathSolver(pWInfo, 0);
  105260. if( db->mallocFailed ) goto whereBeginError;
  105261. if( pWInfo->pOrderBy ){
  105262. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  105263. if( db->mallocFailed ) goto whereBeginError;
  105264. }
  105265. }
  105266. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  105267. pWInfo->revMask = (Bitmask)(-1);
  105268. }
  105269. if( pParse->nErr || NEVER(db->mallocFailed) ){
  105270. goto whereBeginError;
  105271. }
  105272. #ifdef WHERETRACE_ENABLED
  105273. if( sqlite3WhereTrace ){
  105274. int ii;
  105275. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  105276. if( pWInfo->bOBSat ){
  105277. sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
  105278. }
  105279. switch( pWInfo->eDistinct ){
  105280. case WHERE_DISTINCT_UNIQUE: {
  105281. sqlite3DebugPrintf(" DISTINCT=unique");
  105282. break;
  105283. }
  105284. case WHERE_DISTINCT_ORDERED: {
  105285. sqlite3DebugPrintf(" DISTINCT=ordered");
  105286. break;
  105287. }
  105288. case WHERE_DISTINCT_UNORDERED: {
  105289. sqlite3DebugPrintf(" DISTINCT=unordered");
  105290. break;
  105291. }
  105292. }
  105293. sqlite3DebugPrintf("\n");
  105294. for(ii=0; ii<pWInfo->nLevel; ii++){
  105295. whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
  105296. }
  105297. }
  105298. #endif
  105299. /* Attempt to omit tables from the join that do not effect the result */
  105300. if( pWInfo->nLevel>=2
  105301. && pResultSet!=0
  105302. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  105303. ){
  105304. Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
  105305. if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
  105306. while( pWInfo->nLevel>=2 ){
  105307. WhereTerm *pTerm, *pEnd;
  105308. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  105309. if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
  105310. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  105311. && (pLoop->wsFlags & WHERE_ONEROW)==0
  105312. ){
  105313. break;
  105314. }
  105315. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  105316. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  105317. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  105318. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  105319. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  105320. ){
  105321. break;
  105322. }
  105323. }
  105324. if( pTerm<pEnd ) break;
  105325. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  105326. pWInfo->nLevel--;
  105327. nTabList--;
  105328. }
  105329. }
  105330. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  105331. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  105332. /* If the caller is an UPDATE or DELETE statement that is requesting
  105333. ** to use a one-pass algorithm, determine if this is appropriate.
  105334. ** The one-pass algorithm only works if the WHERE clause constrains
  105335. ** the statement to update a single row.
  105336. */
  105337. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  105338. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  105339. && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
  105340. pWInfo->okOnePass = 1;
  105341. pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
  105342. }
  105343. /* Open all tables in the pTabList and any indices selected for
  105344. ** searching those tables.
  105345. */
  105346. notReady = ~(Bitmask)0;
  105347. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  105348. Table *pTab; /* Table to open */
  105349. int iDb; /* Index of database containing table/index */
  105350. struct SrcList_item *pTabItem;
  105351. pTabItem = &pTabList->a[pLevel->iFrom];
  105352. pTab = pTabItem->pTab;
  105353. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  105354. pLoop = pLevel->pWLoop;
  105355. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  105356. /* Do nothing */
  105357. }else
  105358. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105359. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  105360. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  105361. int iCur = pTabItem->iCursor;
  105362. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  105363. }else if( IsVirtual(pTab) ){
  105364. /* noop */
  105365. }else
  105366. #endif
  105367. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  105368. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  105369. int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
  105370. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  105371. testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
  105372. testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
  105373. if( !pWInfo->okOnePass && pTab->nCol<BMS ){
  105374. Bitmask b = pTabItem->colUsed;
  105375. int n = 0;
  105376. for(; b; b=b>>1, n++){}
  105377. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  105378. SQLITE_INT_TO_PTR(n), P4_INT32);
  105379. assert( n<=pTab->nCol );
  105380. }
  105381. }else{
  105382. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  105383. }
  105384. if( pLoop->wsFlags & WHERE_INDEXED ){
  105385. Index *pIx = pLoop->u.btree.pIndex;
  105386. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  105387. /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
  105388. int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
  105389. assert( pIx->pSchema==pTab->pSchema );
  105390. assert( iIndexCur>=0 );
  105391. sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
  105392. (char*)pKey, P4_KEYINFO_HANDOFF);
  105393. VdbeComment((v, "%s", pIx->zName));
  105394. }
  105395. sqlite3CodeVerifySchema(pParse, iDb);
  105396. notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
  105397. }
  105398. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  105399. if( db->mallocFailed ) goto whereBeginError;
  105400. /* Generate the code to do the search. Each iteration of the for
  105401. ** loop below generates code for a single nested loop of the VM
  105402. ** program.
  105403. */
  105404. notReady = ~(Bitmask)0;
  105405. for(ii=0; ii<nTabList; ii++){
  105406. pLevel = &pWInfo->a[ii];
  105407. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  105408. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  105409. constructAutomaticIndex(pParse, &pWInfo->sWC,
  105410. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  105411. if( db->mallocFailed ) goto whereBeginError;
  105412. }
  105413. #endif
  105414. explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
  105415. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  105416. notReady = codeOneLoopStart(pWInfo, ii, notReady);
  105417. pWInfo->iContinue = pLevel->addrCont;
  105418. }
  105419. /* Done. */
  105420. return pWInfo;
  105421. /* Jump here if malloc fails */
  105422. whereBeginError:
  105423. if( pWInfo ){
  105424. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  105425. whereInfoFree(db, pWInfo);
  105426. }
  105427. return 0;
  105428. }
  105429. /*
  105430. ** Generate the end of the WHERE loop. See comments on
  105431. ** sqlite3WhereBegin() for additional information.
  105432. */
  105433. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  105434. Parse *pParse = pWInfo->pParse;
  105435. Vdbe *v = pParse->pVdbe;
  105436. int i;
  105437. WhereLevel *pLevel;
  105438. WhereLoop *pLoop;
  105439. SrcList *pTabList = pWInfo->pTabList;
  105440. sqlite3 *db = pParse->db;
  105441. /* Generate loop termination code.
  105442. */
  105443. sqlite3ExprCacheClear(pParse);
  105444. for(i=pWInfo->nLevel-1; i>=0; i--){
  105445. pLevel = &pWInfo->a[i];
  105446. pLoop = pLevel->pWLoop;
  105447. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  105448. if( pLevel->op!=OP_Noop ){
  105449. sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
  105450. sqlite3VdbeChangeP5(v, pLevel->p5);
  105451. }
  105452. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  105453. struct InLoop *pIn;
  105454. int j;
  105455. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  105456. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  105457. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  105458. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  105459. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  105460. }
  105461. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  105462. }
  105463. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  105464. if( pLevel->iLeftJoin ){
  105465. int addr;
  105466. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
  105467. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  105468. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  105469. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  105470. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  105471. }
  105472. if( pLoop->wsFlags & WHERE_INDEXED ){
  105473. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  105474. }
  105475. if( pLevel->op==OP_Return ){
  105476. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  105477. }else{
  105478. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  105479. }
  105480. sqlite3VdbeJumpHere(v, addr);
  105481. }
  105482. }
  105483. /* The "break" point is here, just past the end of the outer loop.
  105484. ** Set it.
  105485. */
  105486. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  105487. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  105488. */
  105489. assert( pWInfo->nLevel<=pTabList->nSrc );
  105490. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  105491. Index *pIdx = 0;
  105492. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  105493. Table *pTab = pTabItem->pTab;
  105494. assert( pTab!=0 );
  105495. pLoop = pLevel->pWLoop;
  105496. if( (pTab->tabFlags & TF_Ephemeral)==0
  105497. && pTab->pSelect==0
  105498. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  105499. ){
  105500. int ws = pLoop->wsFlags;
  105501. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  105502. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  105503. }
  105504. if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){
  105505. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  105506. }
  105507. }
  105508. /* If this scan uses an index, make VDBE code substitutions to read data
  105509. ** from the index instead of from the table where possible. In some cases
  105510. ** this optimization prevents the table from ever being read, which can
  105511. ** yield a significant performance boost.
  105512. **
  105513. ** Calls to the code generator in between sqlite3WhereBegin and
  105514. ** sqlite3WhereEnd will have created code that references the table
  105515. ** directly. This loop scans all that code looking for opcodes
  105516. ** that reference the table and converts them into opcodes that
  105517. ** reference the index.
  105518. */
  105519. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  105520. pIdx = pLoop->u.btree.pIndex;
  105521. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  105522. pIdx = pLevel->u.pCovidx;
  105523. }
  105524. if( pIdx && !db->mallocFailed ){
  105525. int k, j, last;
  105526. VdbeOp *pOp;
  105527. last = sqlite3VdbeCurrentAddr(v);
  105528. k = pLevel->addrBody;
  105529. pOp = sqlite3VdbeGetOp(v, k);
  105530. for(; k<last; k++, pOp++){
  105531. if( pOp->p1!=pLevel->iTabCur ) continue;
  105532. if( pOp->opcode==OP_Column ){
  105533. for(j=0; j<pIdx->nColumn; j++){
  105534. if( pOp->p2==pIdx->aiColumn[j] ){
  105535. pOp->p2 = j;
  105536. pOp->p1 = pLevel->iIdxCur;
  105537. break;
  105538. }
  105539. }
  105540. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
  105541. }else if( pOp->opcode==OP_Rowid ){
  105542. pOp->p1 = pLevel->iIdxCur;
  105543. pOp->opcode = OP_IdxRowid;
  105544. }
  105545. }
  105546. }
  105547. }
  105548. /* Final cleanup
  105549. */
  105550. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  105551. whereInfoFree(db, pWInfo);
  105552. return;
  105553. }
  105554. /************** End of where.c ***********************************************/
  105555. /************** Begin file parse.c *******************************************/
  105556. /* Driver template for the LEMON parser generator.
  105557. ** The author disclaims copyright to this source code.
  105558. **
  105559. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  105560. ** The only modifications are the addition of a couple of NEVER()
  105561. ** macros to disable tests that are needed in the case of a general
  105562. ** LALR(1) grammar but which are always false in the
  105563. ** specific grammar used by SQLite.
  105564. */
  105565. /* First off, code is included that follows the "include" declaration
  105566. ** in the input grammar file. */
  105567. /* #include <stdio.h> */
  105568. /*
  105569. ** Disable all error recovery processing in the parser push-down
  105570. ** automaton.
  105571. */
  105572. #define YYNOERRORRECOVERY 1
  105573. /*
  105574. ** Make yytestcase() the same as testcase()
  105575. */
  105576. #define yytestcase(X) testcase(X)
  105577. /*
  105578. ** An instance of this structure holds information about the
  105579. ** LIMIT clause of a SELECT statement.
  105580. */
  105581. struct LimitVal {
  105582. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  105583. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  105584. };
  105585. /*
  105586. ** An instance of this structure is used to store the LIKE,
  105587. ** GLOB, NOT LIKE, and NOT GLOB operators.
  105588. */
  105589. struct LikeOp {
  105590. Token eOperator; /* "like" or "glob" or "regexp" */
  105591. int bNot; /* True if the NOT keyword is present */
  105592. };
  105593. /*
  105594. ** An instance of the following structure describes the event of a
  105595. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  105596. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  105597. **
  105598. ** UPDATE ON (a,b,c)
  105599. **
  105600. ** Then the "b" IdList records the list "a,b,c".
  105601. */
  105602. struct TrigEvent { int a; IdList * b; };
  105603. /*
  105604. ** An instance of this structure holds the ATTACH key and the key type.
  105605. */
  105606. struct AttachKey { int type; Token key; };
  105607. /*
  105608. ** One or more VALUES claues
  105609. */
  105610. struct ValueList {
  105611. ExprList *pList;
  105612. Select *pSelect;
  105613. };
  105614. /* This is a utility routine used to set the ExprSpan.zStart and
  105615. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  105616. ** range of text beginning with pStart and going to the end of pEnd.
  105617. */
  105618. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  105619. pOut->zStart = pStart->z;
  105620. pOut->zEnd = &pEnd->z[pEnd->n];
  105621. }
  105622. /* Construct a new Expr object from a single identifier. Use the
  105623. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  105624. ** that created the expression.
  105625. */
  105626. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  105627. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  105628. pOut->zStart = pValue->z;
  105629. pOut->zEnd = &pValue->z[pValue->n];
  105630. }
  105631. /* This routine constructs a binary expression node out of two ExprSpan
  105632. ** objects and uses the result to populate a new ExprSpan object.
  105633. */
  105634. static void spanBinaryExpr(
  105635. ExprSpan *pOut, /* Write the result here */
  105636. Parse *pParse, /* The parsing context. Errors accumulate here */
  105637. int op, /* The binary operation */
  105638. ExprSpan *pLeft, /* The left operand */
  105639. ExprSpan *pRight /* The right operand */
  105640. ){
  105641. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  105642. pOut->zStart = pLeft->zStart;
  105643. pOut->zEnd = pRight->zEnd;
  105644. }
  105645. /* Construct an expression node for a unary postfix operator
  105646. */
  105647. static void spanUnaryPostfix(
  105648. ExprSpan *pOut, /* Write the new expression node here */
  105649. Parse *pParse, /* Parsing context to record errors */
  105650. int op, /* The operator */
  105651. ExprSpan *pOperand, /* The operand */
  105652. Token *pPostOp /* The operand token for setting the span */
  105653. ){
  105654. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  105655. pOut->zStart = pOperand->zStart;
  105656. pOut->zEnd = &pPostOp->z[pPostOp->n];
  105657. }
  105658. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  105659. ** unary TK_ISNULL or TK_NOTNULL expression. */
  105660. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  105661. sqlite3 *db = pParse->db;
  105662. if( db->mallocFailed==0 && pY->op==TK_NULL ){
  105663. pA->op = (u8)op;
  105664. sqlite3ExprDelete(db, pA->pRight);
  105665. pA->pRight = 0;
  105666. }
  105667. }
  105668. /* Construct an expression node for a unary prefix operator
  105669. */
  105670. static void spanUnaryPrefix(
  105671. ExprSpan *pOut, /* Write the new expression node here */
  105672. Parse *pParse, /* Parsing context to record errors */
  105673. int op, /* The operator */
  105674. ExprSpan *pOperand, /* The operand */
  105675. Token *pPreOp /* The operand token for setting the span */
  105676. ){
  105677. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  105678. pOut->zStart = pPreOp->z;
  105679. pOut->zEnd = pOperand->zEnd;
  105680. }
  105681. /* Next is all token values, in a form suitable for use by makeheaders.
  105682. ** This section will be null unless lemon is run with the -m switch.
  105683. */
  105684. /*
  105685. ** These constants (all generated automatically by the parser generator)
  105686. ** specify the various kinds of tokens (terminals) that the parser
  105687. ** understands.
  105688. **
  105689. ** Each symbol here is a terminal symbol in the grammar.
  105690. */
  105691. /* Make sure the INTERFACE macro is defined.
  105692. */
  105693. #ifndef INTERFACE
  105694. # define INTERFACE 1
  105695. #endif
  105696. /* The next thing included is series of defines which control
  105697. ** various aspects of the generated parser.
  105698. ** YYCODETYPE is the data type used for storing terminal
  105699. ** and nonterminal numbers. "unsigned char" is
  105700. ** used if there are fewer than 250 terminals
  105701. ** and nonterminals. "int" is used otherwise.
  105702. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  105703. ** to no legal terminal or nonterminal number. This
  105704. ** number is used to fill in empty slots of the hash
  105705. ** table.
  105706. ** YYFALLBACK If defined, this indicates that one or more tokens
  105707. ** have fall-back values which should be used if the
  105708. ** original value of the token will not parse.
  105709. ** YYACTIONTYPE is the data type used for storing terminal
  105710. ** and nonterminal numbers. "unsigned char" is
  105711. ** used if there are fewer than 250 rules and
  105712. ** states combined. "int" is used otherwise.
  105713. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  105714. ** directly to the parser from the tokenizer.
  105715. ** YYMINORTYPE is the data type used for all minor tokens.
  105716. ** This is typically a union of many types, one of
  105717. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  105718. ** for base tokens is called "yy0".
  105719. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  105720. ** zero the stack is dynamically sized using realloc()
  105721. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  105722. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  105723. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  105724. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  105725. ** YYNSTATE the combined number of states.
  105726. ** YYNRULE the number of rules in the grammar
  105727. ** YYERRORSYMBOL is the code number of the error symbol. If not
  105728. ** defined, then do no error processing.
  105729. */
  105730. #define YYCODETYPE unsigned char
  105731. #define YYNOCODE 251
  105732. #define YYACTIONTYPE unsigned short int
  105733. #define YYWILDCARD 67
  105734. #define sqlite3ParserTOKENTYPE Token
  105735. typedef union {
  105736. int yyinit;
  105737. sqlite3ParserTOKENTYPE yy0;
  105738. struct LimitVal yy64;
  105739. Expr* yy122;
  105740. Select* yy159;
  105741. IdList* yy180;
  105742. struct {int value; int mask;} yy207;
  105743. u8 yy258;
  105744. u16 yy305;
  105745. struct LikeOp yy318;
  105746. TriggerStep* yy327;
  105747. ExprSpan yy342;
  105748. SrcList* yy347;
  105749. int yy392;
  105750. struct TrigEvent yy410;
  105751. ExprList* yy442;
  105752. struct ValueList yy487;
  105753. } YYMINORTYPE;
  105754. #ifndef YYSTACKDEPTH
  105755. #define YYSTACKDEPTH 100
  105756. #endif
  105757. #define sqlite3ParserARG_SDECL Parse *pParse;
  105758. #define sqlite3ParserARG_PDECL ,Parse *pParse
  105759. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  105760. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  105761. #define YYNSTATE 628
  105762. #define YYNRULE 327
  105763. #define YYFALLBACK 1
  105764. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  105765. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  105766. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  105767. /* The yyzerominor constant is used to initialize instances of
  105768. ** YYMINORTYPE objects to zero. */
  105769. static const YYMINORTYPE yyzerominor = { 0 };
  105770. /* Define the yytestcase() macro to be a no-op if is not already defined
  105771. ** otherwise.
  105772. **
  105773. ** Applications can choose to define yytestcase() in the %include section
  105774. ** to a macro that can assist in verifying code coverage. For production
  105775. ** code the yytestcase() macro should be turned off. But it is useful
  105776. ** for testing.
  105777. */
  105778. #ifndef yytestcase
  105779. # define yytestcase(X)
  105780. #endif
  105781. /* Next are the tables used to determine what action to take based on the
  105782. ** current state and lookahead token. These tables are used to implement
  105783. ** functions that take a state number and lookahead value and return an
  105784. ** action integer.
  105785. **
  105786. ** Suppose the action integer is N. Then the action is determined as
  105787. ** follows
  105788. **
  105789. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  105790. ** token onto the stack and goto state N.
  105791. **
  105792. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  105793. **
  105794. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  105795. **
  105796. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  105797. **
  105798. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  105799. ** slots in the yy_action[] table.
  105800. **
  105801. ** The action table is constructed as a single large table named yy_action[].
  105802. ** Given state S and lookahead X, the action is computed as
  105803. **
  105804. ** yy_action[ yy_shift_ofst[S] + X ]
  105805. **
  105806. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  105807. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  105808. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  105809. ** and that yy_default[S] should be used instead.
  105810. **
  105811. ** The formula above is for computing the action when the lookahead is
  105812. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  105813. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  105814. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  105815. ** YY_SHIFT_USE_DFLT.
  105816. **
  105817. ** The following are the tables generated in this section:
  105818. **
  105819. ** yy_action[] A single table containing all actions.
  105820. ** yy_lookahead[] A table containing the lookahead for each entry in
  105821. ** yy_action. Used to detect hash collisions.
  105822. ** yy_shift_ofst[] For each state, the offset into yy_action for
  105823. ** shifting terminals.
  105824. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  105825. ** shifting non-terminals after a reduce.
  105826. ** yy_default[] Default action for each state.
  105827. */
  105828. #define YY_ACTTAB_COUNT (1564)
  105829. static const YYACTIONTYPE yy_action[] = {
  105830. /* 0 */ 310, 956, 184, 418, 2, 171, 625, 595, 56, 56,
  105831. /* 10 */ 56, 56, 49, 54, 54, 54, 54, 53, 53, 52,
  105832. /* 20 */ 52, 52, 51, 233, 621, 620, 299, 621, 620, 234,
  105833. /* 30 */ 588, 582, 56, 56, 56, 56, 19, 54, 54, 54,
  105834. /* 40 */ 54, 53, 53, 52, 52, 52, 51, 233, 606, 57,
  105835. /* 50 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  105836. /* 60 */ 56, 56, 542, 54, 54, 54, 54, 53, 53, 52,
  105837. /* 70 */ 52, 52, 51, 233, 310, 595, 326, 196, 195, 194,
  105838. /* 80 */ 33, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  105839. /* 90 */ 51, 233, 618, 617, 165, 618, 617, 381, 378, 377,
  105840. /* 100 */ 408, 533, 577, 577, 588, 582, 304, 423, 376, 59,
  105841. /* 110 */ 53, 53, 52, 52, 52, 51, 233, 50, 47, 146,
  105842. /* 120 */ 575, 546, 65, 57, 58, 48, 580, 579, 581, 581,
  105843. /* 130 */ 55, 55, 56, 56, 56, 56, 213, 54, 54, 54,
  105844. /* 140 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 223,
  105845. /* 150 */ 540, 421, 170, 176, 138, 281, 384, 276, 383, 168,
  105846. /* 160 */ 490, 552, 410, 669, 621, 620, 272, 439, 410, 439,
  105847. /* 170 */ 551, 605, 67, 483, 508, 619, 600, 413, 588, 582,
  105848. /* 180 */ 601, 484, 619, 413, 619, 599, 91, 440, 441, 440,
  105849. /* 190 */ 336, 599, 73, 670, 222, 267, 481, 57, 58, 48,
  105850. /* 200 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  105851. /* 210 */ 671, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  105852. /* 220 */ 51, 233, 310, 280, 232, 231, 1, 132, 200, 386,
  105853. /* 230 */ 621, 620, 618, 617, 279, 436, 290, 564, 175, 263,
  105854. /* 240 */ 410, 265, 438, 498, 437, 166, 442, 569, 337, 569,
  105855. /* 250 */ 201, 538, 588, 582, 600, 413, 165, 595, 601, 381,
  105856. /* 260 */ 378, 377, 598, 599, 92, 524, 619, 570, 570, 593,
  105857. /* 270 */ 376, 57, 58, 48, 580, 579, 581, 581, 55, 55,
  105858. /* 280 */ 56, 56, 56, 56, 598, 54, 54, 54, 54, 53,
  105859. /* 290 */ 53, 52, 52, 52, 51, 233, 310, 464, 618, 617,
  105860. /* 300 */ 591, 591, 591, 174, 273, 397, 410, 273, 410, 549,
  105861. /* 310 */ 398, 621, 620, 68, 327, 621, 620, 621, 620, 619,
  105862. /* 320 */ 547, 413, 619, 413, 472, 595, 588, 582, 473, 599,
  105863. /* 330 */ 92, 599, 92, 52, 52, 52, 51, 233, 514, 513,
  105864. /* 340 */ 206, 323, 364, 465, 221, 57, 58, 48, 580, 579,
  105865. /* 350 */ 581, 581, 55, 55, 56, 56, 56, 56, 530, 54,
  105866. /* 360 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  105867. /* 370 */ 310, 397, 410, 397, 598, 373, 387, 531, 348, 618,
  105868. /* 380 */ 617, 576, 202, 618, 617, 618, 617, 413, 621, 620,
  105869. /* 390 */ 145, 255, 347, 254, 578, 599, 74, 352, 45, 490,
  105870. /* 400 */ 588, 582, 235, 189, 465, 545, 167, 297, 187, 470,
  105871. /* 410 */ 480, 67, 62, 39, 619, 547, 598, 346, 574, 57,
  105872. /* 420 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  105873. /* 430 */ 56, 56, 6, 54, 54, 54, 54, 53, 53, 52,
  105874. /* 440 */ 52, 52, 51, 233, 310, 563, 559, 408, 529, 577,
  105875. /* 450 */ 577, 345, 255, 347, 254, 182, 618, 617, 504, 505,
  105876. /* 460 */ 315, 410, 558, 235, 166, 272, 410, 353, 565, 181,
  105877. /* 470 */ 408, 547, 577, 577, 588, 582, 413, 538, 557, 562,
  105878. /* 480 */ 518, 413, 619, 249, 599, 16, 7, 36, 468, 599,
  105879. /* 490 */ 92, 517, 619, 57, 58, 48, 580, 579, 581, 581,
  105880. /* 500 */ 55, 55, 56, 56, 56, 56, 542, 54, 54, 54,
  105881. /* 510 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 328,
  105882. /* 520 */ 573, 572, 526, 559, 561, 395, 872, 246, 410, 248,
  105883. /* 530 */ 171, 393, 595, 219, 408, 410, 577, 577, 503, 558,
  105884. /* 540 */ 365, 145, 511, 413, 408, 229, 577, 577, 588, 582,
  105885. /* 550 */ 413, 599, 92, 382, 270, 557, 166, 401, 599, 69,
  105886. /* 560 */ 502, 420, 946, 199, 946, 198, 547, 57, 58, 48,
  105887. /* 570 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  105888. /* 580 */ 569, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  105889. /* 590 */ 51, 233, 310, 318, 420, 945, 509, 945, 309, 598,
  105890. /* 600 */ 595, 566, 491, 212, 173, 247, 424, 616, 615, 614,
  105891. /* 610 */ 324, 197, 143, 406, 573, 572, 490, 66, 50, 47,
  105892. /* 620 */ 146, 595, 588, 582, 232, 231, 560, 428, 67, 556,
  105893. /* 630 */ 15, 619, 186, 544, 304, 422, 35, 206, 433, 424,
  105894. /* 640 */ 553, 57, 58, 48, 580, 579, 581, 581, 55, 55,
  105895. /* 650 */ 56, 56, 56, 56, 205, 54, 54, 54, 54, 53,
  105896. /* 660 */ 53, 52, 52, 52, 51, 233, 310, 570, 570, 261,
  105897. /* 670 */ 269, 598, 12, 374, 569, 166, 410, 314, 410, 421,
  105898. /* 680 */ 410, 474, 474, 366, 619, 50, 47, 146, 598, 595,
  105899. /* 690 */ 256, 413, 166, 413, 352, 413, 588, 582, 32, 599,
  105900. /* 700 */ 94, 599, 97, 599, 95, 628, 626, 330, 142, 50,
  105901. /* 710 */ 47, 146, 334, 350, 359, 57, 58, 48, 580, 579,
  105902. /* 720 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
  105903. /* 730 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  105904. /* 740 */ 310, 410, 389, 413, 410, 22, 566, 405, 212, 363,
  105905. /* 750 */ 390, 599, 104, 360, 410, 156, 413, 410, 604, 413,
  105906. /* 760 */ 538, 332, 570, 570, 599, 103, 494, 599, 105, 413,
  105907. /* 770 */ 588, 582, 413, 261, 550, 619, 11, 599, 106, 522,
  105908. /* 780 */ 599, 133, 169, 458, 457, 170, 35, 602, 619, 57,
  105909. /* 790 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  105910. /* 800 */ 56, 56, 410, 54, 54, 54, 54, 53, 53, 52,
  105911. /* 810 */ 52, 52, 51, 233, 310, 410, 260, 413, 410, 50,
  105912. /* 820 */ 47, 146, 358, 319, 356, 599, 134, 528, 353, 338,
  105913. /* 830 */ 413, 410, 357, 413, 358, 410, 358, 619, 599, 98,
  105914. /* 840 */ 129, 599, 102, 619, 588, 582, 413, 21, 235, 619,
  105915. /* 850 */ 413, 619, 211, 143, 599, 101, 30, 167, 599, 93,
  105916. /* 860 */ 351, 536, 203, 57, 58, 48, 580, 579, 581, 581,
  105917. /* 870 */ 55, 55, 56, 56, 56, 56, 410, 54, 54, 54,
  105918. /* 880 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 410,
  105919. /* 890 */ 527, 413, 410, 426, 215, 306, 598, 552, 141, 599,
  105920. /* 900 */ 100, 40, 410, 38, 413, 410, 551, 413, 410, 228,
  105921. /* 910 */ 220, 315, 599, 77, 501, 599, 96, 413, 588, 582,
  105922. /* 920 */ 413, 339, 253, 413, 218, 599, 137, 380, 599, 136,
  105923. /* 930 */ 28, 599, 135, 271, 716, 210, 482, 57, 58, 48,
  105924. /* 940 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  105925. /* 950 */ 410, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  105926. /* 960 */ 51, 233, 310, 410, 273, 413, 410, 316, 147, 598,
  105927. /* 970 */ 273, 627, 2, 599, 76, 209, 410, 127, 413, 619,
  105928. /* 980 */ 126, 413, 410, 622, 235, 619, 599, 90, 375, 599,
  105929. /* 990 */ 89, 413, 588, 582, 27, 261, 351, 413, 619, 599,
  105930. /* 1000 */ 75, 322, 542, 542, 125, 599, 88, 321, 279, 598,
  105931. /* 1010 */ 619, 57, 46, 48, 580, 579, 581, 581, 55, 55,
  105932. /* 1020 */ 56, 56, 56, 56, 410, 54, 54, 54, 54, 53,
  105933. /* 1030 */ 53, 52, 52, 52, 51, 233, 310, 410, 451, 413,
  105934. /* 1040 */ 164, 285, 283, 273, 610, 425, 305, 599, 87, 371,
  105935. /* 1050 */ 410, 478, 413, 410, 609, 410, 608, 603, 619, 619,
  105936. /* 1060 */ 599, 99, 587, 586, 122, 413, 588, 582, 413, 619,
  105937. /* 1070 */ 413, 619, 619, 599, 86, 367, 599, 17, 599, 85,
  105938. /* 1080 */ 320, 185, 520, 519, 584, 583, 58, 48, 580, 579,
  105939. /* 1090 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
  105940. /* 1100 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  105941. /* 1110 */ 310, 585, 410, 413, 410, 261, 261, 261, 409, 592,
  105942. /* 1120 */ 475, 599, 84, 170, 410, 467, 519, 413, 121, 413,
  105943. /* 1130 */ 619, 619, 619, 619, 619, 599, 83, 599, 72, 413,
  105944. /* 1140 */ 588, 582, 51, 233, 626, 330, 471, 599, 71, 258,
  105945. /* 1150 */ 159, 120, 14, 463, 157, 158, 117, 261, 449, 448,
  105946. /* 1160 */ 447, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  105947. /* 1170 */ 56, 56, 619, 54, 54, 54, 54, 53, 53, 52,
  105948. /* 1180 */ 52, 52, 51, 233, 44, 404, 261, 3, 410, 460,
  105949. /* 1190 */ 261, 414, 620, 118, 399, 10, 25, 24, 555, 349,
  105950. /* 1200 */ 217, 619, 407, 413, 410, 619, 4, 44, 404, 619,
  105951. /* 1210 */ 3, 599, 82, 619, 414, 620, 456, 543, 115, 413,
  105952. /* 1220 */ 539, 402, 537, 275, 507, 407, 251, 599, 81, 216,
  105953. /* 1230 */ 274, 564, 619, 243, 454, 619, 154, 619, 619, 619,
  105954. /* 1240 */ 450, 417, 624, 110, 402, 619, 410, 236, 64, 123,
  105955. /* 1250 */ 488, 41, 42, 532, 564, 204, 410, 268, 43, 412,
  105956. /* 1260 */ 411, 413, 266, 593, 108, 619, 107, 435, 333, 599,
  105957. /* 1270 */ 80, 413, 619, 264, 41, 42, 444, 619, 410, 599,
  105958. /* 1280 */ 70, 43, 412, 411, 434, 262, 593, 149, 619, 598,
  105959. /* 1290 */ 257, 237, 188, 413, 591, 591, 591, 590, 589, 13,
  105960. /* 1300 */ 619, 599, 18, 329, 235, 619, 44, 404, 361, 3,
  105961. /* 1310 */ 419, 462, 340, 414, 620, 227, 124, 591, 591, 591,
  105962. /* 1320 */ 590, 589, 13, 619, 407, 410, 619, 410, 139, 34,
  105963. /* 1330 */ 404, 388, 3, 148, 623, 313, 414, 620, 312, 331,
  105964. /* 1340 */ 413, 461, 413, 402, 180, 354, 413, 407, 599, 79,
  105965. /* 1350 */ 599, 78, 250, 564, 599, 9, 619, 613, 612, 611,
  105966. /* 1360 */ 619, 8, 453, 443, 242, 416, 402, 619, 239, 235,
  105967. /* 1370 */ 179, 238, 429, 41, 42, 289, 564, 619, 619, 619,
  105968. /* 1380 */ 43, 412, 411, 619, 144, 593, 619, 619, 177, 61,
  105969. /* 1390 */ 619, 597, 392, 621, 620, 288, 41, 42, 415, 619,
  105970. /* 1400 */ 294, 30, 394, 43, 412, 411, 293, 619, 593, 31,
  105971. /* 1410 */ 619, 396, 292, 60, 230, 37, 591, 591, 591, 590,
  105972. /* 1420 */ 589, 13, 214, 554, 183, 291, 172, 302, 301, 300,
  105973. /* 1430 */ 178, 298, 596, 564, 452, 29, 286, 391, 541, 591,
  105974. /* 1440 */ 591, 591, 590, 589, 13, 284, 521, 535, 150, 534,
  105975. /* 1450 */ 241, 282, 385, 192, 191, 325, 516, 515, 277, 240,
  105976. /* 1460 */ 511, 524, 308, 512, 128, 593, 510, 225, 226, 487,
  105977. /* 1470 */ 486, 224, 152, 492, 465, 307, 485, 163, 153, 372,
  105978. /* 1480 */ 479, 151, 162, 259, 370, 161, 368, 208, 476, 477,
  105979. /* 1490 */ 26, 160, 469, 466, 362, 140, 591, 591, 591, 116,
  105980. /* 1500 */ 119, 455, 344, 155, 114, 343, 113, 112, 446, 111,
  105981. /* 1510 */ 131, 109, 432, 317, 130, 431, 23, 20, 430, 427,
  105982. /* 1520 */ 190, 63, 255, 342, 244, 607, 295, 287, 311, 594,
  105983. /* 1530 */ 278, 508, 496, 235, 493, 571, 497, 568, 495, 403,
  105984. /* 1540 */ 459, 379, 355, 245, 193, 303, 567, 296, 341, 5,
  105985. /* 1550 */ 445, 548, 506, 207, 525, 500, 335, 489, 252, 369,
  105986. /* 1560 */ 400, 499, 523, 233,
  105987. };
  105988. static const YYCODETYPE yy_lookahead[] = {
  105989. /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
  105990. /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
  105991. /* 20 */ 89, 90, 91, 92, 26, 27, 15, 26, 27, 197,
  105992. /* 30 */ 49, 50, 77, 78, 79, 80, 204, 82, 83, 84,
  105993. /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 23, 68,
  105994. /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  105995. /* 60 */ 79, 80, 166, 82, 83, 84, 85, 86, 87, 88,
  105996. /* 70 */ 89, 90, 91, 92, 19, 94, 19, 105, 106, 107,
  105997. /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  105998. /* 90 */ 91, 92, 94, 95, 96, 94, 95, 99, 100, 101,
  105999. /* 100 */ 112, 205, 114, 115, 49, 50, 22, 23, 110, 54,
  106000. /* 110 */ 86, 87, 88, 89, 90, 91, 92, 221, 222, 223,
  106001. /* 120 */ 23, 120, 25, 68, 69, 70, 71, 72, 73, 74,
  106002. /* 130 */ 75, 76, 77, 78, 79, 80, 22, 82, 83, 84,
  106003. /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 92,
  106004. /* 150 */ 23, 67, 25, 96, 97, 98, 99, 100, 101, 102,
  106005. /* 160 */ 150, 32, 150, 118, 26, 27, 109, 150, 150, 150,
  106006. /* 170 */ 41, 161, 162, 180, 181, 165, 113, 165, 49, 50,
  106007. /* 180 */ 117, 188, 165, 165, 165, 173, 174, 170, 171, 170,
  106008. /* 190 */ 171, 173, 174, 118, 184, 16, 186, 68, 69, 70,
  106009. /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  106010. /* 210 */ 118, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  106011. /* 220 */ 91, 92, 19, 98, 86, 87, 22, 24, 160, 88,
  106012. /* 230 */ 26, 27, 94, 95, 109, 97, 224, 66, 118, 60,
  106013. /* 240 */ 150, 62, 104, 23, 106, 25, 229, 230, 229, 230,
  106014. /* 250 */ 160, 150, 49, 50, 113, 165, 96, 26, 117, 99,
  106015. /* 260 */ 100, 101, 194, 173, 174, 94, 165, 129, 130, 98,
  106016. /* 270 */ 110, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  106017. /* 280 */ 77, 78, 79, 80, 194, 82, 83, 84, 85, 86,
  106018. /* 290 */ 87, 88, 89, 90, 91, 92, 19, 11, 94, 95,
  106019. /* 300 */ 129, 130, 131, 118, 150, 215, 150, 150, 150, 25,
  106020. /* 310 */ 220, 26, 27, 22, 213, 26, 27, 26, 27, 165,
  106021. /* 320 */ 25, 165, 165, 165, 30, 94, 49, 50, 34, 173,
  106022. /* 330 */ 174, 173, 174, 88, 89, 90, 91, 92, 7, 8,
  106023. /* 340 */ 160, 187, 48, 57, 187, 68, 69, 70, 71, 72,
  106024. /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 23, 82,
  106025. /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  106026. /* 370 */ 19, 215, 150, 215, 194, 19, 220, 88, 220, 94,
  106027. /* 380 */ 95, 23, 160, 94, 95, 94, 95, 165, 26, 27,
  106028. /* 390 */ 95, 105, 106, 107, 113, 173, 174, 217, 22, 150,
  106029. /* 400 */ 49, 50, 116, 119, 57, 120, 50, 158, 22, 21,
  106030. /* 410 */ 161, 162, 232, 136, 165, 120, 194, 237, 23, 68,
  106031. /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  106032. /* 430 */ 79, 80, 22, 82, 83, 84, 85, 86, 87, 88,
  106033. /* 440 */ 89, 90, 91, 92, 19, 23, 12, 112, 23, 114,
  106034. /* 450 */ 115, 63, 105, 106, 107, 23, 94, 95, 97, 98,
  106035. /* 460 */ 104, 150, 28, 116, 25, 109, 150, 150, 23, 23,
  106036. /* 470 */ 112, 25, 114, 115, 49, 50, 165, 150, 44, 11,
  106037. /* 480 */ 46, 165, 165, 16, 173, 174, 76, 136, 100, 173,
  106038. /* 490 */ 174, 57, 165, 68, 69, 70, 71, 72, 73, 74,
  106039. /* 500 */ 75, 76, 77, 78, 79, 80, 166, 82, 83, 84,
  106040. /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 169,
  106041. /* 520 */ 170, 171, 23, 12, 23, 214, 138, 60, 150, 62,
  106042. /* 530 */ 24, 215, 26, 216, 112, 150, 114, 115, 36, 28,
  106043. /* 540 */ 213, 95, 103, 165, 112, 205, 114, 115, 49, 50,
  106044. /* 550 */ 165, 173, 174, 51, 23, 44, 25, 46, 173, 174,
  106045. /* 560 */ 58, 22, 23, 22, 25, 160, 120, 68, 69, 70,
  106046. /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  106047. /* 580 */ 230, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  106048. /* 590 */ 91, 92, 19, 215, 22, 23, 23, 25, 163, 194,
  106049. /* 600 */ 94, 166, 167, 168, 25, 138, 67, 7, 8, 9,
  106050. /* 610 */ 108, 206, 207, 169, 170, 171, 150, 22, 221, 222,
  106051. /* 620 */ 223, 26, 49, 50, 86, 87, 23, 161, 162, 23,
  106052. /* 630 */ 22, 165, 24, 120, 22, 23, 25, 160, 241, 67,
  106053. /* 640 */ 176, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  106054. /* 650 */ 77, 78, 79, 80, 160, 82, 83, 84, 85, 86,
  106055. /* 660 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 150,
  106056. /* 670 */ 23, 194, 35, 23, 230, 25, 150, 155, 150, 67,
  106057. /* 680 */ 150, 105, 106, 107, 165, 221, 222, 223, 194, 94,
  106058. /* 690 */ 23, 165, 25, 165, 217, 165, 49, 50, 25, 173,
  106059. /* 700 */ 174, 173, 174, 173, 174, 0, 1, 2, 118, 221,
  106060. /* 710 */ 222, 223, 193, 219, 237, 68, 69, 70, 71, 72,
  106061. /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  106062. /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  106063. /* 740 */ 19, 150, 19, 165, 150, 24, 166, 167, 168, 227,
  106064. /* 750 */ 27, 173, 174, 231, 150, 25, 165, 150, 172, 165,
  106065. /* 760 */ 150, 242, 129, 130, 173, 174, 180, 173, 174, 165,
  106066. /* 770 */ 49, 50, 165, 150, 176, 165, 35, 173, 174, 165,
  106067. /* 780 */ 173, 174, 35, 23, 23, 25, 25, 173, 165, 68,
  106068. /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  106069. /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
  106070. /* 810 */ 89, 90, 91, 92, 19, 150, 193, 165, 150, 221,
  106071. /* 820 */ 222, 223, 150, 213, 19, 173, 174, 23, 150, 97,
  106072. /* 830 */ 165, 150, 27, 165, 150, 150, 150, 165, 173, 174,
  106073. /* 840 */ 22, 173, 174, 165, 49, 50, 165, 52, 116, 165,
  106074. /* 850 */ 165, 165, 206, 207, 173, 174, 126, 50, 173, 174,
  106075. /* 860 */ 128, 27, 160, 68, 69, 70, 71, 72, 73, 74,
  106076. /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
  106077. /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
  106078. /* 890 */ 23, 165, 150, 23, 216, 25, 194, 32, 39, 173,
  106079. /* 900 */ 174, 135, 150, 137, 165, 150, 41, 165, 150, 52,
  106080. /* 910 */ 238, 104, 173, 174, 29, 173, 174, 165, 49, 50,
  106081. /* 920 */ 165, 219, 238, 165, 238, 173, 174, 52, 173, 174,
  106082. /* 930 */ 22, 173, 174, 23, 23, 160, 25, 68, 69, 70,
  106083. /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  106084. /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  106085. /* 960 */ 91, 92, 19, 150, 150, 165, 150, 245, 246, 194,
  106086. /* 970 */ 150, 144, 145, 173, 174, 160, 150, 22, 165, 165,
  106087. /* 980 */ 22, 165, 150, 150, 116, 165, 173, 174, 52, 173,
  106088. /* 990 */ 174, 165, 49, 50, 22, 150, 128, 165, 165, 173,
  106089. /* 1000 */ 174, 187, 166, 166, 22, 173, 174, 187, 109, 194,
  106090. /* 1010 */ 165, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  106091. /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
  106092. /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 150, 193, 165,
  106093. /* 1040 */ 102, 205, 205, 150, 150, 247, 248, 173, 174, 19,
  106094. /* 1050 */ 150, 20, 165, 150, 150, 150, 150, 150, 165, 165,
  106095. /* 1060 */ 173, 174, 49, 50, 104, 165, 49, 50, 165, 165,
  106096. /* 1070 */ 165, 165, 165, 173, 174, 43, 173, 174, 173, 174,
  106097. /* 1080 */ 187, 24, 190, 191, 71, 72, 69, 70, 71, 72,
  106098. /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  106099. /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  106100. /* 1110 */ 19, 98, 150, 165, 150, 150, 150, 150, 150, 150,
  106101. /* 1120 */ 59, 173, 174, 25, 150, 190, 191, 165, 53, 165,
  106102. /* 1130 */ 165, 165, 165, 165, 165, 173, 174, 173, 174, 165,
  106103. /* 1140 */ 49, 50, 91, 92, 1, 2, 53, 173, 174, 138,
  106104. /* 1150 */ 104, 22, 5, 1, 35, 118, 127, 150, 193, 193,
  106105. /* 1160 */ 193, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  106106. /* 1170 */ 79, 80, 165, 82, 83, 84, 85, 86, 87, 88,
  106107. /* 1180 */ 89, 90, 91, 92, 19, 20, 150, 22, 150, 27,
  106108. /* 1190 */ 150, 26, 27, 108, 150, 22, 76, 76, 150, 25,
  106109. /* 1200 */ 193, 165, 37, 165, 150, 165, 22, 19, 20, 165,
  106110. /* 1210 */ 22, 173, 174, 165, 26, 27, 23, 150, 119, 165,
  106111. /* 1220 */ 150, 56, 150, 150, 150, 37, 16, 173, 174, 193,
  106112. /* 1230 */ 150, 66, 165, 193, 1, 165, 121, 165, 165, 165,
  106113. /* 1240 */ 20, 146, 147, 119, 56, 165, 150, 152, 16, 154,
  106114. /* 1250 */ 150, 86, 87, 88, 66, 160, 150, 150, 93, 94,
  106115. /* 1260 */ 95, 165, 150, 98, 108, 165, 127, 23, 65, 173,
  106116. /* 1270 */ 174, 165, 165, 150, 86, 87, 128, 165, 150, 173,
  106117. /* 1280 */ 174, 93, 94, 95, 23, 150, 98, 15, 165, 194,
  106118. /* 1290 */ 150, 140, 22, 165, 129, 130, 131, 132, 133, 134,
  106119. /* 1300 */ 165, 173, 174, 3, 116, 165, 19, 20, 150, 22,
  106120. /* 1310 */ 4, 150, 217, 26, 27, 179, 179, 129, 130, 131,
  106121. /* 1320 */ 132, 133, 134, 165, 37, 150, 165, 150, 164, 19,
  106122. /* 1330 */ 20, 150, 22, 246, 149, 249, 26, 27, 249, 244,
  106123. /* 1340 */ 165, 150, 165, 56, 6, 150, 165, 37, 173, 174,
  106124. /* 1350 */ 173, 174, 150, 66, 173, 174, 165, 149, 149, 13,
  106125. /* 1360 */ 165, 25, 150, 150, 150, 149, 56, 165, 150, 116,
  106126. /* 1370 */ 151, 150, 150, 86, 87, 150, 66, 165, 165, 165,
  106127. /* 1380 */ 93, 94, 95, 165, 150, 98, 165, 165, 151, 22,
  106128. /* 1390 */ 165, 194, 150, 26, 27, 150, 86, 87, 159, 165,
  106129. /* 1400 */ 199, 126, 123, 93, 94, 95, 200, 165, 98, 124,
  106130. /* 1410 */ 165, 122, 201, 125, 225, 135, 129, 130, 131, 132,
  106131. /* 1420 */ 133, 134, 5, 157, 157, 202, 118, 10, 11, 12,
  106132. /* 1430 */ 13, 14, 203, 66, 17, 104, 210, 121, 211, 129,
  106133. /* 1440 */ 130, 131, 132, 133, 134, 210, 175, 211, 31, 211,
  106134. /* 1450 */ 33, 210, 104, 86, 87, 47, 175, 183, 175, 42,
  106135. /* 1460 */ 103, 94, 178, 177, 22, 98, 175, 92, 228, 175,
  106136. /* 1470 */ 175, 228, 55, 183, 57, 178, 175, 156, 61, 18,
  106137. /* 1480 */ 157, 64, 156, 235, 157, 156, 45, 157, 236, 157,
  106138. /* 1490 */ 135, 156, 199, 189, 157, 68, 129, 130, 131, 22,
  106139. /* 1500 */ 189, 199, 157, 156, 192, 18, 192, 192, 199, 192,
  106140. /* 1510 */ 218, 189, 40, 157, 218, 157, 240, 240, 157, 38,
  106141. /* 1520 */ 196, 243, 105, 106, 107, 153, 198, 209, 111, 166,
  106142. /* 1530 */ 176, 181, 166, 116, 166, 230, 176, 230, 176, 226,
  106143. /* 1540 */ 199, 177, 239, 209, 185, 148, 166, 195, 209, 196,
  106144. /* 1550 */ 199, 208, 182, 233, 173, 182, 139, 186, 239, 234,
  106145. /* 1560 */ 191, 182, 173, 92,
  106146. };
  106147. #define YY_SHIFT_USE_DFLT (-70)
  106148. #define YY_SHIFT_COUNT (417)
  106149. #define YY_SHIFT_MIN (-69)
  106150. #define YY_SHIFT_MAX (1487)
  106151. static const short yy_shift_ofst[] = {
  106152. /* 0 */ 1143, 1188, 1417, 1188, 1287, 1287, 138, 138, -2, -19,
  106153. /* 10 */ 1287, 1287, 1287, 1287, 347, 362, 129, 129, 795, 1165,
  106154. /* 20 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  106155. /* 30 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  106156. /* 40 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
  106157. /* 50 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  106158. /* 60 */ 1287, 1287, 286, 362, 362, 538, 538, 231, 1253, 55,
  106159. /* 70 */ 721, 647, 573, 499, 425, 351, 277, 203, 869, 869,
  106160. /* 80 */ 869, 869, 869, 869, 869, 869, 869, 869, 869, 869,
  106161. /* 90 */ 869, 869, 869, 943, 869, 1017, 1091, 1091, -69, -45,
  106162. /* 100 */ -45, -45, -45, -45, -1, 24, 245, 362, 362, 362,
  106163. /* 110 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  106164. /* 120 */ 362, 362, 362, 388, 356, 362, 362, 362, 362, 362,
  106165. /* 130 */ 732, 868, 231, 1051, 1471, -70, -70, -70, 1367, 57,
  106166. /* 140 */ 434, 434, 289, 291, 285, 1, 204, 572, 539, 362,
  106167. /* 150 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  106168. /* 160 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  106169. /* 170 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  106170. /* 180 */ 362, 506, 506, 506, 705, 1253, 1253, 1253, -70, -70,
  106171. /* 190 */ -70, 171, 171, 160, 502, 502, 502, 446, 432, 511,
  106172. /* 200 */ 422, 358, 335, -12, -12, -12, -12, 576, 294, -12,
  106173. /* 210 */ -12, 295, 595, 141, 600, 730, 723, 723, 805, 730,
  106174. /* 220 */ 805, 439, 911, 231, 865, 231, 865, 807, 865, 723,
  106175. /* 230 */ 766, 633, 633, 231, 284, 63, 608, 1481, 1308, 1308,
  106176. /* 240 */ 1472, 1472, 1308, 1477, 1427, 1275, 1487, 1487, 1487, 1487,
  106177. /* 250 */ 1308, 1461, 1275, 1477, 1427, 1427, 1275, 1308, 1461, 1355,
  106178. /* 260 */ 1441, 1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348,
  106179. /* 270 */ 1348, 1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408,
  106180. /* 280 */ 1348, 1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308,
  106181. /* 290 */ 1280, 1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346,
  106182. /* 300 */ 1338, 1338, 1338, 1338, -70, -70, -70, -70, -70, -70,
  106183. /* 310 */ 1013, 467, 612, 84, 179, -28, 870, 410, 761, 760,
  106184. /* 320 */ 667, 650, 531, 220, 361, 331, 125, 127, 97, 1306,
  106185. /* 330 */ 1300, 1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174,
  106186. /* 340 */ 1139, 1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184,
  106187. /* 350 */ 1174, 1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152,
  106188. /* 360 */ 1147, 1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032, 960,
  106189. /* 370 */ 1057, 1031, 1030, 899, 938, 982, 936, 972, 958, 910,
  106190. /* 380 */ 955, 875, 885, 908, 857, 859, 867, 804, 590, 834,
  106191. /* 390 */ 747, 818, 513, 611, 741, 673, 637, 611, 606, 603,
  106192. /* 400 */ 579, 501, 541, 468, 386, 445, 395, 376, 281, 185,
  106193. /* 410 */ 120, 92, 75, 45, 114, 25, 11, 5,
  106194. };
  106195. #define YY_REDUCE_USE_DFLT (-169)
  106196. #define YY_REDUCE_COUNT (309)
  106197. #define YY_REDUCE_MIN (-168)
  106198. #define YY_REDUCE_MAX (1397)
  106199. static const short yy_reduce_ofst[] = {
  106200. /* 0 */ -141, 90, 1095, 222, 158, 156, 19, 17, 10, -104,
  106201. /* 10 */ 378, 316, 311, 12, 180, 249, 598, 464, 397, 1181,
  106202. /* 20 */ 1177, 1175, 1128, 1106, 1096, 1054, 1038, 974, 964, 962,
  106203. /* 30 */ 948, 905, 903, 900, 887, 874, 832, 826, 816, 813,
  106204. /* 40 */ 800, 758, 755, 752, 742, 739, 726, 685, 681, 668,
  106205. /* 50 */ 665, 652, 607, 604, 594, 591, 578, 530, 528, 526,
  106206. /* 60 */ 385, 18, 477, 466, 519, 444, 350, 435, 405, 488,
  106207. /* 70 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  106208. /* 80 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  106209. /* 90 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  106210. /* 100 */ 488, 488, 488, 488, 488, 488, 488, 1040, 678, 1036,
  106211. /* 110 */ 1007, 967, 966, 965, 845, 686, 610, 684, 317, 672,
  106212. /* 120 */ 893, 327, 623, 522, -7, 820, 814, 157, 154, 101,
  106213. /* 130 */ 702, 494, 580, 488, 488, 488, 488, 488, 614, 586,
  106214. /* 140 */ 935, 892, 968, 1245, 1242, 1234, 1225, 798, 798, 1222,
  106215. /* 150 */ 1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
  106216. /* 160 */ 1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
  106217. /* 170 */ 1070, 1067, 1048, 1044, 969, 968, 907, 906, 904, 894,
  106218. /* 180 */ 833, 837, 836, 340, 827, 815, 775, 68, 722, 646,
  106219. /* 190 */ -168, 1389, 1381, 1371, 1379, 1373, 1370, 1343, 1352, 1369,
  106220. /* 200 */ 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1325, 1320, 1352,
  106221. /* 210 */ 1352, 1343, 1380, 1353, 1397, 1351, 1339, 1334, 1319, 1341,
  106222. /* 220 */ 1303, 1364, 1359, 1368, 1362, 1366, 1360, 1350, 1354, 1318,
  106223. /* 230 */ 1313, 1307, 1305, 1363, 1328, 1324, 1372, 1278, 1361, 1358,
  106224. /* 240 */ 1277, 1276, 1356, 1296, 1322, 1309, 1317, 1315, 1314, 1312,
  106225. /* 250 */ 1345, 1347, 1302, 1292, 1311, 1304, 1293, 1337, 1335, 1252,
  106226. /* 260 */ 1248, 1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301,
  106227. /* 270 */ 1295, 1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274,
  106228. /* 280 */ 1281, 1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266,
  106229. /* 290 */ 1189, 1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219,
  106230. /* 300 */ 1216, 1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
  106231. };
  106232. static const YYACTIONTYPE yy_default[] = {
  106233. /* 0 */ 633, 867, 955, 955, 867, 867, 955, 955, 955, 757,
  106234. /* 10 */ 955, 955, 955, 865, 955, 955, 785, 785, 929, 955,
  106235. /* 20 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106236. /* 30 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106237. /* 40 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106238. /* 50 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106239. /* 60 */ 955, 955, 955, 955, 955, 955, 955, 672, 761, 791,
  106240. /* 70 */ 955, 955, 955, 955, 955, 955, 955, 955, 928, 930,
  106241. /* 80 */ 799, 798, 908, 772, 796, 789, 793, 868, 861, 862,
  106242. /* 90 */ 860, 864, 869, 955, 792, 828, 845, 827, 839, 844,
  106243. /* 100 */ 851, 843, 840, 830, 829, 831, 832, 955, 955, 955,
  106244. /* 110 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106245. /* 120 */ 955, 955, 955, 659, 726, 955, 955, 955, 955, 955,
  106246. /* 130 */ 955, 955, 955, 833, 834, 848, 847, 846, 955, 664,
  106247. /* 140 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106248. /* 150 */ 935, 933, 955, 880, 955, 955, 955, 955, 955, 955,
  106249. /* 160 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106250. /* 170 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106251. /* 180 */ 639, 757, 757, 757, 633, 955, 955, 955, 947, 761,
  106252. /* 190 */ 751, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106253. /* 200 */ 955, 955, 955, 801, 740, 918, 920, 955, 901, 738,
  106254. /* 210 */ 661, 759, 674, 749, 641, 795, 774, 774, 913, 795,
  106255. /* 220 */ 913, 697, 720, 955, 785, 955, 785, 694, 785, 774,
  106256. /* 230 */ 863, 955, 955, 955, 758, 749, 955, 940, 765, 765,
  106257. /* 240 */ 932, 932, 765, 807, 730, 795, 737, 737, 737, 737,
  106258. /* 250 */ 765, 656, 795, 807, 730, 730, 795, 765, 656, 907,
  106259. /* 260 */ 905, 765, 765, 656, 765, 656, 765, 656, 873, 728,
  106260. /* 270 */ 728, 728, 712, 877, 877, 873, 728, 697, 728, 712,
  106261. /* 280 */ 728, 728, 778, 773, 778, 773, 778, 773, 765, 765,
  106262. /* 290 */ 955, 790, 779, 788, 786, 795, 955, 715, 649, 649,
  106263. /* 300 */ 638, 638, 638, 638, 952, 952, 947, 699, 699, 682,
  106264. /* 310 */ 955, 955, 955, 955, 955, 955, 955, 882, 955, 955,
  106265. /* 320 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106266. /* 330 */ 634, 942, 955, 955, 939, 955, 955, 955, 955, 800,
  106267. /* 340 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106268. /* 350 */ 917, 955, 955, 955, 955, 955, 955, 955, 911, 955,
  106269. /* 360 */ 955, 955, 955, 955, 955, 904, 903, 955, 955, 955,
  106270. /* 370 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106271. /* 380 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  106272. /* 390 */ 955, 955, 955, 787, 955, 780, 955, 866, 955, 955,
  106273. /* 400 */ 955, 955, 955, 955, 955, 955, 955, 955, 743, 816,
  106274. /* 410 */ 955, 815, 819, 814, 666, 955, 647, 955, 630, 635,
  106275. /* 420 */ 951, 954, 953, 950, 949, 948, 943, 941, 938, 937,
  106276. /* 430 */ 936, 934, 931, 927, 886, 884, 891, 890, 889, 888,
  106277. /* 440 */ 887, 885, 883, 881, 802, 797, 794, 926, 879, 739,
  106278. /* 450 */ 736, 735, 655, 944, 910, 919, 806, 805, 808, 916,
  106279. /* 460 */ 915, 914, 912, 909, 896, 804, 803, 731, 871, 870,
  106280. /* 470 */ 658, 900, 899, 898, 902, 906, 897, 767, 657, 654,
  106281. /* 480 */ 663, 718, 719, 727, 725, 724, 723, 722, 721, 717,
  106282. /* 490 */ 665, 673, 711, 696, 695, 876, 878, 875, 874, 704,
  106283. /* 500 */ 703, 709, 708, 707, 706, 705, 702, 701, 700, 693,
  106284. /* 510 */ 692, 698, 691, 714, 713, 710, 690, 734, 733, 732,
  106285. /* 520 */ 729, 689, 688, 687, 819, 686, 685, 825, 824, 812,
  106286. /* 530 */ 855, 754, 753, 752, 764, 763, 776, 775, 810, 809,
  106287. /* 540 */ 777, 762, 756, 755, 771, 770, 769, 768, 760, 750,
  106288. /* 550 */ 782, 784, 783, 781, 857, 766, 854, 925, 924, 923,
  106289. /* 560 */ 922, 921, 859, 858, 826, 823, 677, 678, 894, 893,
  106290. /* 570 */ 895, 892, 680, 679, 676, 675, 856, 745, 744, 852,
  106291. /* 580 */ 849, 841, 837, 853, 850, 842, 838, 836, 835, 821,
  106292. /* 590 */ 820, 818, 817, 813, 822, 668, 746, 742, 741, 811,
  106293. /* 600 */ 748, 747, 684, 683, 681, 662, 660, 653, 651, 650,
  106294. /* 610 */ 652, 648, 646, 645, 644, 643, 642, 671, 670, 669,
  106295. /* 620 */ 667, 666, 640, 637, 636, 632, 631, 629,
  106296. };
  106297. /* The next table maps tokens into fallback tokens. If a construct
  106298. ** like the following:
  106299. **
  106300. ** %fallback ID X Y Z.
  106301. **
  106302. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  106303. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  106304. ** but it does not parse, the type of the token is changed to ID and
  106305. ** the parse is retried before an error is thrown.
  106306. */
  106307. #ifdef YYFALLBACK
  106308. static const YYCODETYPE yyFallback[] = {
  106309. 0, /* $ => nothing */
  106310. 0, /* SEMI => nothing */
  106311. 26, /* EXPLAIN => ID */
  106312. 26, /* QUERY => ID */
  106313. 26, /* PLAN => ID */
  106314. 26, /* BEGIN => ID */
  106315. 0, /* TRANSACTION => nothing */
  106316. 26, /* DEFERRED => ID */
  106317. 26, /* IMMEDIATE => ID */
  106318. 26, /* EXCLUSIVE => ID */
  106319. 0, /* COMMIT => nothing */
  106320. 26, /* END => ID */
  106321. 26, /* ROLLBACK => ID */
  106322. 26, /* SAVEPOINT => ID */
  106323. 26, /* RELEASE => ID */
  106324. 0, /* TO => nothing */
  106325. 0, /* TABLE => nothing */
  106326. 0, /* CREATE => nothing */
  106327. 26, /* IF => ID */
  106328. 0, /* NOT => nothing */
  106329. 0, /* EXISTS => nothing */
  106330. 26, /* TEMP => ID */
  106331. 0, /* LP => nothing */
  106332. 0, /* RP => nothing */
  106333. 0, /* AS => nothing */
  106334. 0, /* COMMA => nothing */
  106335. 0, /* ID => nothing */
  106336. 0, /* INDEXED => nothing */
  106337. 26, /* ABORT => ID */
  106338. 26, /* ACTION => ID */
  106339. 26, /* AFTER => ID */
  106340. 26, /* ANALYZE => ID */
  106341. 26, /* ASC => ID */
  106342. 26, /* ATTACH => ID */
  106343. 26, /* BEFORE => ID */
  106344. 26, /* BY => ID */
  106345. 26, /* CASCADE => ID */
  106346. 26, /* CAST => ID */
  106347. 26, /* COLUMNKW => ID */
  106348. 26, /* CONFLICT => ID */
  106349. 26, /* DATABASE => ID */
  106350. 26, /* DESC => ID */
  106351. 26, /* DETACH => ID */
  106352. 26, /* EACH => ID */
  106353. 26, /* FAIL => ID */
  106354. 26, /* FOR => ID */
  106355. 26, /* IGNORE => ID */
  106356. 26, /* INITIALLY => ID */
  106357. 26, /* INSTEAD => ID */
  106358. 26, /* LIKE_KW => ID */
  106359. 26, /* MATCH => ID */
  106360. 26, /* NO => ID */
  106361. 26, /* KEY => ID */
  106362. 26, /* OF => ID */
  106363. 26, /* OFFSET => ID */
  106364. 26, /* PRAGMA => ID */
  106365. 26, /* RAISE => ID */
  106366. 26, /* REPLACE => ID */
  106367. 26, /* RESTRICT => ID */
  106368. 26, /* ROW => ID */
  106369. 26, /* TRIGGER => ID */
  106370. 26, /* VACUUM => ID */
  106371. 26, /* VIEW => ID */
  106372. 26, /* VIRTUAL => ID */
  106373. 26, /* REINDEX => ID */
  106374. 26, /* RENAME => ID */
  106375. 26, /* CTIME_KW => ID */
  106376. };
  106377. #endif /* YYFALLBACK */
  106378. /* The following structure represents a single element of the
  106379. ** parser's stack. Information stored includes:
  106380. **
  106381. ** + The state number for the parser at this level of the stack.
  106382. **
  106383. ** + The value of the token stored at this level of the stack.
  106384. ** (In other words, the "major" token.)
  106385. **
  106386. ** + The semantic value stored at this level of the stack. This is
  106387. ** the information used by the action routines in the grammar.
  106388. ** It is sometimes called the "minor" token.
  106389. */
  106390. struct yyStackEntry {
  106391. YYACTIONTYPE stateno; /* The state-number */
  106392. YYCODETYPE major; /* The major token value. This is the code
  106393. ** number for the token at this stack level */
  106394. YYMINORTYPE minor; /* The user-supplied minor token value. This
  106395. ** is the value of the token */
  106396. };
  106397. typedef struct yyStackEntry yyStackEntry;
  106398. /* The state of the parser is completely contained in an instance of
  106399. ** the following structure */
  106400. struct yyParser {
  106401. int yyidx; /* Index of top element in stack */
  106402. #ifdef YYTRACKMAXSTACKDEPTH
  106403. int yyidxMax; /* Maximum value of yyidx */
  106404. #endif
  106405. int yyerrcnt; /* Shifts left before out of the error */
  106406. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  106407. #if YYSTACKDEPTH<=0
  106408. int yystksz; /* Current side of the stack */
  106409. yyStackEntry *yystack; /* The parser's stack */
  106410. #else
  106411. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  106412. #endif
  106413. };
  106414. typedef struct yyParser yyParser;
  106415. #ifndef NDEBUG
  106416. /* #include <stdio.h> */
  106417. static FILE *yyTraceFILE = 0;
  106418. static char *yyTracePrompt = 0;
  106419. #endif /* NDEBUG */
  106420. #ifndef NDEBUG
  106421. /*
  106422. ** Turn parser tracing on by giving a stream to which to write the trace
  106423. ** and a prompt to preface each trace message. Tracing is turned off
  106424. ** by making either argument NULL
  106425. **
  106426. ** Inputs:
  106427. ** <ul>
  106428. ** <li> A FILE* to which trace output should be written.
  106429. ** If NULL, then tracing is turned off.
  106430. ** <li> A prefix string written at the beginning of every
  106431. ** line of trace output. If NULL, then tracing is
  106432. ** turned off.
  106433. ** </ul>
  106434. **
  106435. ** Outputs:
  106436. ** None.
  106437. */
  106438. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  106439. yyTraceFILE = TraceFILE;
  106440. yyTracePrompt = zTracePrompt;
  106441. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  106442. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  106443. }
  106444. #endif /* NDEBUG */
  106445. #ifndef NDEBUG
  106446. /* For tracing shifts, the names of all terminals and nonterminals
  106447. ** are required. The following table supplies these names */
  106448. static const char *const yyTokenName[] = {
  106449. "$", "SEMI", "EXPLAIN", "QUERY",
  106450. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  106451. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  106452. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  106453. "TABLE", "CREATE", "IF", "NOT",
  106454. "EXISTS", "TEMP", "LP", "RP",
  106455. "AS", "COMMA", "ID", "INDEXED",
  106456. "ABORT", "ACTION", "AFTER", "ANALYZE",
  106457. "ASC", "ATTACH", "BEFORE", "BY",
  106458. "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
  106459. "DATABASE", "DESC", "DETACH", "EACH",
  106460. "FAIL", "FOR", "IGNORE", "INITIALLY",
  106461. "INSTEAD", "LIKE_KW", "MATCH", "NO",
  106462. "KEY", "OF", "OFFSET", "PRAGMA",
  106463. "RAISE", "REPLACE", "RESTRICT", "ROW",
  106464. "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
  106465. "REINDEX", "RENAME", "CTIME_KW", "ANY",
  106466. "OR", "AND", "IS", "BETWEEN",
  106467. "IN", "ISNULL", "NOTNULL", "NE",
  106468. "EQ", "GT", "LE", "LT",
  106469. "GE", "ESCAPE", "BITAND", "BITOR",
  106470. "LSHIFT", "RSHIFT", "PLUS", "MINUS",
  106471. "STAR", "SLASH", "REM", "CONCAT",
  106472. "COLLATE", "BITNOT", "STRING", "JOIN_KW",
  106473. "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
  106474. "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
  106475. "ON", "INSERT", "DELETE", "UPDATE",
  106476. "SET", "DEFERRABLE", "FOREIGN", "DROP",
  106477. "UNION", "ALL", "EXCEPT", "INTERSECT",
  106478. "SELECT", "DISTINCT", "DOT", "FROM",
  106479. "JOIN", "USING", "ORDER", "GROUP",
  106480. "HAVING", "LIMIT", "WHERE", "INTO",
  106481. "VALUES", "INTEGER", "FLOAT", "BLOB",
  106482. "REGISTER", "VARIABLE", "CASE", "WHEN",
  106483. "THEN", "ELSE", "INDEX", "ALTER",
  106484. "ADD", "error", "input", "cmdlist",
  106485. "ecmd", "explain", "cmdx", "cmd",
  106486. "transtype", "trans_opt", "nm", "savepoint_opt",
  106487. "create_table", "create_table_args", "createkw", "temp",
  106488. "ifnotexists", "dbnm", "columnlist", "conslist_opt",
  106489. "select", "column", "columnid", "type",
  106490. "carglist", "id", "ids", "typetoken",
  106491. "typename", "signed", "plus_num", "minus_num",
  106492. "ccons", "term", "expr", "onconf",
  106493. "sortorder", "autoinc", "idxlist_opt", "refargs",
  106494. "defer_subclause", "refarg", "refact", "init_deferred_pred_opt",
  106495. "conslist", "tconscomma", "tcons", "idxlist",
  106496. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  106497. "ifexists", "fullname", "oneselect", "multiselect_op",
  106498. "distinct", "selcollist", "from", "where_opt",
  106499. "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
  106500. "sclp", "as", "seltablist", "stl_prefix",
  106501. "joinop", "indexed_opt", "on_opt", "using_opt",
  106502. "joinop2", "inscollist", "sortlist", "nexprlist",
  106503. "setlist", "insert_cmd", "inscollist_opt", "valuelist",
  106504. "exprlist", "likeop", "between_op", "in_op",
  106505. "case_operand", "case_exprlist", "case_else", "uniqueflag",
  106506. "collate", "nmnum", "number", "trigger_decl",
  106507. "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
  106508. "when_clause", "trigger_cmd", "trnm", "tridxby",
  106509. "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
  106510. "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
  106511. "lp", "anylist",
  106512. };
  106513. #endif /* NDEBUG */
  106514. #ifndef NDEBUG
  106515. /* For tracing reduce actions, the names of all rules are required.
  106516. */
  106517. static const char *const yyRuleName[] = {
  106518. /* 0 */ "input ::= cmdlist",
  106519. /* 1 */ "cmdlist ::= cmdlist ecmd",
  106520. /* 2 */ "cmdlist ::= ecmd",
  106521. /* 3 */ "ecmd ::= SEMI",
  106522. /* 4 */ "ecmd ::= explain cmdx SEMI",
  106523. /* 5 */ "explain ::=",
  106524. /* 6 */ "explain ::= EXPLAIN",
  106525. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  106526. /* 8 */ "cmdx ::= cmd",
  106527. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  106528. /* 10 */ "trans_opt ::=",
  106529. /* 11 */ "trans_opt ::= TRANSACTION",
  106530. /* 12 */ "trans_opt ::= TRANSACTION nm",
  106531. /* 13 */ "transtype ::=",
  106532. /* 14 */ "transtype ::= DEFERRED",
  106533. /* 15 */ "transtype ::= IMMEDIATE",
  106534. /* 16 */ "transtype ::= EXCLUSIVE",
  106535. /* 17 */ "cmd ::= COMMIT trans_opt",
  106536. /* 18 */ "cmd ::= END trans_opt",
  106537. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  106538. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  106539. /* 21 */ "savepoint_opt ::=",
  106540. /* 22 */ "cmd ::= SAVEPOINT nm",
  106541. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  106542. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  106543. /* 25 */ "cmd ::= create_table create_table_args",
  106544. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  106545. /* 27 */ "createkw ::= CREATE",
  106546. /* 28 */ "ifnotexists ::=",
  106547. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  106548. /* 30 */ "temp ::= TEMP",
  106549. /* 31 */ "temp ::=",
  106550. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
  106551. /* 33 */ "create_table_args ::= AS select",
  106552. /* 34 */ "columnlist ::= columnlist COMMA column",
  106553. /* 35 */ "columnlist ::= column",
  106554. /* 36 */ "column ::= columnid type carglist",
  106555. /* 37 */ "columnid ::= nm",
  106556. /* 38 */ "id ::= ID",
  106557. /* 39 */ "id ::= INDEXED",
  106558. /* 40 */ "ids ::= ID|STRING",
  106559. /* 41 */ "nm ::= id",
  106560. /* 42 */ "nm ::= STRING",
  106561. /* 43 */ "nm ::= JOIN_KW",
  106562. /* 44 */ "type ::=",
  106563. /* 45 */ "type ::= typetoken",
  106564. /* 46 */ "typetoken ::= typename",
  106565. /* 47 */ "typetoken ::= typename LP signed RP",
  106566. /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
  106567. /* 49 */ "typename ::= ids",
  106568. /* 50 */ "typename ::= typename ids",
  106569. /* 51 */ "signed ::= plus_num",
  106570. /* 52 */ "signed ::= minus_num",
  106571. /* 53 */ "carglist ::= carglist ccons",
  106572. /* 54 */ "carglist ::=",
  106573. /* 55 */ "ccons ::= CONSTRAINT nm",
  106574. /* 56 */ "ccons ::= DEFAULT term",
  106575. /* 57 */ "ccons ::= DEFAULT LP expr RP",
  106576. /* 58 */ "ccons ::= DEFAULT PLUS term",
  106577. /* 59 */ "ccons ::= DEFAULT MINUS term",
  106578. /* 60 */ "ccons ::= DEFAULT id",
  106579. /* 61 */ "ccons ::= NULL onconf",
  106580. /* 62 */ "ccons ::= NOT NULL onconf",
  106581. /* 63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  106582. /* 64 */ "ccons ::= UNIQUE onconf",
  106583. /* 65 */ "ccons ::= CHECK LP expr RP",
  106584. /* 66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  106585. /* 67 */ "ccons ::= defer_subclause",
  106586. /* 68 */ "ccons ::= COLLATE ids",
  106587. /* 69 */ "autoinc ::=",
  106588. /* 70 */ "autoinc ::= AUTOINCR",
  106589. /* 71 */ "refargs ::=",
  106590. /* 72 */ "refargs ::= refargs refarg",
  106591. /* 73 */ "refarg ::= MATCH nm",
  106592. /* 74 */ "refarg ::= ON INSERT refact",
  106593. /* 75 */ "refarg ::= ON DELETE refact",
  106594. /* 76 */ "refarg ::= ON UPDATE refact",
  106595. /* 77 */ "refact ::= SET NULL",
  106596. /* 78 */ "refact ::= SET DEFAULT",
  106597. /* 79 */ "refact ::= CASCADE",
  106598. /* 80 */ "refact ::= RESTRICT",
  106599. /* 81 */ "refact ::= NO ACTION",
  106600. /* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  106601. /* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  106602. /* 84 */ "init_deferred_pred_opt ::=",
  106603. /* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  106604. /* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  106605. /* 87 */ "conslist_opt ::=",
  106606. /* 88 */ "conslist_opt ::= COMMA conslist",
  106607. /* 89 */ "conslist ::= conslist tconscomma tcons",
  106608. /* 90 */ "conslist ::= tcons",
  106609. /* 91 */ "tconscomma ::= COMMA",
  106610. /* 92 */ "tconscomma ::=",
  106611. /* 93 */ "tcons ::= CONSTRAINT nm",
  106612. /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  106613. /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  106614. /* 96 */ "tcons ::= CHECK LP expr RP onconf",
  106615. /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  106616. /* 98 */ "defer_subclause_opt ::=",
  106617. /* 99 */ "defer_subclause_opt ::= defer_subclause",
  106618. /* 100 */ "onconf ::=",
  106619. /* 101 */ "onconf ::= ON CONFLICT resolvetype",
  106620. /* 102 */ "orconf ::=",
  106621. /* 103 */ "orconf ::= OR resolvetype",
  106622. /* 104 */ "resolvetype ::= raisetype",
  106623. /* 105 */ "resolvetype ::= IGNORE",
  106624. /* 106 */ "resolvetype ::= REPLACE",
  106625. /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
  106626. /* 108 */ "ifexists ::= IF EXISTS",
  106627. /* 109 */ "ifexists ::=",
  106628. /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  106629. /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
  106630. /* 112 */ "cmd ::= select",
  106631. /* 113 */ "select ::= oneselect",
  106632. /* 114 */ "select ::= select multiselect_op oneselect",
  106633. /* 115 */ "multiselect_op ::= UNION",
  106634. /* 116 */ "multiselect_op ::= UNION ALL",
  106635. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  106636. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  106637. /* 119 */ "distinct ::= DISTINCT",
  106638. /* 120 */ "distinct ::= ALL",
  106639. /* 121 */ "distinct ::=",
  106640. /* 122 */ "sclp ::= selcollist COMMA",
  106641. /* 123 */ "sclp ::=",
  106642. /* 124 */ "selcollist ::= sclp expr as",
  106643. /* 125 */ "selcollist ::= sclp STAR",
  106644. /* 126 */ "selcollist ::= sclp nm DOT STAR",
  106645. /* 127 */ "as ::= AS nm",
  106646. /* 128 */ "as ::= ids",
  106647. /* 129 */ "as ::=",
  106648. /* 130 */ "from ::=",
  106649. /* 131 */ "from ::= FROM seltablist",
  106650. /* 132 */ "stl_prefix ::= seltablist joinop",
  106651. /* 133 */ "stl_prefix ::=",
  106652. /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  106653. /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  106654. /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  106655. /* 137 */ "dbnm ::=",
  106656. /* 138 */ "dbnm ::= DOT nm",
  106657. /* 139 */ "fullname ::= nm dbnm",
  106658. /* 140 */ "joinop ::= COMMA|JOIN",
  106659. /* 141 */ "joinop ::= JOIN_KW JOIN",
  106660. /* 142 */ "joinop ::= JOIN_KW nm JOIN",
  106661. /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
  106662. /* 144 */ "on_opt ::= ON expr",
  106663. /* 145 */ "on_opt ::=",
  106664. /* 146 */ "indexed_opt ::=",
  106665. /* 147 */ "indexed_opt ::= INDEXED BY nm",
  106666. /* 148 */ "indexed_opt ::= NOT INDEXED",
  106667. /* 149 */ "using_opt ::= USING LP inscollist RP",
  106668. /* 150 */ "using_opt ::=",
  106669. /* 151 */ "orderby_opt ::=",
  106670. /* 152 */ "orderby_opt ::= ORDER BY sortlist",
  106671. /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
  106672. /* 154 */ "sortlist ::= expr sortorder",
  106673. /* 155 */ "sortorder ::= ASC",
  106674. /* 156 */ "sortorder ::= DESC",
  106675. /* 157 */ "sortorder ::=",
  106676. /* 158 */ "groupby_opt ::=",
  106677. /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
  106678. /* 160 */ "having_opt ::=",
  106679. /* 161 */ "having_opt ::= HAVING expr",
  106680. /* 162 */ "limit_opt ::=",
  106681. /* 163 */ "limit_opt ::= LIMIT expr",
  106682. /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
  106683. /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
  106684. /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
  106685. /* 167 */ "where_opt ::=",
  106686. /* 168 */ "where_opt ::= WHERE expr",
  106687. /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
  106688. /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
  106689. /* 171 */ "setlist ::= nm EQ expr",
  106690. /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
  106691. /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
  106692. /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  106693. /* 175 */ "insert_cmd ::= INSERT orconf",
  106694. /* 176 */ "insert_cmd ::= REPLACE",
  106695. /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
  106696. /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
  106697. /* 179 */ "inscollist_opt ::=",
  106698. /* 180 */ "inscollist_opt ::= LP inscollist RP",
  106699. /* 181 */ "inscollist ::= inscollist COMMA nm",
  106700. /* 182 */ "inscollist ::= nm",
  106701. /* 183 */ "expr ::= term",
  106702. /* 184 */ "expr ::= LP expr RP",
  106703. /* 185 */ "term ::= NULL",
  106704. /* 186 */ "expr ::= id",
  106705. /* 187 */ "expr ::= JOIN_KW",
  106706. /* 188 */ "expr ::= nm DOT nm",
  106707. /* 189 */ "expr ::= nm DOT nm DOT nm",
  106708. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  106709. /* 191 */ "term ::= STRING",
  106710. /* 192 */ "expr ::= REGISTER",
  106711. /* 193 */ "expr ::= VARIABLE",
  106712. /* 194 */ "expr ::= expr COLLATE ids",
  106713. /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
  106714. /* 196 */ "expr ::= ID LP distinct exprlist RP",
  106715. /* 197 */ "expr ::= ID LP STAR RP",
  106716. /* 198 */ "term ::= CTIME_KW",
  106717. /* 199 */ "expr ::= expr AND expr",
  106718. /* 200 */ "expr ::= expr OR expr",
  106719. /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
  106720. /* 202 */ "expr ::= expr EQ|NE expr",
  106721. /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  106722. /* 204 */ "expr ::= expr PLUS|MINUS expr",
  106723. /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
  106724. /* 206 */ "expr ::= expr CONCAT expr",
  106725. /* 207 */ "likeop ::= LIKE_KW",
  106726. /* 208 */ "likeop ::= NOT LIKE_KW",
  106727. /* 209 */ "likeop ::= MATCH",
  106728. /* 210 */ "likeop ::= NOT MATCH",
  106729. /* 211 */ "expr ::= expr likeop expr",
  106730. /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
  106731. /* 213 */ "expr ::= expr ISNULL|NOTNULL",
  106732. /* 214 */ "expr ::= expr NOT NULL",
  106733. /* 215 */ "expr ::= expr IS expr",
  106734. /* 216 */ "expr ::= expr IS NOT expr",
  106735. /* 217 */ "expr ::= NOT expr",
  106736. /* 218 */ "expr ::= BITNOT expr",
  106737. /* 219 */ "expr ::= MINUS expr",
  106738. /* 220 */ "expr ::= PLUS expr",
  106739. /* 221 */ "between_op ::= BETWEEN",
  106740. /* 222 */ "between_op ::= NOT BETWEEN",
  106741. /* 223 */ "expr ::= expr between_op expr AND expr",
  106742. /* 224 */ "in_op ::= IN",
  106743. /* 225 */ "in_op ::= NOT IN",
  106744. /* 226 */ "expr ::= expr in_op LP exprlist RP",
  106745. /* 227 */ "expr ::= LP select RP",
  106746. /* 228 */ "expr ::= expr in_op LP select RP",
  106747. /* 229 */ "expr ::= expr in_op nm dbnm",
  106748. /* 230 */ "expr ::= EXISTS LP select RP",
  106749. /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
  106750. /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  106751. /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
  106752. /* 234 */ "case_else ::= ELSE expr",
  106753. /* 235 */ "case_else ::=",
  106754. /* 236 */ "case_operand ::= expr",
  106755. /* 237 */ "case_operand ::=",
  106756. /* 238 */ "exprlist ::= nexprlist",
  106757. /* 239 */ "exprlist ::=",
  106758. /* 240 */ "nexprlist ::= nexprlist COMMA expr",
  106759. /* 241 */ "nexprlist ::= expr",
  106760. /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
  106761. /* 243 */ "uniqueflag ::= UNIQUE",
  106762. /* 244 */ "uniqueflag ::=",
  106763. /* 245 */ "idxlist_opt ::=",
  106764. /* 246 */ "idxlist_opt ::= LP idxlist RP",
  106765. /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  106766. /* 248 */ "idxlist ::= nm collate sortorder",
  106767. /* 249 */ "collate ::=",
  106768. /* 250 */ "collate ::= COLLATE ids",
  106769. /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
  106770. /* 252 */ "cmd ::= VACUUM",
  106771. /* 253 */ "cmd ::= VACUUM nm",
  106772. /* 254 */ "cmd ::= PRAGMA nm dbnm",
  106773. /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  106774. /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  106775. /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  106776. /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  106777. /* 259 */ "nmnum ::= plus_num",
  106778. /* 260 */ "nmnum ::= nm",
  106779. /* 261 */ "nmnum ::= ON",
  106780. /* 262 */ "nmnum ::= DELETE",
  106781. /* 263 */ "nmnum ::= DEFAULT",
  106782. /* 264 */ "plus_num ::= PLUS number",
  106783. /* 265 */ "plus_num ::= number",
  106784. /* 266 */ "minus_num ::= MINUS number",
  106785. /* 267 */ "number ::= INTEGER|FLOAT",
  106786. /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  106787. /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  106788. /* 270 */ "trigger_time ::= BEFORE",
  106789. /* 271 */ "trigger_time ::= AFTER",
  106790. /* 272 */ "trigger_time ::= INSTEAD OF",
  106791. /* 273 */ "trigger_time ::=",
  106792. /* 274 */ "trigger_event ::= DELETE|INSERT",
  106793. /* 275 */ "trigger_event ::= UPDATE",
  106794. /* 276 */ "trigger_event ::= UPDATE OF inscollist",
  106795. /* 277 */ "foreach_clause ::=",
  106796. /* 278 */ "foreach_clause ::= FOR EACH ROW",
  106797. /* 279 */ "when_clause ::=",
  106798. /* 280 */ "when_clause ::= WHEN expr",
  106799. /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  106800. /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  106801. /* 283 */ "trnm ::= nm",
  106802. /* 284 */ "trnm ::= nm DOT nm",
  106803. /* 285 */ "tridxby ::=",
  106804. /* 286 */ "tridxby ::= INDEXED BY nm",
  106805. /* 287 */ "tridxby ::= NOT INDEXED",
  106806. /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  106807. /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
  106808. /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  106809. /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  106810. /* 292 */ "trigger_cmd ::= select",
  106811. /* 293 */ "expr ::= RAISE LP IGNORE RP",
  106812. /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  106813. /* 295 */ "raisetype ::= ROLLBACK",
  106814. /* 296 */ "raisetype ::= ABORT",
  106815. /* 297 */ "raisetype ::= FAIL",
  106816. /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
  106817. /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  106818. /* 300 */ "cmd ::= DETACH database_kw_opt expr",
  106819. /* 301 */ "key_opt ::=",
  106820. /* 302 */ "key_opt ::= KEY expr",
  106821. /* 303 */ "database_kw_opt ::= DATABASE",
  106822. /* 304 */ "database_kw_opt ::=",
  106823. /* 305 */ "cmd ::= REINDEX",
  106824. /* 306 */ "cmd ::= REINDEX nm dbnm",
  106825. /* 307 */ "cmd ::= ANALYZE",
  106826. /* 308 */ "cmd ::= ANALYZE nm dbnm",
  106827. /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  106828. /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  106829. /* 311 */ "add_column_fullname ::= fullname",
  106830. /* 312 */ "kwcolumn_opt ::=",
  106831. /* 313 */ "kwcolumn_opt ::= COLUMNKW",
  106832. /* 314 */ "cmd ::= create_vtab",
  106833. /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
  106834. /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  106835. /* 317 */ "vtabarglist ::= vtabarg",
  106836. /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  106837. /* 319 */ "vtabarg ::=",
  106838. /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
  106839. /* 321 */ "vtabargtoken ::= ANY",
  106840. /* 322 */ "vtabargtoken ::= lp anylist RP",
  106841. /* 323 */ "lp ::= LP",
  106842. /* 324 */ "anylist ::=",
  106843. /* 325 */ "anylist ::= anylist LP anylist RP",
  106844. /* 326 */ "anylist ::= anylist ANY",
  106845. };
  106846. #endif /* NDEBUG */
  106847. #if YYSTACKDEPTH<=0
  106848. /*
  106849. ** Try to increase the size of the parser stack.
  106850. */
  106851. static void yyGrowStack(yyParser *p){
  106852. int newSize;
  106853. yyStackEntry *pNew;
  106854. newSize = p->yystksz*2 + 100;
  106855. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  106856. if( pNew ){
  106857. p->yystack = pNew;
  106858. p->yystksz = newSize;
  106859. #ifndef NDEBUG
  106860. if( yyTraceFILE ){
  106861. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  106862. yyTracePrompt, p->yystksz);
  106863. }
  106864. #endif
  106865. }
  106866. }
  106867. #endif
  106868. /*
  106869. ** This function allocates a new parser.
  106870. ** The only argument is a pointer to a function which works like
  106871. ** malloc.
  106872. **
  106873. ** Inputs:
  106874. ** A pointer to the function used to allocate memory.
  106875. **
  106876. ** Outputs:
  106877. ** A pointer to a parser. This pointer is used in subsequent calls
  106878. ** to sqlite3Parser and sqlite3ParserFree.
  106879. */
  106880. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
  106881. yyParser *pParser;
  106882. pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  106883. if( pParser ){
  106884. pParser->yyidx = -1;
  106885. #ifdef YYTRACKMAXSTACKDEPTH
  106886. pParser->yyidxMax = 0;
  106887. #endif
  106888. #if YYSTACKDEPTH<=0
  106889. pParser->yystack = NULL;
  106890. pParser->yystksz = 0;
  106891. yyGrowStack(pParser);
  106892. #endif
  106893. }
  106894. return pParser;
  106895. }
  106896. /* The following function deletes the value associated with a
  106897. ** symbol. The symbol can be either a terminal or nonterminal.
  106898. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  106899. ** the value.
  106900. */
  106901. static void yy_destructor(
  106902. yyParser *yypParser, /* The parser */
  106903. YYCODETYPE yymajor, /* Type code for object to destroy */
  106904. YYMINORTYPE *yypminor /* The object to be destroyed */
  106905. ){
  106906. sqlite3ParserARG_FETCH;
  106907. switch( yymajor ){
  106908. /* Here is inserted the actions which take place when a
  106909. ** terminal or non-terminal is destroyed. This can happen
  106910. ** when the symbol is popped from the stack during a
  106911. ** reduce or during error processing or when a parser is
  106912. ** being destroyed before it is finished parsing.
  106913. **
  106914. ** Note: during a reduce, the only symbols destroyed are those
  106915. ** which appear on the RHS of the rule, but which are not used
  106916. ** inside the C code.
  106917. */
  106918. case 160: /* select */
  106919. case 194: /* oneselect */
  106920. {
  106921. sqlite3SelectDelete(pParse->db, (yypminor->yy159));
  106922. }
  106923. break;
  106924. case 173: /* term */
  106925. case 174: /* expr */
  106926. {
  106927. sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
  106928. }
  106929. break;
  106930. case 178: /* idxlist_opt */
  106931. case 187: /* idxlist */
  106932. case 197: /* selcollist */
  106933. case 200: /* groupby_opt */
  106934. case 202: /* orderby_opt */
  106935. case 204: /* sclp */
  106936. case 214: /* sortlist */
  106937. case 215: /* nexprlist */
  106938. case 216: /* setlist */
  106939. case 220: /* exprlist */
  106940. case 225: /* case_exprlist */
  106941. {
  106942. sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
  106943. }
  106944. break;
  106945. case 193: /* fullname */
  106946. case 198: /* from */
  106947. case 206: /* seltablist */
  106948. case 207: /* stl_prefix */
  106949. {
  106950. sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
  106951. }
  106952. break;
  106953. case 199: /* where_opt */
  106954. case 201: /* having_opt */
  106955. case 210: /* on_opt */
  106956. case 224: /* case_operand */
  106957. case 226: /* case_else */
  106958. case 236: /* when_clause */
  106959. case 241: /* key_opt */
  106960. {
  106961. sqlite3ExprDelete(pParse->db, (yypminor->yy122));
  106962. }
  106963. break;
  106964. case 211: /* using_opt */
  106965. case 213: /* inscollist */
  106966. case 218: /* inscollist_opt */
  106967. {
  106968. sqlite3IdListDelete(pParse->db, (yypminor->yy180));
  106969. }
  106970. break;
  106971. case 219: /* valuelist */
  106972. {
  106973. sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
  106974. sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
  106975. }
  106976. break;
  106977. case 232: /* trigger_cmd_list */
  106978. case 237: /* trigger_cmd */
  106979. {
  106980. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
  106981. }
  106982. break;
  106983. case 234: /* trigger_event */
  106984. {
  106985. sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
  106986. }
  106987. break;
  106988. default: break; /* If no destructor action specified: do nothing */
  106989. }
  106990. }
  106991. /*
  106992. ** Pop the parser's stack once.
  106993. **
  106994. ** If there is a destructor routine associated with the token which
  106995. ** is popped from the stack, then call it.
  106996. **
  106997. ** Return the major token number for the symbol popped.
  106998. */
  106999. static int yy_pop_parser_stack(yyParser *pParser){
  107000. YYCODETYPE yymajor;
  107001. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  107002. /* There is no mechanism by which the parser stack can be popped below
  107003. ** empty in SQLite. */
  107004. if( NEVER(pParser->yyidx<0) ) return 0;
  107005. #ifndef NDEBUG
  107006. if( yyTraceFILE && pParser->yyidx>=0 ){
  107007. fprintf(yyTraceFILE,"%sPopping %s\n",
  107008. yyTracePrompt,
  107009. yyTokenName[yytos->major]);
  107010. }
  107011. #endif
  107012. yymajor = yytos->major;
  107013. yy_destructor(pParser, yymajor, &yytos->minor);
  107014. pParser->yyidx--;
  107015. return yymajor;
  107016. }
  107017. /*
  107018. ** Deallocate and destroy a parser. Destructors are all called for
  107019. ** all stack elements before shutting the parser down.
  107020. **
  107021. ** Inputs:
  107022. ** <ul>
  107023. ** <li> A pointer to the parser. This should be a pointer
  107024. ** obtained from sqlite3ParserAlloc.
  107025. ** <li> A pointer to a function used to reclaim memory obtained
  107026. ** from malloc.
  107027. ** </ul>
  107028. */
  107029. SQLITE_PRIVATE void sqlite3ParserFree(
  107030. void *p, /* The parser to be deleted */
  107031. void (*freeProc)(void*) /* Function used to reclaim memory */
  107032. ){
  107033. yyParser *pParser = (yyParser*)p;
  107034. /* In SQLite, we never try to destroy a parser that was not successfully
  107035. ** created in the first place. */
  107036. if( NEVER(pParser==0) ) return;
  107037. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  107038. #if YYSTACKDEPTH<=0
  107039. free(pParser->yystack);
  107040. #endif
  107041. (*freeProc)((void*)pParser);
  107042. }
  107043. /*
  107044. ** Return the peak depth of the stack for a parser.
  107045. */
  107046. #ifdef YYTRACKMAXSTACKDEPTH
  107047. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  107048. yyParser *pParser = (yyParser*)p;
  107049. return pParser->yyidxMax;
  107050. }
  107051. #endif
  107052. /*
  107053. ** Find the appropriate action for a parser given the terminal
  107054. ** look-ahead token iLookAhead.
  107055. **
  107056. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  107057. ** independent of the look-ahead. If it is, return the action, otherwise
  107058. ** return YY_NO_ACTION.
  107059. */
  107060. static int yy_find_shift_action(
  107061. yyParser *pParser, /* The parser */
  107062. YYCODETYPE iLookAhead /* The look-ahead token */
  107063. ){
  107064. int i;
  107065. int stateno = pParser->yystack[pParser->yyidx].stateno;
  107066. if( stateno>YY_SHIFT_COUNT
  107067. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  107068. return yy_default[stateno];
  107069. }
  107070. assert( iLookAhead!=YYNOCODE );
  107071. i += iLookAhead;
  107072. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  107073. if( iLookAhead>0 ){
  107074. #ifdef YYFALLBACK
  107075. YYCODETYPE iFallback; /* Fallback token */
  107076. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  107077. && (iFallback = yyFallback[iLookAhead])!=0 ){
  107078. #ifndef NDEBUG
  107079. if( yyTraceFILE ){
  107080. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  107081. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  107082. }
  107083. #endif
  107084. return yy_find_shift_action(pParser, iFallback);
  107085. }
  107086. #endif
  107087. #ifdef YYWILDCARD
  107088. {
  107089. int j = i - iLookAhead + YYWILDCARD;
  107090. if(
  107091. #if YY_SHIFT_MIN+YYWILDCARD<0
  107092. j>=0 &&
  107093. #endif
  107094. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  107095. j<YY_ACTTAB_COUNT &&
  107096. #endif
  107097. yy_lookahead[j]==YYWILDCARD
  107098. ){
  107099. #ifndef NDEBUG
  107100. if( yyTraceFILE ){
  107101. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  107102. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  107103. }
  107104. #endif /* NDEBUG */
  107105. return yy_action[j];
  107106. }
  107107. }
  107108. #endif /* YYWILDCARD */
  107109. }
  107110. return yy_default[stateno];
  107111. }else{
  107112. return yy_action[i];
  107113. }
  107114. }
  107115. /*
  107116. ** Find the appropriate action for a parser given the non-terminal
  107117. ** look-ahead token iLookAhead.
  107118. **
  107119. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  107120. ** independent of the look-ahead. If it is, return the action, otherwise
  107121. ** return YY_NO_ACTION.
  107122. */
  107123. static int yy_find_reduce_action(
  107124. int stateno, /* Current state number */
  107125. YYCODETYPE iLookAhead /* The look-ahead token */
  107126. ){
  107127. int i;
  107128. #ifdef YYERRORSYMBOL
  107129. if( stateno>YY_REDUCE_COUNT ){
  107130. return yy_default[stateno];
  107131. }
  107132. #else
  107133. assert( stateno<=YY_REDUCE_COUNT );
  107134. #endif
  107135. i = yy_reduce_ofst[stateno];
  107136. assert( i!=YY_REDUCE_USE_DFLT );
  107137. assert( iLookAhead!=YYNOCODE );
  107138. i += iLookAhead;
  107139. #ifdef YYERRORSYMBOL
  107140. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  107141. return yy_default[stateno];
  107142. }
  107143. #else
  107144. assert( i>=0 && i<YY_ACTTAB_COUNT );
  107145. assert( yy_lookahead[i]==iLookAhead );
  107146. #endif
  107147. return yy_action[i];
  107148. }
  107149. /*
  107150. ** The following routine is called if the stack overflows.
  107151. */
  107152. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  107153. sqlite3ParserARG_FETCH;
  107154. yypParser->yyidx--;
  107155. #ifndef NDEBUG
  107156. if( yyTraceFILE ){
  107157. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  107158. }
  107159. #endif
  107160. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  107161. /* Here code is inserted which will execute if the parser
  107162. ** stack every overflows */
  107163. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  107164. sqlite3ErrorMsg(pParse, "parser stack overflow");
  107165. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  107166. }
  107167. /*
  107168. ** Perform a shift action.
  107169. */
  107170. static void yy_shift(
  107171. yyParser *yypParser, /* The parser to be shifted */
  107172. int yyNewState, /* The new state to shift in */
  107173. int yyMajor, /* The major token to shift in */
  107174. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  107175. ){
  107176. yyStackEntry *yytos;
  107177. yypParser->yyidx++;
  107178. #ifdef YYTRACKMAXSTACKDEPTH
  107179. if( yypParser->yyidx>yypParser->yyidxMax ){
  107180. yypParser->yyidxMax = yypParser->yyidx;
  107181. }
  107182. #endif
  107183. #if YYSTACKDEPTH>0
  107184. if( yypParser->yyidx>=YYSTACKDEPTH ){
  107185. yyStackOverflow(yypParser, yypMinor);
  107186. return;
  107187. }
  107188. #else
  107189. if( yypParser->yyidx>=yypParser->yystksz ){
  107190. yyGrowStack(yypParser);
  107191. if( yypParser->yyidx>=yypParser->yystksz ){
  107192. yyStackOverflow(yypParser, yypMinor);
  107193. return;
  107194. }
  107195. }
  107196. #endif
  107197. yytos = &yypParser->yystack[yypParser->yyidx];
  107198. yytos->stateno = (YYACTIONTYPE)yyNewState;
  107199. yytos->major = (YYCODETYPE)yyMajor;
  107200. yytos->minor = *yypMinor;
  107201. #ifndef NDEBUG
  107202. if( yyTraceFILE && yypParser->yyidx>0 ){
  107203. int i;
  107204. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  107205. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  107206. for(i=1; i<=yypParser->yyidx; i++)
  107207. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  107208. fprintf(yyTraceFILE,"\n");
  107209. }
  107210. #endif
  107211. }
  107212. /* The following table contains information about every rule that
  107213. ** is used during the reduce.
  107214. */
  107215. static const struct {
  107216. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  107217. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  107218. } yyRuleInfo[] = {
  107219. { 142, 1 },
  107220. { 143, 2 },
  107221. { 143, 1 },
  107222. { 144, 1 },
  107223. { 144, 3 },
  107224. { 145, 0 },
  107225. { 145, 1 },
  107226. { 145, 3 },
  107227. { 146, 1 },
  107228. { 147, 3 },
  107229. { 149, 0 },
  107230. { 149, 1 },
  107231. { 149, 2 },
  107232. { 148, 0 },
  107233. { 148, 1 },
  107234. { 148, 1 },
  107235. { 148, 1 },
  107236. { 147, 2 },
  107237. { 147, 2 },
  107238. { 147, 2 },
  107239. { 151, 1 },
  107240. { 151, 0 },
  107241. { 147, 2 },
  107242. { 147, 3 },
  107243. { 147, 5 },
  107244. { 147, 2 },
  107245. { 152, 6 },
  107246. { 154, 1 },
  107247. { 156, 0 },
  107248. { 156, 3 },
  107249. { 155, 1 },
  107250. { 155, 0 },
  107251. { 153, 4 },
  107252. { 153, 2 },
  107253. { 158, 3 },
  107254. { 158, 1 },
  107255. { 161, 3 },
  107256. { 162, 1 },
  107257. { 165, 1 },
  107258. { 165, 1 },
  107259. { 166, 1 },
  107260. { 150, 1 },
  107261. { 150, 1 },
  107262. { 150, 1 },
  107263. { 163, 0 },
  107264. { 163, 1 },
  107265. { 167, 1 },
  107266. { 167, 4 },
  107267. { 167, 6 },
  107268. { 168, 1 },
  107269. { 168, 2 },
  107270. { 169, 1 },
  107271. { 169, 1 },
  107272. { 164, 2 },
  107273. { 164, 0 },
  107274. { 172, 2 },
  107275. { 172, 2 },
  107276. { 172, 4 },
  107277. { 172, 3 },
  107278. { 172, 3 },
  107279. { 172, 2 },
  107280. { 172, 2 },
  107281. { 172, 3 },
  107282. { 172, 5 },
  107283. { 172, 2 },
  107284. { 172, 4 },
  107285. { 172, 4 },
  107286. { 172, 1 },
  107287. { 172, 2 },
  107288. { 177, 0 },
  107289. { 177, 1 },
  107290. { 179, 0 },
  107291. { 179, 2 },
  107292. { 181, 2 },
  107293. { 181, 3 },
  107294. { 181, 3 },
  107295. { 181, 3 },
  107296. { 182, 2 },
  107297. { 182, 2 },
  107298. { 182, 1 },
  107299. { 182, 1 },
  107300. { 182, 2 },
  107301. { 180, 3 },
  107302. { 180, 2 },
  107303. { 183, 0 },
  107304. { 183, 2 },
  107305. { 183, 2 },
  107306. { 159, 0 },
  107307. { 159, 2 },
  107308. { 184, 3 },
  107309. { 184, 1 },
  107310. { 185, 1 },
  107311. { 185, 0 },
  107312. { 186, 2 },
  107313. { 186, 7 },
  107314. { 186, 5 },
  107315. { 186, 5 },
  107316. { 186, 10 },
  107317. { 188, 0 },
  107318. { 188, 1 },
  107319. { 175, 0 },
  107320. { 175, 3 },
  107321. { 189, 0 },
  107322. { 189, 2 },
  107323. { 190, 1 },
  107324. { 190, 1 },
  107325. { 190, 1 },
  107326. { 147, 4 },
  107327. { 192, 2 },
  107328. { 192, 0 },
  107329. { 147, 8 },
  107330. { 147, 4 },
  107331. { 147, 1 },
  107332. { 160, 1 },
  107333. { 160, 3 },
  107334. { 195, 1 },
  107335. { 195, 2 },
  107336. { 195, 1 },
  107337. { 194, 9 },
  107338. { 196, 1 },
  107339. { 196, 1 },
  107340. { 196, 0 },
  107341. { 204, 2 },
  107342. { 204, 0 },
  107343. { 197, 3 },
  107344. { 197, 2 },
  107345. { 197, 4 },
  107346. { 205, 2 },
  107347. { 205, 1 },
  107348. { 205, 0 },
  107349. { 198, 0 },
  107350. { 198, 2 },
  107351. { 207, 2 },
  107352. { 207, 0 },
  107353. { 206, 7 },
  107354. { 206, 7 },
  107355. { 206, 7 },
  107356. { 157, 0 },
  107357. { 157, 2 },
  107358. { 193, 2 },
  107359. { 208, 1 },
  107360. { 208, 2 },
  107361. { 208, 3 },
  107362. { 208, 4 },
  107363. { 210, 2 },
  107364. { 210, 0 },
  107365. { 209, 0 },
  107366. { 209, 3 },
  107367. { 209, 2 },
  107368. { 211, 4 },
  107369. { 211, 0 },
  107370. { 202, 0 },
  107371. { 202, 3 },
  107372. { 214, 4 },
  107373. { 214, 2 },
  107374. { 176, 1 },
  107375. { 176, 1 },
  107376. { 176, 0 },
  107377. { 200, 0 },
  107378. { 200, 3 },
  107379. { 201, 0 },
  107380. { 201, 2 },
  107381. { 203, 0 },
  107382. { 203, 2 },
  107383. { 203, 4 },
  107384. { 203, 4 },
  107385. { 147, 5 },
  107386. { 199, 0 },
  107387. { 199, 2 },
  107388. { 147, 7 },
  107389. { 216, 5 },
  107390. { 216, 3 },
  107391. { 147, 5 },
  107392. { 147, 5 },
  107393. { 147, 6 },
  107394. { 217, 2 },
  107395. { 217, 1 },
  107396. { 219, 4 },
  107397. { 219, 5 },
  107398. { 218, 0 },
  107399. { 218, 3 },
  107400. { 213, 3 },
  107401. { 213, 1 },
  107402. { 174, 1 },
  107403. { 174, 3 },
  107404. { 173, 1 },
  107405. { 174, 1 },
  107406. { 174, 1 },
  107407. { 174, 3 },
  107408. { 174, 5 },
  107409. { 173, 1 },
  107410. { 173, 1 },
  107411. { 174, 1 },
  107412. { 174, 1 },
  107413. { 174, 3 },
  107414. { 174, 6 },
  107415. { 174, 5 },
  107416. { 174, 4 },
  107417. { 173, 1 },
  107418. { 174, 3 },
  107419. { 174, 3 },
  107420. { 174, 3 },
  107421. { 174, 3 },
  107422. { 174, 3 },
  107423. { 174, 3 },
  107424. { 174, 3 },
  107425. { 174, 3 },
  107426. { 221, 1 },
  107427. { 221, 2 },
  107428. { 221, 1 },
  107429. { 221, 2 },
  107430. { 174, 3 },
  107431. { 174, 5 },
  107432. { 174, 2 },
  107433. { 174, 3 },
  107434. { 174, 3 },
  107435. { 174, 4 },
  107436. { 174, 2 },
  107437. { 174, 2 },
  107438. { 174, 2 },
  107439. { 174, 2 },
  107440. { 222, 1 },
  107441. { 222, 2 },
  107442. { 174, 5 },
  107443. { 223, 1 },
  107444. { 223, 2 },
  107445. { 174, 5 },
  107446. { 174, 3 },
  107447. { 174, 5 },
  107448. { 174, 4 },
  107449. { 174, 4 },
  107450. { 174, 5 },
  107451. { 225, 5 },
  107452. { 225, 4 },
  107453. { 226, 2 },
  107454. { 226, 0 },
  107455. { 224, 1 },
  107456. { 224, 0 },
  107457. { 220, 1 },
  107458. { 220, 0 },
  107459. { 215, 3 },
  107460. { 215, 1 },
  107461. { 147, 12 },
  107462. { 227, 1 },
  107463. { 227, 0 },
  107464. { 178, 0 },
  107465. { 178, 3 },
  107466. { 187, 5 },
  107467. { 187, 3 },
  107468. { 228, 0 },
  107469. { 228, 2 },
  107470. { 147, 4 },
  107471. { 147, 1 },
  107472. { 147, 2 },
  107473. { 147, 3 },
  107474. { 147, 5 },
  107475. { 147, 6 },
  107476. { 147, 5 },
  107477. { 147, 6 },
  107478. { 229, 1 },
  107479. { 229, 1 },
  107480. { 229, 1 },
  107481. { 229, 1 },
  107482. { 229, 1 },
  107483. { 170, 2 },
  107484. { 170, 1 },
  107485. { 171, 2 },
  107486. { 230, 1 },
  107487. { 147, 5 },
  107488. { 231, 11 },
  107489. { 233, 1 },
  107490. { 233, 1 },
  107491. { 233, 2 },
  107492. { 233, 0 },
  107493. { 234, 1 },
  107494. { 234, 1 },
  107495. { 234, 3 },
  107496. { 235, 0 },
  107497. { 235, 3 },
  107498. { 236, 0 },
  107499. { 236, 2 },
  107500. { 232, 3 },
  107501. { 232, 2 },
  107502. { 238, 1 },
  107503. { 238, 3 },
  107504. { 239, 0 },
  107505. { 239, 3 },
  107506. { 239, 2 },
  107507. { 237, 7 },
  107508. { 237, 5 },
  107509. { 237, 5 },
  107510. { 237, 5 },
  107511. { 237, 1 },
  107512. { 174, 4 },
  107513. { 174, 6 },
  107514. { 191, 1 },
  107515. { 191, 1 },
  107516. { 191, 1 },
  107517. { 147, 4 },
  107518. { 147, 6 },
  107519. { 147, 3 },
  107520. { 241, 0 },
  107521. { 241, 2 },
  107522. { 240, 1 },
  107523. { 240, 0 },
  107524. { 147, 1 },
  107525. { 147, 3 },
  107526. { 147, 1 },
  107527. { 147, 3 },
  107528. { 147, 6 },
  107529. { 147, 6 },
  107530. { 242, 1 },
  107531. { 243, 0 },
  107532. { 243, 1 },
  107533. { 147, 1 },
  107534. { 147, 4 },
  107535. { 244, 8 },
  107536. { 245, 1 },
  107537. { 245, 3 },
  107538. { 246, 0 },
  107539. { 246, 2 },
  107540. { 247, 1 },
  107541. { 247, 3 },
  107542. { 248, 1 },
  107543. { 249, 0 },
  107544. { 249, 4 },
  107545. { 249, 2 },
  107546. };
  107547. static void yy_accept(yyParser*); /* Forward Declaration */
  107548. /*
  107549. ** Perform a reduce action and the shift that must immediately
  107550. ** follow the reduce.
  107551. */
  107552. static void yy_reduce(
  107553. yyParser *yypParser, /* The parser */
  107554. int yyruleno /* Number of the rule by which to reduce */
  107555. ){
  107556. int yygoto; /* The next state */
  107557. int yyact; /* The next action */
  107558. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  107559. yyStackEntry *yymsp; /* The top of the parser's stack */
  107560. int yysize; /* Amount to pop the stack */
  107561. sqlite3ParserARG_FETCH;
  107562. yymsp = &yypParser->yystack[yypParser->yyidx];
  107563. #ifndef NDEBUG
  107564. if( yyTraceFILE && yyruleno>=0
  107565. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  107566. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  107567. yyRuleName[yyruleno]);
  107568. }
  107569. #endif /* NDEBUG */
  107570. /* Silence complaints from purify about yygotominor being uninitialized
  107571. ** in some cases when it is copied into the stack after the following
  107572. ** switch. yygotominor is uninitialized when a rule reduces that does
  107573. ** not set the value of its left-hand side nonterminal. Leaving the
  107574. ** value of the nonterminal uninitialized is utterly harmless as long
  107575. ** as the value is never used. So really the only thing this code
  107576. ** accomplishes is to quieten purify.
  107577. **
  107578. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  107579. ** without this code, their parser segfaults. I'm not sure what there
  107580. ** parser is doing to make this happen. This is the second bug report
  107581. ** from wireshark this week. Clearly they are stressing Lemon in ways
  107582. ** that it has not been previously stressed... (SQLite ticket #2172)
  107583. */
  107584. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  107585. yygotominor = yyzerominor;
  107586. switch( yyruleno ){
  107587. /* Beginning here are the reduction cases. A typical example
  107588. ** follows:
  107589. ** case 0:
  107590. ** #line <lineno> <grammarfile>
  107591. ** { ... } // User supplied code
  107592. ** #line <lineno> <thisfile>
  107593. ** break;
  107594. */
  107595. case 5: /* explain ::= */
  107596. { sqlite3BeginParse(pParse, 0); }
  107597. break;
  107598. case 6: /* explain ::= EXPLAIN */
  107599. { sqlite3BeginParse(pParse, 1); }
  107600. break;
  107601. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  107602. { sqlite3BeginParse(pParse, 2); }
  107603. break;
  107604. case 8: /* cmdx ::= cmd */
  107605. { sqlite3FinishCoding(pParse); }
  107606. break;
  107607. case 9: /* cmd ::= BEGIN transtype trans_opt */
  107608. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
  107609. break;
  107610. case 13: /* transtype ::= */
  107611. {yygotominor.yy392 = TK_DEFERRED;}
  107612. break;
  107613. case 14: /* transtype ::= DEFERRED */
  107614. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  107615. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  107616. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  107617. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  107618. {yygotominor.yy392 = yymsp[0].major;}
  107619. break;
  107620. case 17: /* cmd ::= COMMIT trans_opt */
  107621. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  107622. {sqlite3CommitTransaction(pParse);}
  107623. break;
  107624. case 19: /* cmd ::= ROLLBACK trans_opt */
  107625. {sqlite3RollbackTransaction(pParse);}
  107626. break;
  107627. case 22: /* cmd ::= SAVEPOINT nm */
  107628. {
  107629. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  107630. }
  107631. break;
  107632. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  107633. {
  107634. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  107635. }
  107636. break;
  107637. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  107638. {
  107639. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  107640. }
  107641. break;
  107642. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  107643. {
  107644. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
  107645. }
  107646. break;
  107647. case 27: /* createkw ::= CREATE */
  107648. {
  107649. pParse->db->lookaside.bEnabled = 0;
  107650. yygotominor.yy0 = yymsp[0].minor.yy0;
  107651. }
  107652. break;
  107653. case 28: /* ifnotexists ::= */
  107654. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  107655. case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
  107656. case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
  107657. case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
  107658. case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
  107659. case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
  107660. case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
  107661. case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
  107662. case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
  107663. {yygotominor.yy392 = 0;}
  107664. break;
  107665. case 29: /* ifnotexists ::= IF NOT EXISTS */
  107666. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  107667. case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
  107668. case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
  107669. case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
  107670. case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
  107671. case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
  107672. {yygotominor.yy392 = 1;}
  107673. break;
  107674. case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
  107675. {
  107676. sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
  107677. }
  107678. break;
  107679. case 33: /* create_table_args ::= AS select */
  107680. {
  107681. sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
  107682. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  107683. }
  107684. break;
  107685. case 36: /* column ::= columnid type carglist */
  107686. {
  107687. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  107688. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  107689. }
  107690. break;
  107691. case 37: /* columnid ::= nm */
  107692. {
  107693. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  107694. yygotominor.yy0 = yymsp[0].minor.yy0;
  107695. pParse->constraintName.n = 0;
  107696. }
  107697. break;
  107698. case 38: /* id ::= ID */
  107699. case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
  107700. case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
  107701. case 41: /* nm ::= id */ yytestcase(yyruleno==41);
  107702. case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
  107703. case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
  107704. case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
  107705. case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
  107706. case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
  107707. case 128: /* as ::= ids */ yytestcase(yyruleno==128);
  107708. case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
  107709. case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
  107710. case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
  107711. case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
  107712. case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
  107713. case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
  107714. case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
  107715. case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
  107716. case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
  107717. case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
  107718. case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
  107719. case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
  107720. case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
  107721. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  107722. break;
  107723. case 45: /* type ::= typetoken */
  107724. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  107725. break;
  107726. case 47: /* typetoken ::= typename LP signed RP */
  107727. {
  107728. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  107729. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  107730. }
  107731. break;
  107732. case 48: /* typetoken ::= typename LP signed COMMA signed RP */
  107733. {
  107734. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  107735. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  107736. }
  107737. break;
  107738. case 50: /* typename ::= typename ids */
  107739. {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);}
  107740. break;
  107741. case 55: /* ccons ::= CONSTRAINT nm */
  107742. case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
  107743. {pParse->constraintName = yymsp[0].minor.yy0;}
  107744. break;
  107745. case 56: /* ccons ::= DEFAULT term */
  107746. case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
  107747. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
  107748. break;
  107749. case 57: /* ccons ::= DEFAULT LP expr RP */
  107750. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
  107751. break;
  107752. case 59: /* ccons ::= DEFAULT MINUS term */
  107753. {
  107754. ExprSpan v;
  107755. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
  107756. v.zStart = yymsp[-1].minor.yy0.z;
  107757. v.zEnd = yymsp[0].minor.yy342.zEnd;
  107758. sqlite3AddDefaultValue(pParse,&v);
  107759. }
  107760. break;
  107761. case 60: /* ccons ::= DEFAULT id */
  107762. {
  107763. ExprSpan v;
  107764. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  107765. sqlite3AddDefaultValue(pParse,&v);
  107766. }
  107767. break;
  107768. case 62: /* ccons ::= NOT NULL onconf */
  107769. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
  107770. break;
  107771. case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  107772. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
  107773. break;
  107774. case 64: /* ccons ::= UNIQUE onconf */
  107775. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
  107776. break;
  107777. case 65: /* ccons ::= CHECK LP expr RP */
  107778. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
  107779. break;
  107780. case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  107781. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
  107782. break;
  107783. case 67: /* ccons ::= defer_subclause */
  107784. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
  107785. break;
  107786. case 68: /* ccons ::= COLLATE ids */
  107787. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  107788. break;
  107789. case 71: /* refargs ::= */
  107790. { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
  107791. break;
  107792. case 72: /* refargs ::= refargs refarg */
  107793. { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
  107794. break;
  107795. case 73: /* refarg ::= MATCH nm */
  107796. case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
  107797. { yygotominor.yy207.value = 0; yygotominor.yy207.mask = 0x000000; }
  107798. break;
  107799. case 75: /* refarg ::= ON DELETE refact */
  107800. { yygotominor.yy207.value = yymsp[0].minor.yy392; yygotominor.yy207.mask = 0x0000ff; }
  107801. break;
  107802. case 76: /* refarg ::= ON UPDATE refact */
  107803. { yygotominor.yy207.value = yymsp[0].minor.yy392<<8; yygotominor.yy207.mask = 0x00ff00; }
  107804. break;
  107805. case 77: /* refact ::= SET NULL */
  107806. { yygotominor.yy392 = OE_SetNull; /* EV: R-33326-45252 */}
  107807. break;
  107808. case 78: /* refact ::= SET DEFAULT */
  107809. { yygotominor.yy392 = OE_SetDflt; /* EV: R-33326-45252 */}
  107810. break;
  107811. case 79: /* refact ::= CASCADE */
  107812. { yygotominor.yy392 = OE_Cascade; /* EV: R-33326-45252 */}
  107813. break;
  107814. case 80: /* refact ::= RESTRICT */
  107815. { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
  107816. break;
  107817. case 81: /* refact ::= NO ACTION */
  107818. { yygotominor.yy392 = OE_None; /* EV: R-33326-45252 */}
  107819. break;
  107820. case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  107821. case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
  107822. case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
  107823. case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
  107824. {yygotominor.yy392 = yymsp[0].minor.yy392;}
  107825. break;
  107826. case 87: /* conslist_opt ::= */
  107827. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  107828. break;
  107829. case 88: /* conslist_opt ::= COMMA conslist */
  107830. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  107831. break;
  107832. case 91: /* tconscomma ::= COMMA */
  107833. {pParse->constraintName.n = 0;}
  107834. break;
  107835. case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  107836. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
  107837. break;
  107838. case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
  107839. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
  107840. break;
  107841. case 96: /* tcons ::= CHECK LP expr RP onconf */
  107842. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
  107843. break;
  107844. case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  107845. {
  107846. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
  107847. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
  107848. }
  107849. break;
  107850. case 100: /* onconf ::= */
  107851. {yygotominor.yy392 = OE_Default;}
  107852. break;
  107853. case 102: /* orconf ::= */
  107854. {yygotominor.yy258 = OE_Default;}
  107855. break;
  107856. case 103: /* orconf ::= OR resolvetype */
  107857. {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
  107858. break;
  107859. case 105: /* resolvetype ::= IGNORE */
  107860. {yygotominor.yy392 = OE_Ignore;}
  107861. break;
  107862. case 106: /* resolvetype ::= REPLACE */
  107863. {yygotominor.yy392 = OE_Replace;}
  107864. break;
  107865. case 107: /* cmd ::= DROP TABLE ifexists fullname */
  107866. {
  107867. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
  107868. }
  107869. break;
  107870. case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  107871. {
  107872. sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
  107873. }
  107874. break;
  107875. case 111: /* cmd ::= DROP VIEW ifexists fullname */
  107876. {
  107877. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
  107878. }
  107879. break;
  107880. case 112: /* cmd ::= select */
  107881. {
  107882. SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  107883. sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
  107884. sqlite3ExplainBegin(pParse->pVdbe);
  107885. sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
  107886. sqlite3ExplainFinish(pParse->pVdbe);
  107887. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  107888. }
  107889. break;
  107890. case 113: /* select ::= oneselect */
  107891. {yygotominor.yy159 = yymsp[0].minor.yy159;}
  107892. break;
  107893. case 114: /* select ::= select multiselect_op oneselect */
  107894. {
  107895. if( yymsp[0].minor.yy159 ){
  107896. yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
  107897. yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
  107898. if( yymsp[-1].minor.yy392!=TK_ALL ) pParse->hasCompound = 1;
  107899. }else{
  107900. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
  107901. }
  107902. yygotominor.yy159 = yymsp[0].minor.yy159;
  107903. }
  107904. break;
  107905. case 116: /* multiselect_op ::= UNION ALL */
  107906. {yygotominor.yy392 = TK_ALL;}
  107907. break;
  107908. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  107909. {
  107910. yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy305,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
  107911. }
  107912. break;
  107913. case 119: /* distinct ::= DISTINCT */
  107914. {yygotominor.yy305 = SF_Distinct;}
  107915. break;
  107916. case 120: /* distinct ::= ALL */
  107917. case 121: /* distinct ::= */ yytestcase(yyruleno==121);
  107918. {yygotominor.yy305 = 0;}
  107919. break;
  107920. case 122: /* sclp ::= selcollist COMMA */
  107921. case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
  107922. {yygotominor.yy442 = yymsp[-1].minor.yy442;}
  107923. break;
  107924. case 123: /* sclp ::= */
  107925. case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
  107926. case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
  107927. case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
  107928. case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
  107929. {yygotominor.yy442 = 0;}
  107930. break;
  107931. case 124: /* selcollist ::= sclp expr as */
  107932. {
  107933. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
  107934. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
  107935. sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
  107936. }
  107937. break;
  107938. case 125: /* selcollist ::= sclp STAR */
  107939. {
  107940. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  107941. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
  107942. }
  107943. break;
  107944. case 126: /* selcollist ::= sclp nm DOT STAR */
  107945. {
  107946. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  107947. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  107948. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  107949. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
  107950. }
  107951. break;
  107952. case 129: /* as ::= */
  107953. {yygotominor.yy0.n = 0;}
  107954. break;
  107955. case 130: /* from ::= */
  107956. {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
  107957. break;
  107958. case 131: /* from ::= FROM seltablist */
  107959. {
  107960. yygotominor.yy347 = yymsp[0].minor.yy347;
  107961. sqlite3SrcListShiftJoinType(yygotominor.yy347);
  107962. }
  107963. break;
  107964. case 132: /* stl_prefix ::= seltablist joinop */
  107965. {
  107966. yygotominor.yy347 = yymsp[-1].minor.yy347;
  107967. if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
  107968. }
  107969. break;
  107970. case 133: /* stl_prefix ::= */
  107971. {yygotominor.yy347 = 0;}
  107972. break;
  107973. case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  107974. {
  107975. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  107976. sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
  107977. }
  107978. break;
  107979. case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  107980. {
  107981. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  107982. }
  107983. break;
  107984. case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  107985. {
  107986. if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
  107987. yygotominor.yy347 = yymsp[-4].minor.yy347;
  107988. }else if( yymsp[-4].minor.yy347->nSrc==1 ){
  107989. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  107990. if( yygotominor.yy347 ){
  107991. struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1];
  107992. struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
  107993. pNew->zName = pOld->zName;
  107994. pNew->zDatabase = pOld->zDatabase;
  107995. pNew->pSelect = pOld->pSelect;
  107996. pOld->zName = pOld->zDatabase = 0;
  107997. pOld->pSelect = 0;
  107998. }
  107999. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
  108000. }else{
  108001. Select *pSubquery;
  108002. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
  108003. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
  108004. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  108005. }
  108006. }
  108007. break;
  108008. case 137: /* dbnm ::= */
  108009. case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
  108010. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  108011. break;
  108012. case 139: /* fullname ::= nm dbnm */
  108013. {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  108014. break;
  108015. case 140: /* joinop ::= COMMA|JOIN */
  108016. { yygotominor.yy392 = JT_INNER; }
  108017. break;
  108018. case 141: /* joinop ::= JOIN_KW JOIN */
  108019. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  108020. break;
  108021. case 142: /* joinop ::= JOIN_KW nm JOIN */
  108022. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  108023. break;
  108024. case 143: /* joinop ::= JOIN_KW nm nm JOIN */
  108025. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  108026. break;
  108027. case 144: /* on_opt ::= ON expr */
  108028. case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
  108029. case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
  108030. case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
  108031. case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
  108032. {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
  108033. break;
  108034. case 145: /* on_opt ::= */
  108035. case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
  108036. case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
  108037. case 235: /* case_else ::= */ yytestcase(yyruleno==235);
  108038. case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
  108039. {yygotominor.yy122 = 0;}
  108040. break;
  108041. case 148: /* indexed_opt ::= NOT INDEXED */
  108042. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  108043. break;
  108044. case 149: /* using_opt ::= USING LP inscollist RP */
  108045. case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
  108046. {yygotominor.yy180 = yymsp[-1].minor.yy180;}
  108047. break;
  108048. case 150: /* using_opt ::= */
  108049. case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
  108050. {yygotominor.yy180 = 0;}
  108051. break;
  108052. case 152: /* orderby_opt ::= ORDER BY sortlist */
  108053. case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
  108054. case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
  108055. {yygotominor.yy442 = yymsp[0].minor.yy442;}
  108056. break;
  108057. case 153: /* sortlist ::= sortlist COMMA expr sortorder */
  108058. {
  108059. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
  108060. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  108061. }
  108062. break;
  108063. case 154: /* sortlist ::= expr sortorder */
  108064. {
  108065. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
  108066. if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
  108067. }
  108068. break;
  108069. case 155: /* sortorder ::= ASC */
  108070. case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
  108071. {yygotominor.yy392 = SQLITE_SO_ASC;}
  108072. break;
  108073. case 156: /* sortorder ::= DESC */
  108074. {yygotominor.yy392 = SQLITE_SO_DESC;}
  108075. break;
  108076. case 162: /* limit_opt ::= */
  108077. {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
  108078. break;
  108079. case 163: /* limit_opt ::= LIMIT expr */
  108080. {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
  108081. break;
  108082. case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
  108083. {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
  108084. break;
  108085. case 165: /* limit_opt ::= LIMIT expr COMMA expr */
  108086. {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
  108087. break;
  108088. case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
  108089. {
  108090. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
  108091. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
  108092. }
  108093. break;
  108094. case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
  108095. {
  108096. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
  108097. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
  108098. sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
  108099. }
  108100. break;
  108101. case 170: /* setlist ::= setlist COMMA nm EQ expr */
  108102. {
  108103. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
  108104. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  108105. }
  108106. break;
  108107. case 171: /* setlist ::= nm EQ expr */
  108108. {
  108109. yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
  108110. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  108111. }
  108112. break;
  108113. case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
  108114. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  108115. break;
  108116. case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
  108117. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  108118. break;
  108119. case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  108120. {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
  108121. break;
  108122. case 175: /* insert_cmd ::= INSERT orconf */
  108123. {yygotominor.yy258 = yymsp[0].minor.yy258;}
  108124. break;
  108125. case 176: /* insert_cmd ::= REPLACE */
  108126. {yygotominor.yy258 = OE_Replace;}
  108127. break;
  108128. case 177: /* valuelist ::= VALUES LP nexprlist RP */
  108129. {
  108130. yygotominor.yy487.pList = yymsp[-1].minor.yy442;
  108131. yygotominor.yy487.pSelect = 0;
  108132. }
  108133. break;
  108134. case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
  108135. {
  108136. Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
  108137. if( yymsp[-4].minor.yy487.pList ){
  108138. yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
  108139. yymsp[-4].minor.yy487.pList = 0;
  108140. }
  108141. yygotominor.yy487.pList = 0;
  108142. if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
  108143. sqlite3SelectDelete(pParse->db, pRight);
  108144. sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
  108145. yygotominor.yy487.pSelect = 0;
  108146. }else{
  108147. pRight->op = TK_ALL;
  108148. pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
  108149. pRight->selFlags |= SF_Values;
  108150. pRight->pPrior->selFlags |= SF_Values;
  108151. yygotominor.yy487.pSelect = pRight;
  108152. }
  108153. }
  108154. break;
  108155. case 181: /* inscollist ::= inscollist COMMA nm */
  108156. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
  108157. break;
  108158. case 182: /* inscollist ::= nm */
  108159. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  108160. break;
  108161. case 183: /* expr ::= term */
  108162. {yygotominor.yy342 = yymsp[0].minor.yy342;}
  108163. break;
  108164. case 184: /* expr ::= LP expr RP */
  108165. {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  108166. break;
  108167. case 185: /* term ::= NULL */
  108168. case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
  108169. case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
  108170. {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  108171. break;
  108172. case 186: /* expr ::= id */
  108173. case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
  108174. {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
  108175. break;
  108176. case 188: /* expr ::= nm DOT nm */
  108177. {
  108178. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  108179. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  108180. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  108181. spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  108182. }
  108183. break;
  108184. case 189: /* expr ::= nm DOT nm DOT nm */
  108185. {
  108186. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  108187. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  108188. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  108189. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  108190. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  108191. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  108192. }
  108193. break;
  108194. case 192: /* expr ::= REGISTER */
  108195. {
  108196. /* When doing a nested parse, one can include terms in an expression
  108197. ** that look like this: #1 #2 ... These terms refer to registers
  108198. ** in the virtual machine. #N is the N-th register. */
  108199. if( pParse->nested==0 ){
  108200. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  108201. yygotominor.yy342.pExpr = 0;
  108202. }else{
  108203. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  108204. if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
  108205. }
  108206. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  108207. }
  108208. break;
  108209. case 193: /* expr ::= VARIABLE */
  108210. {
  108211. spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  108212. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
  108213. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  108214. }
  108215. break;
  108216. case 194: /* expr ::= expr COLLATE ids */
  108217. {
  108218. yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
  108219. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  108220. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  108221. }
  108222. break;
  108223. case 195: /* expr ::= CAST LP expr AS typetoken RP */
  108224. {
  108225. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
  108226. spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  108227. }
  108228. break;
  108229. case 196: /* expr ::= ID LP distinct exprlist RP */
  108230. {
  108231. if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  108232. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  108233. }
  108234. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
  108235. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  108236. if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){
  108237. yygotominor.yy342.pExpr->flags |= EP_Distinct;
  108238. }
  108239. }
  108240. break;
  108241. case 197: /* expr ::= ID LP STAR RP */
  108242. {
  108243. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  108244. spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  108245. }
  108246. break;
  108247. case 198: /* term ::= CTIME_KW */
  108248. {
  108249. /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  108250. ** treated as functions that return constants */
  108251. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  108252. if( yygotominor.yy342.pExpr ){
  108253. yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
  108254. }
  108255. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  108256. }
  108257. break;
  108258. case 199: /* expr ::= expr AND expr */
  108259. case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
  108260. case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
  108261. case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
  108262. case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
  108263. case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
  108264. case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
  108265. case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
  108266. {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
  108267. break;
  108268. case 207: /* likeop ::= LIKE_KW */
  108269. case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
  108270. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
  108271. break;
  108272. case 208: /* likeop ::= NOT LIKE_KW */
  108273. case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
  108274. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
  108275. break;
  108276. case 211: /* expr ::= expr likeop expr */
  108277. {
  108278. ExprList *pList;
  108279. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
  108280. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
  108281. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
  108282. if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  108283. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  108284. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  108285. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  108286. }
  108287. break;
  108288. case 212: /* expr ::= expr likeop expr ESCAPE expr */
  108289. {
  108290. ExprList *pList;
  108291. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  108292. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
  108293. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  108294. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
  108295. if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  108296. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  108297. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  108298. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  108299. }
  108300. break;
  108301. case 213: /* expr ::= expr ISNULL|NOTNULL */
  108302. {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
  108303. break;
  108304. case 214: /* expr ::= expr NOT NULL */
  108305. {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
  108306. break;
  108307. case 215: /* expr ::= expr IS expr */
  108308. {
  108309. spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
  108310. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
  108311. }
  108312. break;
  108313. case 216: /* expr ::= expr IS NOT expr */
  108314. {
  108315. spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
  108316. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
  108317. }
  108318. break;
  108319. case 217: /* expr ::= NOT expr */
  108320. case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
  108321. {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  108322. break;
  108323. case 219: /* expr ::= MINUS expr */
  108324. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  108325. break;
  108326. case 220: /* expr ::= PLUS expr */
  108327. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  108328. break;
  108329. case 223: /* expr ::= expr between_op expr AND expr */
  108330. {
  108331. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  108332. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  108333. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  108334. if( yygotominor.yy342.pExpr ){
  108335. yygotominor.yy342.pExpr->x.pList = pList;
  108336. }else{
  108337. sqlite3ExprListDelete(pParse->db, pList);
  108338. }
  108339. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  108340. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  108341. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  108342. }
  108343. break;
  108344. case 226: /* expr ::= expr in_op LP exprlist RP */
  108345. {
  108346. if( yymsp[-1].minor.yy442==0 ){
  108347. /* Expressions of the form
  108348. **
  108349. ** expr1 IN ()
  108350. ** expr1 NOT IN ()
  108351. **
  108352. ** simplify to constants 0 (false) and 1 (true), respectively,
  108353. ** regardless of the value of expr1.
  108354. */
  108355. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
  108356. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
  108357. }else{
  108358. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  108359. if( yygotominor.yy342.pExpr ){
  108360. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
  108361. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  108362. }else{
  108363. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
  108364. }
  108365. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  108366. }
  108367. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  108368. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  108369. }
  108370. break;
  108371. case 227: /* expr ::= LP select RP */
  108372. {
  108373. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  108374. if( yygotominor.yy342.pExpr ){
  108375. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  108376. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  108377. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  108378. }else{
  108379. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  108380. }
  108381. yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
  108382. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  108383. }
  108384. break;
  108385. case 228: /* expr ::= expr in_op LP select RP */
  108386. {
  108387. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  108388. if( yygotominor.yy342.pExpr ){
  108389. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  108390. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  108391. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  108392. }else{
  108393. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  108394. }
  108395. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  108396. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  108397. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  108398. }
  108399. break;
  108400. case 229: /* expr ::= expr in_op nm dbnm */
  108401. {
  108402. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  108403. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
  108404. if( yygotominor.yy342.pExpr ){
  108405. yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  108406. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  108407. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  108408. }else{
  108409. sqlite3SrcListDelete(pParse->db, pSrc);
  108410. }
  108411. if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  108412. yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
  108413. yygotominor.yy342.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];
  108414. }
  108415. break;
  108416. case 230: /* expr ::= EXISTS LP select RP */
  108417. {
  108418. Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  108419. if( p ){
  108420. p->x.pSelect = yymsp[-1].minor.yy159;
  108421. ExprSetProperty(p, EP_xIsSelect);
  108422. sqlite3ExprSetHeight(pParse, p);
  108423. }else{
  108424. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  108425. }
  108426. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  108427. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  108428. }
  108429. break;
  108430. case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
  108431. {
  108432. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, 0, 0);
  108433. if( yygotominor.yy342.pExpr ){
  108434. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy122 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[-1].minor.yy122) : yymsp[-2].minor.yy442;
  108435. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  108436. }else{
  108437. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
  108438. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy122);
  108439. }
  108440. yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
  108441. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  108442. }
  108443. break;
  108444. case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  108445. {
  108446. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
  108447. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  108448. }
  108449. break;
  108450. case 233: /* case_exprlist ::= WHEN expr THEN expr */
  108451. {
  108452. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  108453. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  108454. }
  108455. break;
  108456. case 240: /* nexprlist ::= nexprlist COMMA expr */
  108457. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
  108458. break;
  108459. case 241: /* nexprlist ::= expr */
  108460. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
  108461. break;
  108462. case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
  108463. {
  108464. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  108465. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy442, yymsp[-10].minor.yy392,
  108466. &yymsp[-11].minor.yy0, yymsp[0].minor.yy122, SQLITE_SO_ASC, yymsp[-8].minor.yy392);
  108467. }
  108468. break;
  108469. case 243: /* uniqueflag ::= UNIQUE */
  108470. case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
  108471. {yygotominor.yy392 = OE_Abort;}
  108472. break;
  108473. case 244: /* uniqueflag ::= */
  108474. {yygotominor.yy392 = OE_None;}
  108475. break;
  108476. case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
  108477. {
  108478. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  108479. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
  108480. sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
  108481. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  108482. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  108483. }
  108484. break;
  108485. case 248: /* idxlist ::= nm collate sortorder */
  108486. {
  108487. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  108488. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
  108489. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  108490. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  108491. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  108492. }
  108493. break;
  108494. case 249: /* collate ::= */
  108495. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  108496. break;
  108497. case 251: /* cmd ::= DROP INDEX ifexists fullname */
  108498. {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
  108499. break;
  108500. case 252: /* cmd ::= VACUUM */
  108501. case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
  108502. {sqlite3Vacuum(pParse);}
  108503. break;
  108504. case 254: /* cmd ::= PRAGMA nm dbnm */
  108505. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  108506. break;
  108507. case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  108508. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  108509. break;
  108510. case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  108511. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  108512. break;
  108513. case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  108514. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  108515. break;
  108516. case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  108517. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  108518. break;
  108519. case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  108520. {
  108521. Token all;
  108522. all.z = yymsp[-3].minor.yy0.z;
  108523. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  108524. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
  108525. }
  108526. break;
  108527. case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  108528. {
  108529. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
  108530. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  108531. }
  108532. break;
  108533. case 270: /* trigger_time ::= BEFORE */
  108534. case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
  108535. { yygotominor.yy392 = TK_BEFORE; }
  108536. break;
  108537. case 271: /* trigger_time ::= AFTER */
  108538. { yygotominor.yy392 = TK_AFTER; }
  108539. break;
  108540. case 272: /* trigger_time ::= INSTEAD OF */
  108541. { yygotominor.yy392 = TK_INSTEAD;}
  108542. break;
  108543. case 274: /* trigger_event ::= DELETE|INSERT */
  108544. case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
  108545. {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
  108546. break;
  108547. case 276: /* trigger_event ::= UPDATE OF inscollist */
  108548. {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
  108549. break;
  108550. case 279: /* when_clause ::= */
  108551. case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
  108552. { yygotominor.yy122 = 0; }
  108553. break;
  108554. case 280: /* when_clause ::= WHEN expr */
  108555. case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
  108556. { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
  108557. break;
  108558. case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  108559. {
  108560. assert( yymsp[-2].minor.yy327!=0 );
  108561. yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
  108562. yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
  108563. yygotominor.yy327 = yymsp[-2].minor.yy327;
  108564. }
  108565. break;
  108566. case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
  108567. {
  108568. assert( yymsp[-1].minor.yy327!=0 );
  108569. yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
  108570. yygotominor.yy327 = yymsp[-1].minor.yy327;
  108571. }
  108572. break;
  108573. case 284: /* trnm ::= nm DOT nm */
  108574. {
  108575. yygotominor.yy0 = yymsp[0].minor.yy0;
  108576. sqlite3ErrorMsg(pParse,
  108577. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  108578. "statements within triggers");
  108579. }
  108580. break;
  108581. case 286: /* tridxby ::= INDEXED BY nm */
  108582. {
  108583. sqlite3ErrorMsg(pParse,
  108584. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  108585. "within triggers");
  108586. }
  108587. break;
  108588. case 287: /* tridxby ::= NOT INDEXED */
  108589. {
  108590. sqlite3ErrorMsg(pParse,
  108591. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  108592. "within triggers");
  108593. }
  108594. break;
  108595. case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  108596. { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
  108597. break;
  108598. case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
  108599. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);}
  108600. break;
  108601. case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  108602. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
  108603. break;
  108604. case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  108605. {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
  108606. break;
  108607. case 292: /* trigger_cmd ::= select */
  108608. {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
  108609. break;
  108610. case 293: /* expr ::= RAISE LP IGNORE RP */
  108611. {
  108612. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  108613. if( yygotominor.yy342.pExpr ){
  108614. yygotominor.yy342.pExpr->affinity = OE_Ignore;
  108615. }
  108616. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  108617. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  108618. }
  108619. break;
  108620. case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
  108621. {
  108622. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  108623. if( yygotominor.yy342.pExpr ) {
  108624. yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
  108625. }
  108626. yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
  108627. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  108628. }
  108629. break;
  108630. case 295: /* raisetype ::= ROLLBACK */
  108631. {yygotominor.yy392 = OE_Rollback;}
  108632. break;
  108633. case 297: /* raisetype ::= FAIL */
  108634. {yygotominor.yy392 = OE_Fail;}
  108635. break;
  108636. case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
  108637. {
  108638. sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
  108639. }
  108640. break;
  108641. case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  108642. {
  108643. sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
  108644. }
  108645. break;
  108646. case 300: /* cmd ::= DETACH database_kw_opt expr */
  108647. {
  108648. sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
  108649. }
  108650. break;
  108651. case 305: /* cmd ::= REINDEX */
  108652. {sqlite3Reindex(pParse, 0, 0);}
  108653. break;
  108654. case 306: /* cmd ::= REINDEX nm dbnm */
  108655. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  108656. break;
  108657. case 307: /* cmd ::= ANALYZE */
  108658. {sqlite3Analyze(pParse, 0, 0);}
  108659. break;
  108660. case 308: /* cmd ::= ANALYZE nm dbnm */
  108661. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  108662. break;
  108663. case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  108664. {
  108665. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
  108666. }
  108667. break;
  108668. case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  108669. {
  108670. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  108671. }
  108672. break;
  108673. case 311: /* add_column_fullname ::= fullname */
  108674. {
  108675. pParse->db->lookaside.bEnabled = 0;
  108676. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
  108677. }
  108678. break;
  108679. case 314: /* cmd ::= create_vtab */
  108680. {sqlite3VtabFinishParse(pParse,0);}
  108681. break;
  108682. case 315: /* cmd ::= create_vtab LP vtabarglist RP */
  108683. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  108684. break;
  108685. case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  108686. {
  108687. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
  108688. }
  108689. break;
  108690. case 319: /* vtabarg ::= */
  108691. {sqlite3VtabArgInit(pParse);}
  108692. break;
  108693. case 321: /* vtabargtoken ::= ANY */
  108694. case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
  108695. case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
  108696. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  108697. break;
  108698. default:
  108699. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  108700. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  108701. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  108702. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  108703. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  108704. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  108705. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  108706. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  108707. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  108708. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  108709. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  108710. /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
  108711. /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
  108712. /* (44) type ::= */ yytestcase(yyruleno==44);
  108713. /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
  108714. /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
  108715. /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
  108716. /* (54) carglist ::= */ yytestcase(yyruleno==54);
  108717. /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
  108718. /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
  108719. /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
  108720. /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
  108721. /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
  108722. /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
  108723. /* (285) tridxby ::= */ yytestcase(yyruleno==285);
  108724. /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
  108725. /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
  108726. /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
  108727. /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
  108728. /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
  108729. /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
  108730. /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
  108731. /* (324) anylist ::= */ yytestcase(yyruleno==324);
  108732. /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
  108733. /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
  108734. break;
  108735. };
  108736. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  108737. yygoto = yyRuleInfo[yyruleno].lhs;
  108738. yysize = yyRuleInfo[yyruleno].nrhs;
  108739. yypParser->yyidx -= yysize;
  108740. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  108741. if( yyact < YYNSTATE ){
  108742. #ifdef NDEBUG
  108743. /* If we are not debugging and the reduce action popped at least
  108744. ** one element off the stack, then we can push the new element back
  108745. ** onto the stack here, and skip the stack overflow test in yy_shift().
  108746. ** That gives a significant speed improvement. */
  108747. if( yysize ){
  108748. yypParser->yyidx++;
  108749. yymsp -= yysize-1;
  108750. yymsp->stateno = (YYACTIONTYPE)yyact;
  108751. yymsp->major = (YYCODETYPE)yygoto;
  108752. yymsp->minor = yygotominor;
  108753. }else
  108754. #endif
  108755. {
  108756. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  108757. }
  108758. }else{
  108759. assert( yyact == YYNSTATE + YYNRULE + 1 );
  108760. yy_accept(yypParser);
  108761. }
  108762. }
  108763. /*
  108764. ** The following code executes when the parse fails
  108765. */
  108766. #ifndef YYNOERRORRECOVERY
  108767. static void yy_parse_failed(
  108768. yyParser *yypParser /* The parser */
  108769. ){
  108770. sqlite3ParserARG_FETCH;
  108771. #ifndef NDEBUG
  108772. if( yyTraceFILE ){
  108773. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  108774. }
  108775. #endif
  108776. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  108777. /* Here code is inserted which will be executed whenever the
  108778. ** parser fails */
  108779. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  108780. }
  108781. #endif /* YYNOERRORRECOVERY */
  108782. /*
  108783. ** The following code executes when a syntax error first occurs.
  108784. */
  108785. static void yy_syntax_error(
  108786. yyParser *yypParser, /* The parser */
  108787. int yymajor, /* The major type of the error token */
  108788. YYMINORTYPE yyminor /* The minor type of the error token */
  108789. ){
  108790. sqlite3ParserARG_FETCH;
  108791. #define TOKEN (yyminor.yy0)
  108792. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  108793. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  108794. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  108795. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  108796. }
  108797. /*
  108798. ** The following is executed when the parser accepts
  108799. */
  108800. static void yy_accept(
  108801. yyParser *yypParser /* The parser */
  108802. ){
  108803. sqlite3ParserARG_FETCH;
  108804. #ifndef NDEBUG
  108805. if( yyTraceFILE ){
  108806. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  108807. }
  108808. #endif
  108809. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  108810. /* Here code is inserted which will be executed whenever the
  108811. ** parser accepts */
  108812. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  108813. }
  108814. /* The main parser program.
  108815. ** The first argument is a pointer to a structure obtained from
  108816. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  108817. ** The second argument is the major token number. The third is
  108818. ** the minor token. The fourth optional argument is whatever the
  108819. ** user wants (and specified in the grammar) and is available for
  108820. ** use by the action routines.
  108821. **
  108822. ** Inputs:
  108823. ** <ul>
  108824. ** <li> A pointer to the parser (an opaque structure.)
  108825. ** <li> The major token number.
  108826. ** <li> The minor token number.
  108827. ** <li> An option argument of a grammar-specified type.
  108828. ** </ul>
  108829. **
  108830. ** Outputs:
  108831. ** None.
  108832. */
  108833. SQLITE_PRIVATE void sqlite3Parser(
  108834. void *yyp, /* The parser */
  108835. int yymajor, /* The major token code number */
  108836. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  108837. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  108838. ){
  108839. YYMINORTYPE yyminorunion;
  108840. int yyact; /* The parser action. */
  108841. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  108842. int yyendofinput; /* True if we are at the end of input */
  108843. #endif
  108844. #ifdef YYERRORSYMBOL
  108845. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  108846. #endif
  108847. yyParser *yypParser; /* The parser */
  108848. /* (re)initialize the parser, if necessary */
  108849. yypParser = (yyParser*)yyp;
  108850. if( yypParser->yyidx<0 ){
  108851. #if YYSTACKDEPTH<=0
  108852. if( yypParser->yystksz <=0 ){
  108853. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  108854. yyminorunion = yyzerominor;
  108855. yyStackOverflow(yypParser, &yyminorunion);
  108856. return;
  108857. }
  108858. #endif
  108859. yypParser->yyidx = 0;
  108860. yypParser->yyerrcnt = -1;
  108861. yypParser->yystack[0].stateno = 0;
  108862. yypParser->yystack[0].major = 0;
  108863. }
  108864. yyminorunion.yy0 = yyminor;
  108865. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  108866. yyendofinput = (yymajor==0);
  108867. #endif
  108868. sqlite3ParserARG_STORE;
  108869. #ifndef NDEBUG
  108870. if( yyTraceFILE ){
  108871. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  108872. }
  108873. #endif
  108874. do{
  108875. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  108876. if( yyact<YYNSTATE ){
  108877. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  108878. yypParser->yyerrcnt--;
  108879. yymajor = YYNOCODE;
  108880. }else if( yyact < YYNSTATE + YYNRULE ){
  108881. yy_reduce(yypParser,yyact-YYNSTATE);
  108882. }else{
  108883. assert( yyact == YY_ERROR_ACTION );
  108884. #ifdef YYERRORSYMBOL
  108885. int yymx;
  108886. #endif
  108887. #ifndef NDEBUG
  108888. if( yyTraceFILE ){
  108889. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  108890. }
  108891. #endif
  108892. #ifdef YYERRORSYMBOL
  108893. /* A syntax error has occurred.
  108894. ** The response to an error depends upon whether or not the
  108895. ** grammar defines an error token "ERROR".
  108896. **
  108897. ** This is what we do if the grammar does define ERROR:
  108898. **
  108899. ** * Call the %syntax_error function.
  108900. **
  108901. ** * Begin popping the stack until we enter a state where
  108902. ** it is legal to shift the error symbol, then shift
  108903. ** the error symbol.
  108904. **
  108905. ** * Set the error count to three.
  108906. **
  108907. ** * Begin accepting and shifting new tokens. No new error
  108908. ** processing will occur until three tokens have been
  108909. ** shifted successfully.
  108910. **
  108911. */
  108912. if( yypParser->yyerrcnt<0 ){
  108913. yy_syntax_error(yypParser,yymajor,yyminorunion);
  108914. }
  108915. yymx = yypParser->yystack[yypParser->yyidx].major;
  108916. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  108917. #ifndef NDEBUG
  108918. if( yyTraceFILE ){
  108919. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  108920. yyTracePrompt,yyTokenName[yymajor]);
  108921. }
  108922. #endif
  108923. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  108924. yymajor = YYNOCODE;
  108925. }else{
  108926. while(
  108927. yypParser->yyidx >= 0 &&
  108928. yymx != YYERRORSYMBOL &&
  108929. (yyact = yy_find_reduce_action(
  108930. yypParser->yystack[yypParser->yyidx].stateno,
  108931. YYERRORSYMBOL)) >= YYNSTATE
  108932. ){
  108933. yy_pop_parser_stack(yypParser);
  108934. }
  108935. if( yypParser->yyidx < 0 || yymajor==0 ){
  108936. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  108937. yy_parse_failed(yypParser);
  108938. yymajor = YYNOCODE;
  108939. }else if( yymx!=YYERRORSYMBOL ){
  108940. YYMINORTYPE u2;
  108941. u2.YYERRSYMDT = 0;
  108942. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  108943. }
  108944. }
  108945. yypParser->yyerrcnt = 3;
  108946. yyerrorhit = 1;
  108947. #elif defined(YYNOERRORRECOVERY)
  108948. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  108949. ** do any kind of error recovery. Instead, simply invoke the syntax
  108950. ** error routine and continue going as if nothing had happened.
  108951. **
  108952. ** Applications can set this macro (for example inside %include) if
  108953. ** they intend to abandon the parse upon the first syntax error seen.
  108954. */
  108955. yy_syntax_error(yypParser,yymajor,yyminorunion);
  108956. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  108957. yymajor = YYNOCODE;
  108958. #else /* YYERRORSYMBOL is not defined */
  108959. /* This is what we do if the grammar does not define ERROR:
  108960. **
  108961. ** * Report an error message, and throw away the input token.
  108962. **
  108963. ** * If the input token is $, then fail the parse.
  108964. **
  108965. ** As before, subsequent error messages are suppressed until
  108966. ** three input tokens have been successfully shifted.
  108967. */
  108968. if( yypParser->yyerrcnt<=0 ){
  108969. yy_syntax_error(yypParser,yymajor,yyminorunion);
  108970. }
  108971. yypParser->yyerrcnt = 3;
  108972. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  108973. if( yyendofinput ){
  108974. yy_parse_failed(yypParser);
  108975. }
  108976. yymajor = YYNOCODE;
  108977. #endif
  108978. }
  108979. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  108980. return;
  108981. }
  108982. /************** End of parse.c ***********************************************/
  108983. /************** Begin file tokenize.c ****************************************/
  108984. /*
  108985. ** 2001 September 15
  108986. **
  108987. ** The author disclaims copyright to this source code. In place of
  108988. ** a legal notice, here is a blessing:
  108989. **
  108990. ** May you do good and not evil.
  108991. ** May you find forgiveness for yourself and forgive others.
  108992. ** May you share freely, never taking more than you give.
  108993. **
  108994. *************************************************************************
  108995. ** An tokenizer for SQL
  108996. **
  108997. ** This file contains C code that splits an SQL input string up into
  108998. ** individual tokens and sends those tokens one-by-one over to the
  108999. ** parser for analysis.
  109000. */
  109001. /* #include <stdlib.h> */
  109002. /*
  109003. ** The charMap() macro maps alphabetic characters into their
  109004. ** lower-case ASCII equivalent. On ASCII machines, this is just
  109005. ** an upper-to-lower case map. On EBCDIC machines we also need
  109006. ** to adjust the encoding. Only alphabetic characters and underscores
  109007. ** need to be translated.
  109008. */
  109009. #ifdef SQLITE_ASCII
  109010. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  109011. #endif
  109012. #ifdef SQLITE_EBCDIC
  109013. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  109014. const unsigned char ebcdicToAscii[] = {
  109015. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  109016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  109017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  109018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  109019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  109020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  109021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  109022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  109023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  109024. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  109025. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  109026. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  109027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  109028. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  109029. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  109030. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  109031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  109032. };
  109033. #endif
  109034. /*
  109035. ** The sqlite3KeywordCode function looks up an identifier to determine if
  109036. ** it is a keyword. If it is a keyword, the token code of that keyword is
  109037. ** returned. If the input is not a keyword, TK_ID is returned.
  109038. **
  109039. ** The implementation of this routine was generated by a program,
  109040. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  109041. ** The output of the mkkeywordhash.c program is written into a file
  109042. ** named keywordhash.h and then included into this source file by
  109043. ** the #include below.
  109044. */
  109045. /************** Include keywordhash.h in the middle of tokenize.c ************/
  109046. /************** Begin file keywordhash.h *************************************/
  109047. /***** This file contains automatically generated code ******
  109048. **
  109049. ** The code in this file has been automatically generated by
  109050. **
  109051. ** sqlite/tool/mkkeywordhash.c
  109052. **
  109053. ** The code in this file implements a function that determines whether
  109054. ** or not a given identifier is really an SQL keyword. The same thing
  109055. ** might be implemented more directly using a hand-written hash table.
  109056. ** But by using this automatically generated code, the size of the code
  109057. ** is substantially reduced. This is important for embedded applications
  109058. ** on platforms with limited memory.
  109059. */
  109060. /* Hash score: 175 */
  109061. static int keywordCode(const char *z, int n){
  109062. /* zText[] encodes 811 bytes of keywords in 541 bytes */
  109063. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  109064. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  109065. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  109066. /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
  109067. /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
  109068. /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
  109069. /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
  109070. /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
  109071. /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
  109072. /* INITIALLY */
  109073. static const char zText[540] = {
  109074. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  109075. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  109076. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  109077. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  109078. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  109079. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  109080. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  109081. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  109082. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  109083. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  109084. 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
  109085. 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
  109086. 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
  109087. 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
  109088. 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
  109089. 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
  109090. 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
  109091. 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
  109092. 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
  109093. 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
  109094. 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
  109095. 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
  109096. 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
  109097. 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
  109098. 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
  109099. 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
  109100. 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
  109101. 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
  109102. 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
  109103. 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
  109104. };
  109105. static const unsigned char aHash[127] = {
  109106. 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
  109107. 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
  109108. 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
  109109. 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
  109110. 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
  109111. 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
  109112. 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
  109113. 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
  109114. 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
  109115. 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
  109116. };
  109117. static const unsigned char aNext[121] = {
  109118. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  109119. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  109120. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  109121. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
  109122. 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
  109123. 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
  109124. 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
  109125. 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
  109126. 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
  109127. 35, 64, 0, 0,
  109128. };
  109129. static const unsigned char aLen[121] = {
  109130. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  109131. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  109132. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  109133. 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
  109134. 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
  109135. 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
  109136. 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
  109137. 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
  109138. 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
  109139. 6, 4, 9, 3,
  109140. };
  109141. static const unsigned short int aOffset[121] = {
  109142. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  109143. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  109144. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  109145. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
  109146. 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
  109147. 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
  109148. 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
  109149. 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
  109150. 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
  109151. 521, 527, 531, 536,
  109152. };
  109153. static const unsigned char aCode[121] = {
  109154. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  109155. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  109156. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  109157. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  109158. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  109159. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  109160. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  109161. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  109162. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  109163. TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
  109164. TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
  109165. TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
  109166. TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
  109167. TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
  109168. TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
  109169. TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
  109170. TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
  109171. TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
  109172. TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
  109173. TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
  109174. TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
  109175. TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
  109176. TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
  109177. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
  109178. TK_ALL,
  109179. };
  109180. int h, i;
  109181. if( n<2 ) return TK_ID;
  109182. h = ((charMap(z[0])*4) ^
  109183. (charMap(z[n-1])*3) ^
  109184. n) % 127;
  109185. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  109186. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  109187. testcase( i==0 ); /* REINDEX */
  109188. testcase( i==1 ); /* INDEXED */
  109189. testcase( i==2 ); /* INDEX */
  109190. testcase( i==3 ); /* DESC */
  109191. testcase( i==4 ); /* ESCAPE */
  109192. testcase( i==5 ); /* EACH */
  109193. testcase( i==6 ); /* CHECK */
  109194. testcase( i==7 ); /* KEY */
  109195. testcase( i==8 ); /* BEFORE */
  109196. testcase( i==9 ); /* FOREIGN */
  109197. testcase( i==10 ); /* FOR */
  109198. testcase( i==11 ); /* IGNORE */
  109199. testcase( i==12 ); /* REGEXP */
  109200. testcase( i==13 ); /* EXPLAIN */
  109201. testcase( i==14 ); /* INSTEAD */
  109202. testcase( i==15 ); /* ADD */
  109203. testcase( i==16 ); /* DATABASE */
  109204. testcase( i==17 ); /* AS */
  109205. testcase( i==18 ); /* SELECT */
  109206. testcase( i==19 ); /* TABLE */
  109207. testcase( i==20 ); /* LEFT */
  109208. testcase( i==21 ); /* THEN */
  109209. testcase( i==22 ); /* END */
  109210. testcase( i==23 ); /* DEFERRABLE */
  109211. testcase( i==24 ); /* ELSE */
  109212. testcase( i==25 ); /* EXCEPT */
  109213. testcase( i==26 ); /* TRANSACTION */
  109214. testcase( i==27 ); /* ACTION */
  109215. testcase( i==28 ); /* ON */
  109216. testcase( i==29 ); /* NATURAL */
  109217. testcase( i==30 ); /* ALTER */
  109218. testcase( i==31 ); /* RAISE */
  109219. testcase( i==32 ); /* EXCLUSIVE */
  109220. testcase( i==33 ); /* EXISTS */
  109221. testcase( i==34 ); /* SAVEPOINT */
  109222. testcase( i==35 ); /* INTERSECT */
  109223. testcase( i==36 ); /* TRIGGER */
  109224. testcase( i==37 ); /* REFERENCES */
  109225. testcase( i==38 ); /* CONSTRAINT */
  109226. testcase( i==39 ); /* INTO */
  109227. testcase( i==40 ); /* OFFSET */
  109228. testcase( i==41 ); /* OF */
  109229. testcase( i==42 ); /* SET */
  109230. testcase( i==43 ); /* TEMPORARY */
  109231. testcase( i==44 ); /* TEMP */
  109232. testcase( i==45 ); /* OR */
  109233. testcase( i==46 ); /* UNIQUE */
  109234. testcase( i==47 ); /* QUERY */
  109235. testcase( i==48 ); /* ATTACH */
  109236. testcase( i==49 ); /* HAVING */
  109237. testcase( i==50 ); /* GROUP */
  109238. testcase( i==51 ); /* UPDATE */
  109239. testcase( i==52 ); /* BEGIN */
  109240. testcase( i==53 ); /* INNER */
  109241. testcase( i==54 ); /* RELEASE */
  109242. testcase( i==55 ); /* BETWEEN */
  109243. testcase( i==56 ); /* NOTNULL */
  109244. testcase( i==57 ); /* NOT */
  109245. testcase( i==58 ); /* NO */
  109246. testcase( i==59 ); /* NULL */
  109247. testcase( i==60 ); /* LIKE */
  109248. testcase( i==61 ); /* CASCADE */
  109249. testcase( i==62 ); /* ASC */
  109250. testcase( i==63 ); /* DELETE */
  109251. testcase( i==64 ); /* CASE */
  109252. testcase( i==65 ); /* COLLATE */
  109253. testcase( i==66 ); /* CREATE */
  109254. testcase( i==67 ); /* CURRENT_DATE */
  109255. testcase( i==68 ); /* DETACH */
  109256. testcase( i==69 ); /* IMMEDIATE */
  109257. testcase( i==70 ); /* JOIN */
  109258. testcase( i==71 ); /* INSERT */
  109259. testcase( i==72 ); /* MATCH */
  109260. testcase( i==73 ); /* PLAN */
  109261. testcase( i==74 ); /* ANALYZE */
  109262. testcase( i==75 ); /* PRAGMA */
  109263. testcase( i==76 ); /* ABORT */
  109264. testcase( i==77 ); /* VALUES */
  109265. testcase( i==78 ); /* VIRTUAL */
  109266. testcase( i==79 ); /* LIMIT */
  109267. testcase( i==80 ); /* WHEN */
  109268. testcase( i==81 ); /* WHERE */
  109269. testcase( i==82 ); /* RENAME */
  109270. testcase( i==83 ); /* AFTER */
  109271. testcase( i==84 ); /* REPLACE */
  109272. testcase( i==85 ); /* AND */
  109273. testcase( i==86 ); /* DEFAULT */
  109274. testcase( i==87 ); /* AUTOINCREMENT */
  109275. testcase( i==88 ); /* TO */
  109276. testcase( i==89 ); /* IN */
  109277. testcase( i==90 ); /* CAST */
  109278. testcase( i==91 ); /* COLUMN */
  109279. testcase( i==92 ); /* COMMIT */
  109280. testcase( i==93 ); /* CONFLICT */
  109281. testcase( i==94 ); /* CROSS */
  109282. testcase( i==95 ); /* CURRENT_TIMESTAMP */
  109283. testcase( i==96 ); /* CURRENT_TIME */
  109284. testcase( i==97 ); /* PRIMARY */
  109285. testcase( i==98 ); /* DEFERRED */
  109286. testcase( i==99 ); /* DISTINCT */
  109287. testcase( i==100 ); /* IS */
  109288. testcase( i==101 ); /* DROP */
  109289. testcase( i==102 ); /* FAIL */
  109290. testcase( i==103 ); /* FROM */
  109291. testcase( i==104 ); /* FULL */
  109292. testcase( i==105 ); /* GLOB */
  109293. testcase( i==106 ); /* BY */
  109294. testcase( i==107 ); /* IF */
  109295. testcase( i==108 ); /* ISNULL */
  109296. testcase( i==109 ); /* ORDER */
  109297. testcase( i==110 ); /* RESTRICT */
  109298. testcase( i==111 ); /* OUTER */
  109299. testcase( i==112 ); /* RIGHT */
  109300. testcase( i==113 ); /* ROLLBACK */
  109301. testcase( i==114 ); /* ROW */
  109302. testcase( i==115 ); /* UNION */
  109303. testcase( i==116 ); /* USING */
  109304. testcase( i==117 ); /* VACUUM */
  109305. testcase( i==118 ); /* VIEW */
  109306. testcase( i==119 ); /* INITIALLY */
  109307. testcase( i==120 ); /* ALL */
  109308. return aCode[i];
  109309. }
  109310. }
  109311. return TK_ID;
  109312. }
  109313. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  109314. return keywordCode((char*)z, n);
  109315. }
  109316. #define SQLITE_N_KEYWORD 121
  109317. /************** End of keywordhash.h *****************************************/
  109318. /************** Continuing where we left off in tokenize.c *******************/
  109319. /*
  109320. ** If X is a character that can be used in an identifier then
  109321. ** IdChar(X) will be true. Otherwise it is false.
  109322. **
  109323. ** For ASCII, any character with the high-order bit set is
  109324. ** allowed in an identifier. For 7-bit characters,
  109325. ** sqlite3IsIdChar[X] must be 1.
  109326. **
  109327. ** For EBCDIC, the rules are more complex but have the same
  109328. ** end result.
  109329. **
  109330. ** Ticket #1066. the SQL standard does not allow '$' in the
  109331. ** middle of identfiers. But many SQL implementations do.
  109332. ** SQLite will allow '$' in identifiers for compatibility.
  109333. ** But the feature is undocumented.
  109334. */
  109335. #ifdef SQLITE_ASCII
  109336. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  109337. #endif
  109338. #ifdef SQLITE_EBCDIC
  109339. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  109340. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  109341. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  109342. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  109343. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  109344. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  109345. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  109346. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  109347. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  109348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  109349. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  109350. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  109351. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  109352. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  109353. };
  109354. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  109355. #endif
  109356. /*
  109357. ** Return the length of the token that begins at z[0].
  109358. ** Store the token type in *tokenType before returning.
  109359. */
  109360. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  109361. int i, c;
  109362. switch( *z ){
  109363. case ' ': case '\t': case '\n': case '\f': case '\r': {
  109364. testcase( z[0]==' ' );
  109365. testcase( z[0]=='\t' );
  109366. testcase( z[0]=='\n' );
  109367. testcase( z[0]=='\f' );
  109368. testcase( z[0]=='\r' );
  109369. for(i=1; sqlite3Isspace(z[i]); i++){}
  109370. *tokenType = TK_SPACE;
  109371. return i;
  109372. }
  109373. case '-': {
  109374. if( z[1]=='-' ){
  109375. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  109376. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  109377. return i;
  109378. }
  109379. *tokenType = TK_MINUS;
  109380. return 1;
  109381. }
  109382. case '(': {
  109383. *tokenType = TK_LP;
  109384. return 1;
  109385. }
  109386. case ')': {
  109387. *tokenType = TK_RP;
  109388. return 1;
  109389. }
  109390. case ';': {
  109391. *tokenType = TK_SEMI;
  109392. return 1;
  109393. }
  109394. case '+': {
  109395. *tokenType = TK_PLUS;
  109396. return 1;
  109397. }
  109398. case '*': {
  109399. *tokenType = TK_STAR;
  109400. return 1;
  109401. }
  109402. case '/': {
  109403. if( z[1]!='*' || z[2]==0 ){
  109404. *tokenType = TK_SLASH;
  109405. return 1;
  109406. }
  109407. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  109408. if( c ) i++;
  109409. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  109410. return i;
  109411. }
  109412. case '%': {
  109413. *tokenType = TK_REM;
  109414. return 1;
  109415. }
  109416. case '=': {
  109417. *tokenType = TK_EQ;
  109418. return 1 + (z[1]=='=');
  109419. }
  109420. case '<': {
  109421. if( (c=z[1])=='=' ){
  109422. *tokenType = TK_LE;
  109423. return 2;
  109424. }else if( c=='>' ){
  109425. *tokenType = TK_NE;
  109426. return 2;
  109427. }else if( c=='<' ){
  109428. *tokenType = TK_LSHIFT;
  109429. return 2;
  109430. }else{
  109431. *tokenType = TK_LT;
  109432. return 1;
  109433. }
  109434. }
  109435. case '>': {
  109436. if( (c=z[1])=='=' ){
  109437. *tokenType = TK_GE;
  109438. return 2;
  109439. }else if( c=='>' ){
  109440. *tokenType = TK_RSHIFT;
  109441. return 2;
  109442. }else{
  109443. *tokenType = TK_GT;
  109444. return 1;
  109445. }
  109446. }
  109447. case '!': {
  109448. if( z[1]!='=' ){
  109449. *tokenType = TK_ILLEGAL;
  109450. return 2;
  109451. }else{
  109452. *tokenType = TK_NE;
  109453. return 2;
  109454. }
  109455. }
  109456. case '|': {
  109457. if( z[1]!='|' ){
  109458. *tokenType = TK_BITOR;
  109459. return 1;
  109460. }else{
  109461. *tokenType = TK_CONCAT;
  109462. return 2;
  109463. }
  109464. }
  109465. case ',': {
  109466. *tokenType = TK_COMMA;
  109467. return 1;
  109468. }
  109469. case '&': {
  109470. *tokenType = TK_BITAND;
  109471. return 1;
  109472. }
  109473. case '~': {
  109474. *tokenType = TK_BITNOT;
  109475. return 1;
  109476. }
  109477. case '`':
  109478. case '\'':
  109479. case '"': {
  109480. int delim = z[0];
  109481. testcase( delim=='`' );
  109482. testcase( delim=='\'' );
  109483. testcase( delim=='"' );
  109484. for(i=1; (c=z[i])!=0; i++){
  109485. if( c==delim ){
  109486. if( z[i+1]==delim ){
  109487. i++;
  109488. }else{
  109489. break;
  109490. }
  109491. }
  109492. }
  109493. if( c=='\'' ){
  109494. *tokenType = TK_STRING;
  109495. return i+1;
  109496. }else if( c!=0 ){
  109497. *tokenType = TK_ID;
  109498. return i+1;
  109499. }else{
  109500. *tokenType = TK_ILLEGAL;
  109501. return i;
  109502. }
  109503. }
  109504. case '.': {
  109505. #ifndef SQLITE_OMIT_FLOATING_POINT
  109506. if( !sqlite3Isdigit(z[1]) )
  109507. #endif
  109508. {
  109509. *tokenType = TK_DOT;
  109510. return 1;
  109511. }
  109512. /* If the next character is a digit, this is a floating point
  109513. ** number that begins with ".". Fall thru into the next case */
  109514. }
  109515. case '0': case '1': case '2': case '3': case '4':
  109516. case '5': case '6': case '7': case '8': case '9': {
  109517. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  109518. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  109519. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  109520. testcase( z[0]=='9' );
  109521. *tokenType = TK_INTEGER;
  109522. for(i=0; sqlite3Isdigit(z[i]); i++){}
  109523. #ifndef SQLITE_OMIT_FLOATING_POINT
  109524. if( z[i]=='.' ){
  109525. i++;
  109526. while( sqlite3Isdigit(z[i]) ){ i++; }
  109527. *tokenType = TK_FLOAT;
  109528. }
  109529. if( (z[i]=='e' || z[i]=='E') &&
  109530. ( sqlite3Isdigit(z[i+1])
  109531. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  109532. )
  109533. ){
  109534. i += 2;
  109535. while( sqlite3Isdigit(z[i]) ){ i++; }
  109536. *tokenType = TK_FLOAT;
  109537. }
  109538. #endif
  109539. while( IdChar(z[i]) ){
  109540. *tokenType = TK_ILLEGAL;
  109541. i++;
  109542. }
  109543. return i;
  109544. }
  109545. case '[': {
  109546. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  109547. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  109548. return i;
  109549. }
  109550. case '?': {
  109551. *tokenType = TK_VARIABLE;
  109552. for(i=1; sqlite3Isdigit(z[i]); i++){}
  109553. return i;
  109554. }
  109555. case '#': {
  109556. for(i=1; sqlite3Isdigit(z[i]); i++){}
  109557. if( i>1 ){
  109558. /* Parameters of the form #NNN (where NNN is a number) are used
  109559. ** internally by sqlite3NestedParse. */
  109560. *tokenType = TK_REGISTER;
  109561. return i;
  109562. }
  109563. /* Fall through into the next case if the '#' is not followed by
  109564. ** a digit. Try to match #AAAA where AAAA is a parameter name. */
  109565. }
  109566. #ifndef SQLITE_OMIT_TCL_VARIABLE
  109567. case '$':
  109568. #endif
  109569. case '@': /* For compatibility with MS SQL Server */
  109570. case ':': {
  109571. int n = 0;
  109572. testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
  109573. *tokenType = TK_VARIABLE;
  109574. for(i=1; (c=z[i])!=0; i++){
  109575. if( IdChar(c) ){
  109576. n++;
  109577. #ifndef SQLITE_OMIT_TCL_VARIABLE
  109578. }else if( c=='(' && n>0 ){
  109579. do{
  109580. i++;
  109581. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  109582. if( c==')' ){
  109583. i++;
  109584. }else{
  109585. *tokenType = TK_ILLEGAL;
  109586. }
  109587. break;
  109588. }else if( c==':' && z[i+1]==':' ){
  109589. i++;
  109590. #endif
  109591. }else{
  109592. break;
  109593. }
  109594. }
  109595. if( n==0 ) *tokenType = TK_ILLEGAL;
  109596. return i;
  109597. }
  109598. #ifndef SQLITE_OMIT_BLOB_LITERAL
  109599. case 'x': case 'X': {
  109600. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  109601. if( z[1]=='\'' ){
  109602. *tokenType = TK_BLOB;
  109603. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  109604. if( z[i]!='\'' || i%2 ){
  109605. *tokenType = TK_ILLEGAL;
  109606. while( z[i] && z[i]!='\'' ){ i++; }
  109607. }
  109608. if( z[i] ) i++;
  109609. return i;
  109610. }
  109611. /* Otherwise fall through to the next case */
  109612. }
  109613. #endif
  109614. default: {
  109615. if( !IdChar(*z) ){
  109616. break;
  109617. }
  109618. for(i=1; IdChar(z[i]); i++){}
  109619. *tokenType = keywordCode((char*)z, i);
  109620. return i;
  109621. }
  109622. }
  109623. *tokenType = TK_ILLEGAL;
  109624. return 1;
  109625. }
  109626. /*
  109627. ** Run the parser on the given SQL string. The parser structure is
  109628. ** passed in. An SQLITE_ status code is returned. If an error occurs
  109629. ** then an and attempt is made to write an error message into
  109630. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  109631. ** error message.
  109632. */
  109633. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  109634. int nErr = 0; /* Number of errors encountered */
  109635. int i; /* Loop counter */
  109636. void *pEngine; /* The LEMON-generated LALR(1) parser */
  109637. int tokenType; /* type of the next token */
  109638. int lastTokenParsed = -1; /* type of the previous token */
  109639. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  109640. sqlite3 *db = pParse->db; /* The database connection */
  109641. int mxSqlLen; /* Max length of an SQL string */
  109642. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  109643. if( db->nVdbeActive==0 ){
  109644. db->u1.isInterrupted = 0;
  109645. }
  109646. pParse->rc = SQLITE_OK;
  109647. pParse->zTail = zSql;
  109648. i = 0;
  109649. assert( pzErrMsg!=0 );
  109650. pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
  109651. if( pEngine==0 ){
  109652. db->mallocFailed = 1;
  109653. return SQLITE_NOMEM;
  109654. }
  109655. assert( pParse->pNewTable==0 );
  109656. assert( pParse->pNewTrigger==0 );
  109657. assert( pParse->nVar==0 );
  109658. assert( pParse->nzVar==0 );
  109659. assert( pParse->azVar==0 );
  109660. enableLookaside = db->lookaside.bEnabled;
  109661. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  109662. while( !db->mallocFailed && zSql[i]!=0 ){
  109663. assert( i>=0 );
  109664. pParse->sLastToken.z = &zSql[i];
  109665. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  109666. i += pParse->sLastToken.n;
  109667. if( i>mxSqlLen ){
  109668. pParse->rc = SQLITE_TOOBIG;
  109669. break;
  109670. }
  109671. switch( tokenType ){
  109672. case TK_SPACE: {
  109673. if( db->u1.isInterrupted ){
  109674. sqlite3ErrorMsg(pParse, "interrupt");
  109675. pParse->rc = SQLITE_INTERRUPT;
  109676. goto abort_parse;
  109677. }
  109678. break;
  109679. }
  109680. case TK_ILLEGAL: {
  109681. sqlite3DbFree(db, *pzErrMsg);
  109682. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  109683. &pParse->sLastToken);
  109684. nErr++;
  109685. goto abort_parse;
  109686. }
  109687. case TK_SEMI: {
  109688. pParse->zTail = &zSql[i];
  109689. /* Fall thru into the default case */
  109690. }
  109691. default: {
  109692. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  109693. lastTokenParsed = tokenType;
  109694. if( pParse->rc!=SQLITE_OK ){
  109695. goto abort_parse;
  109696. }
  109697. break;
  109698. }
  109699. }
  109700. }
  109701. abort_parse:
  109702. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  109703. if( lastTokenParsed!=TK_SEMI ){
  109704. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  109705. pParse->zTail = &zSql[i];
  109706. }
  109707. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  109708. }
  109709. #ifdef YYTRACKMAXSTACKDEPTH
  109710. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  109711. sqlite3ParserStackPeak(pEngine)
  109712. );
  109713. #endif /* YYDEBUG */
  109714. sqlite3ParserFree(pEngine, sqlite3_free);
  109715. db->lookaside.bEnabled = enableLookaside;
  109716. if( db->mallocFailed ){
  109717. pParse->rc = SQLITE_NOMEM;
  109718. }
  109719. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  109720. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  109721. }
  109722. assert( pzErrMsg!=0 );
  109723. if( pParse->zErrMsg ){
  109724. *pzErrMsg = pParse->zErrMsg;
  109725. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  109726. pParse->zErrMsg = 0;
  109727. nErr++;
  109728. }
  109729. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  109730. sqlite3VdbeDelete(pParse->pVdbe);
  109731. pParse->pVdbe = 0;
  109732. }
  109733. #ifndef SQLITE_OMIT_SHARED_CACHE
  109734. if( pParse->nested==0 ){
  109735. sqlite3DbFree(db, pParse->aTableLock);
  109736. pParse->aTableLock = 0;
  109737. pParse->nTableLock = 0;
  109738. }
  109739. #endif
  109740. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109741. sqlite3_free(pParse->apVtabLock);
  109742. #endif
  109743. if( !IN_DECLARE_VTAB ){
  109744. /* If the pParse->declareVtab flag is set, do not delete any table
  109745. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  109746. ** will take responsibility for freeing the Table structure.
  109747. */
  109748. sqlite3DeleteTable(db, pParse->pNewTable);
  109749. }
  109750. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  109751. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  109752. sqlite3DbFree(db, pParse->azVar);
  109753. sqlite3DbFree(db, pParse->aAlias);
  109754. while( pParse->pAinc ){
  109755. AutoincInfo *p = pParse->pAinc;
  109756. pParse->pAinc = p->pNext;
  109757. sqlite3DbFree(db, p);
  109758. }
  109759. while( pParse->pZombieTab ){
  109760. Table *p = pParse->pZombieTab;
  109761. pParse->pZombieTab = p->pNextZombie;
  109762. sqlite3DeleteTable(db, p);
  109763. }
  109764. if( nErr>0 && pParse->rc==SQLITE_OK ){
  109765. pParse->rc = SQLITE_ERROR;
  109766. }
  109767. return nErr;
  109768. }
  109769. /************** End of tokenize.c ********************************************/
  109770. /************** Begin file complete.c ****************************************/
  109771. /*
  109772. ** 2001 September 15
  109773. **
  109774. ** The author disclaims copyright to this source code. In place of
  109775. ** a legal notice, here is a blessing:
  109776. **
  109777. ** May you do good and not evil.
  109778. ** May you find forgiveness for yourself and forgive others.
  109779. ** May you share freely, never taking more than you give.
  109780. **
  109781. *************************************************************************
  109782. ** An tokenizer for SQL
  109783. **
  109784. ** This file contains C code that implements the sqlite3_complete() API.
  109785. ** This code used to be part of the tokenizer.c source file. But by
  109786. ** separating it out, the code will be automatically omitted from
  109787. ** static links that do not use it.
  109788. */
  109789. #ifndef SQLITE_OMIT_COMPLETE
  109790. /*
  109791. ** This is defined in tokenize.c. We just have to import the definition.
  109792. */
  109793. #ifndef SQLITE_AMALGAMATION
  109794. #ifdef SQLITE_ASCII
  109795. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  109796. #endif
  109797. #ifdef SQLITE_EBCDIC
  109798. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  109799. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  109800. #endif
  109801. #endif /* SQLITE_AMALGAMATION */
  109802. /*
  109803. ** Token types used by the sqlite3_complete() routine. See the header
  109804. ** comments on that procedure for additional information.
  109805. */
  109806. #define tkSEMI 0
  109807. #define tkWS 1
  109808. #define tkOTHER 2
  109809. #ifndef SQLITE_OMIT_TRIGGER
  109810. #define tkEXPLAIN 3
  109811. #define tkCREATE 4
  109812. #define tkTEMP 5
  109813. #define tkTRIGGER 6
  109814. #define tkEND 7
  109815. #endif
  109816. /*
  109817. ** Return TRUE if the given SQL string ends in a semicolon.
  109818. **
  109819. ** Special handling is require for CREATE TRIGGER statements.
  109820. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  109821. ** must end with ";END;".
  109822. **
  109823. ** This implementation uses a state machine with 8 states:
  109824. **
  109825. ** (0) INVALID We have not yet seen a non-whitespace character.
  109826. **
  109827. ** (1) START At the beginning or end of an SQL statement. This routine
  109828. ** returns 1 if it ends in the START state and 0 if it ends
  109829. ** in any other state.
  109830. **
  109831. ** (2) NORMAL We are in the middle of statement which ends with a single
  109832. ** semicolon.
  109833. **
  109834. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  109835. ** a statement.
  109836. **
  109837. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  109838. ** statement, possibly preceeded by EXPLAIN and/or followed by
  109839. ** TEMP or TEMPORARY
  109840. **
  109841. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  109842. ** ended by a semicolon, the keyword END, and another semicolon.
  109843. **
  109844. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  109845. ** the end of a trigger definition.
  109846. **
  109847. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  109848. ** of a trigger difinition.
  109849. **
  109850. ** Transitions between states above are determined by tokens extracted
  109851. ** from the input. The following tokens are significant:
  109852. **
  109853. ** (0) tkSEMI A semicolon.
  109854. ** (1) tkWS Whitespace.
  109855. ** (2) tkOTHER Any other SQL token.
  109856. ** (3) tkEXPLAIN The "explain" keyword.
  109857. ** (4) tkCREATE The "create" keyword.
  109858. ** (5) tkTEMP The "temp" or "temporary" keyword.
  109859. ** (6) tkTRIGGER The "trigger" keyword.
  109860. ** (7) tkEND The "end" keyword.
  109861. **
  109862. ** Whitespace never causes a state transition and is always ignored.
  109863. ** This means that a SQL string of all whitespace is invalid.
  109864. **
  109865. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  109866. ** to recognize the end of a trigger can be omitted. All we have to do
  109867. ** is look for a semicolon that is not part of an string or comment.
  109868. */
  109869. SQLITE_API int sqlite3_complete(const char *zSql){
  109870. u8 state = 0; /* Current state, using numbers defined in header comment */
  109871. u8 token; /* Value of the next token */
  109872. #ifndef SQLITE_OMIT_TRIGGER
  109873. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  109874. ** statement. This is the normal case.
  109875. */
  109876. static const u8 trans[8][8] = {
  109877. /* Token: */
  109878. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  109879. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  109880. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  109881. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  109882. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  109883. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  109884. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  109885. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  109886. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  109887. };
  109888. #else
  109889. /* If triggers are not supported by this compile then the statement machine
  109890. ** used to detect the end of a statement is much simplier
  109891. */
  109892. static const u8 trans[3][3] = {
  109893. /* Token: */
  109894. /* State: ** SEMI WS OTHER */
  109895. /* 0 INVALID: */ { 1, 0, 2, },
  109896. /* 1 START: */ { 1, 1, 2, },
  109897. /* 2 NORMAL: */ { 1, 2, 2, },
  109898. };
  109899. #endif /* SQLITE_OMIT_TRIGGER */
  109900. while( *zSql ){
  109901. switch( *zSql ){
  109902. case ';': { /* A semicolon */
  109903. token = tkSEMI;
  109904. break;
  109905. }
  109906. case ' ':
  109907. case '\r':
  109908. case '\t':
  109909. case '\n':
  109910. case '\f': { /* White space is ignored */
  109911. token = tkWS;
  109912. break;
  109913. }
  109914. case '/': { /* C-style comments */
  109915. if( zSql[1]!='*' ){
  109916. token = tkOTHER;
  109917. break;
  109918. }
  109919. zSql += 2;
  109920. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  109921. if( zSql[0]==0 ) return 0;
  109922. zSql++;
  109923. token = tkWS;
  109924. break;
  109925. }
  109926. case '-': { /* SQL-style comments from "--" to end of line */
  109927. if( zSql[1]!='-' ){
  109928. token = tkOTHER;
  109929. break;
  109930. }
  109931. while( *zSql && *zSql!='\n' ){ zSql++; }
  109932. if( *zSql==0 ) return state==1;
  109933. token = tkWS;
  109934. break;
  109935. }
  109936. case '[': { /* Microsoft-style identifiers in [...] */
  109937. zSql++;
  109938. while( *zSql && *zSql!=']' ){ zSql++; }
  109939. if( *zSql==0 ) return 0;
  109940. token = tkOTHER;
  109941. break;
  109942. }
  109943. case '`': /* Grave-accent quoted symbols used by MySQL */
  109944. case '"': /* single- and double-quoted strings */
  109945. case '\'': {
  109946. int c = *zSql;
  109947. zSql++;
  109948. while( *zSql && *zSql!=c ){ zSql++; }
  109949. if( *zSql==0 ) return 0;
  109950. token = tkOTHER;
  109951. break;
  109952. }
  109953. default: {
  109954. #ifdef SQLITE_EBCDIC
  109955. unsigned char c;
  109956. #endif
  109957. if( IdChar((u8)*zSql) ){
  109958. /* Keywords and unquoted identifiers */
  109959. int nId;
  109960. for(nId=1; IdChar(zSql[nId]); nId++){}
  109961. #ifdef SQLITE_OMIT_TRIGGER
  109962. token = tkOTHER;
  109963. #else
  109964. switch( *zSql ){
  109965. case 'c': case 'C': {
  109966. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  109967. token = tkCREATE;
  109968. }else{
  109969. token = tkOTHER;
  109970. }
  109971. break;
  109972. }
  109973. case 't': case 'T': {
  109974. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  109975. token = tkTRIGGER;
  109976. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  109977. token = tkTEMP;
  109978. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  109979. token = tkTEMP;
  109980. }else{
  109981. token = tkOTHER;
  109982. }
  109983. break;
  109984. }
  109985. case 'e': case 'E': {
  109986. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  109987. token = tkEND;
  109988. }else
  109989. #ifndef SQLITE_OMIT_EXPLAIN
  109990. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  109991. token = tkEXPLAIN;
  109992. }else
  109993. #endif
  109994. {
  109995. token = tkOTHER;
  109996. }
  109997. break;
  109998. }
  109999. default: {
  110000. token = tkOTHER;
  110001. break;
  110002. }
  110003. }
  110004. #endif /* SQLITE_OMIT_TRIGGER */
  110005. zSql += nId-1;
  110006. }else{
  110007. /* Operators and special symbols */
  110008. token = tkOTHER;
  110009. }
  110010. break;
  110011. }
  110012. }
  110013. state = trans[state][token];
  110014. zSql++;
  110015. }
  110016. return state==1;
  110017. }
  110018. #ifndef SQLITE_OMIT_UTF16
  110019. /*
  110020. ** This routine is the same as the sqlite3_complete() routine described
  110021. ** above, except that the parameter is required to be UTF-16 encoded, not
  110022. ** UTF-8.
  110023. */
  110024. SQLITE_API int sqlite3_complete16(const void *zSql){
  110025. sqlite3_value *pVal;
  110026. char const *zSql8;
  110027. int rc = SQLITE_NOMEM;
  110028. #ifndef SQLITE_OMIT_AUTOINIT
  110029. rc = sqlite3_initialize();
  110030. if( rc ) return rc;
  110031. #endif
  110032. pVal = sqlite3ValueNew(0);
  110033. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  110034. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  110035. if( zSql8 ){
  110036. rc = sqlite3_complete(zSql8);
  110037. }else{
  110038. rc = SQLITE_NOMEM;
  110039. }
  110040. sqlite3ValueFree(pVal);
  110041. return sqlite3ApiExit(0, rc);
  110042. }
  110043. #endif /* SQLITE_OMIT_UTF16 */
  110044. #endif /* SQLITE_OMIT_COMPLETE */
  110045. /************** End of complete.c ********************************************/
  110046. /************** Begin file main.c ********************************************/
  110047. /*
  110048. ** 2001 September 15
  110049. **
  110050. ** The author disclaims copyright to this source code. In place of
  110051. ** a legal notice, here is a blessing:
  110052. **
  110053. ** May you do good and not evil.
  110054. ** May you find forgiveness for yourself and forgive others.
  110055. ** May you share freely, never taking more than you give.
  110056. **
  110057. *************************************************************************
  110058. ** Main file for the SQLite library. The routines in this file
  110059. ** implement the programmer interface to the library. Routines in
  110060. ** other files are for internal use by SQLite and should not be
  110061. ** accessed by users of the library.
  110062. */
  110063. #ifdef SQLITE_ENABLE_FTS3
  110064. /************** Include fts3.h in the middle of main.c ***********************/
  110065. /************** Begin file fts3.h ********************************************/
  110066. /*
  110067. ** 2006 Oct 10
  110068. **
  110069. ** The author disclaims copyright to this source code. In place of
  110070. ** a legal notice, here is a blessing:
  110071. **
  110072. ** May you do good and not evil.
  110073. ** May you find forgiveness for yourself and forgive others.
  110074. ** May you share freely, never taking more than you give.
  110075. **
  110076. ******************************************************************************
  110077. **
  110078. ** This header file is used by programs that want to link against the
  110079. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  110080. */
  110081. #if 0
  110082. extern "C" {
  110083. #endif /* __cplusplus */
  110084. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  110085. #if 0
  110086. } /* extern "C" */
  110087. #endif /* __cplusplus */
  110088. /************** End of fts3.h ************************************************/
  110089. /************** Continuing where we left off in main.c ***********************/
  110090. #endif
  110091. #ifdef SQLITE_ENABLE_RTREE
  110092. /************** Include rtree.h in the middle of main.c **********************/
  110093. /************** Begin file rtree.h *******************************************/
  110094. /*
  110095. ** 2008 May 26
  110096. **
  110097. ** The author disclaims copyright to this source code. In place of
  110098. ** a legal notice, here is a blessing:
  110099. **
  110100. ** May you do good and not evil.
  110101. ** May you find forgiveness for yourself and forgive others.
  110102. ** May you share freely, never taking more than you give.
  110103. **
  110104. ******************************************************************************
  110105. **
  110106. ** This header file is used by programs that want to link against the
  110107. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  110108. */
  110109. #if 0
  110110. extern "C" {
  110111. #endif /* __cplusplus */
  110112. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  110113. #if 0
  110114. } /* extern "C" */
  110115. #endif /* __cplusplus */
  110116. /************** End of rtree.h ***********************************************/
  110117. /************** Continuing where we left off in main.c ***********************/
  110118. #endif
  110119. #ifdef SQLITE_ENABLE_ICU
  110120. /************** Include sqliteicu.h in the middle of main.c ******************/
  110121. /************** Begin file sqliteicu.h ***************************************/
  110122. /*
  110123. ** 2008 May 26
  110124. **
  110125. ** The author disclaims copyright to this source code. In place of
  110126. ** a legal notice, here is a blessing:
  110127. **
  110128. ** May you do good and not evil.
  110129. ** May you find forgiveness for yourself and forgive others.
  110130. ** May you share freely, never taking more than you give.
  110131. **
  110132. ******************************************************************************
  110133. **
  110134. ** This header file is used by programs that want to link against the
  110135. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  110136. */
  110137. #if 0
  110138. extern "C" {
  110139. #endif /* __cplusplus */
  110140. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  110141. #if 0
  110142. } /* extern "C" */
  110143. #endif /* __cplusplus */
  110144. /************** End of sqliteicu.h *******************************************/
  110145. /************** Continuing where we left off in main.c ***********************/
  110146. #endif
  110147. #ifndef SQLITE_AMALGAMATION
  110148. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  110149. ** contains the text of SQLITE_VERSION macro.
  110150. */
  110151. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  110152. #endif
  110153. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  110154. ** a pointer to the to the sqlite3_version[] string constant.
  110155. */
  110156. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  110157. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  110158. ** pointer to a string constant whose value is the same as the
  110159. ** SQLITE_SOURCE_ID C preprocessor macro.
  110160. */
  110161. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  110162. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  110163. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  110164. */
  110165. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  110166. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  110167. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  110168. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  110169. */
  110170. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  110171. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  110172. /*
  110173. ** If the following function pointer is not NULL and if
  110174. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  110175. ** I/O active are written using this function. These messages
  110176. ** are intended for debugging activity only.
  110177. */
  110178. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  110179. #endif
  110180. /*
  110181. ** If the following global variable points to a string which is the
  110182. ** name of a directory, then that directory will be used to store
  110183. ** temporary files.
  110184. **
  110185. ** See also the "PRAGMA temp_store_directory" SQL command.
  110186. */
  110187. SQLITE_API char *sqlite3_temp_directory = 0;
  110188. /*
  110189. ** If the following global variable points to a string which is the
  110190. ** name of a directory, then that directory will be used to store
  110191. ** all database files specified with a relative pathname.
  110192. **
  110193. ** See also the "PRAGMA data_store_directory" SQL command.
  110194. */
  110195. SQLITE_API char *sqlite3_data_directory = 0;
  110196. /*
  110197. ** Initialize SQLite.
  110198. **
  110199. ** This routine must be called to initialize the memory allocation,
  110200. ** VFS, and mutex subsystems prior to doing any serious work with
  110201. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  110202. ** this routine will be called automatically by key routines such as
  110203. ** sqlite3_open().
  110204. **
  110205. ** This routine is a no-op except on its very first call for the process,
  110206. ** or for the first call after a call to sqlite3_shutdown.
  110207. **
  110208. ** The first thread to call this routine runs the initialization to
  110209. ** completion. If subsequent threads call this routine before the first
  110210. ** thread has finished the initialization process, then the subsequent
  110211. ** threads must block until the first thread finishes with the initialization.
  110212. **
  110213. ** The first thread might call this routine recursively. Recursive
  110214. ** calls to this routine should not block, of course. Otherwise the
  110215. ** initialization process would never complete.
  110216. **
  110217. ** Let X be the first thread to enter this routine. Let Y be some other
  110218. ** thread. Then while the initial invocation of this routine by X is
  110219. ** incomplete, it is required that:
  110220. **
  110221. ** * Calls to this routine from Y must block until the outer-most
  110222. ** call by X completes.
  110223. **
  110224. ** * Recursive calls to this routine from thread X return immediately
  110225. ** without blocking.
  110226. */
  110227. SQLITE_API int sqlite3_initialize(void){
  110228. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  110229. int rc; /* Result code */
  110230. #ifdef SQLITE_EXTRA_INIT
  110231. int bRunExtraInit = 0; /* Extra initialization needed */
  110232. #endif
  110233. #ifdef SQLITE_OMIT_WSD
  110234. rc = sqlite3_wsd_init(4096, 24);
  110235. if( rc!=SQLITE_OK ){
  110236. return rc;
  110237. }
  110238. #endif
  110239. /* If SQLite is already completely initialized, then this call
  110240. ** to sqlite3_initialize() should be a no-op. But the initialization
  110241. ** must be complete. So isInit must not be set until the very end
  110242. ** of this routine.
  110243. */
  110244. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  110245. #ifdef SQLITE_ENABLE_SQLLOG
  110246. {
  110247. extern void sqlite3_init_sqllog(void);
  110248. sqlite3_init_sqllog();
  110249. }
  110250. #endif
  110251. /* Make sure the mutex subsystem is initialized. If unable to
  110252. ** initialize the mutex subsystem, return early with the error.
  110253. ** If the system is so sick that we are unable to allocate a mutex,
  110254. ** there is not much SQLite is going to be able to do.
  110255. **
  110256. ** The mutex subsystem must take care of serializing its own
  110257. ** initialization.
  110258. */
  110259. rc = sqlite3MutexInit();
  110260. if( rc ) return rc;
  110261. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  110262. ** This operation is protected by the STATIC_MASTER mutex. Note that
  110263. ** MutexAlloc() is called for a static mutex prior to initializing the
  110264. ** malloc subsystem - this implies that the allocation of a static
  110265. ** mutex must not require support from the malloc subsystem.
  110266. */
  110267. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  110268. sqlite3_mutex_enter(pMaster);
  110269. sqlite3GlobalConfig.isMutexInit = 1;
  110270. if( !sqlite3GlobalConfig.isMallocInit ){
  110271. rc = sqlite3MallocInit();
  110272. }
  110273. if( rc==SQLITE_OK ){
  110274. sqlite3GlobalConfig.isMallocInit = 1;
  110275. if( !sqlite3GlobalConfig.pInitMutex ){
  110276. sqlite3GlobalConfig.pInitMutex =
  110277. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  110278. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  110279. rc = SQLITE_NOMEM;
  110280. }
  110281. }
  110282. }
  110283. if( rc==SQLITE_OK ){
  110284. sqlite3GlobalConfig.nRefInitMutex++;
  110285. }
  110286. sqlite3_mutex_leave(pMaster);
  110287. /* If rc is not SQLITE_OK at this point, then either the malloc
  110288. ** subsystem could not be initialized or the system failed to allocate
  110289. ** the pInitMutex mutex. Return an error in either case. */
  110290. if( rc!=SQLITE_OK ){
  110291. return rc;
  110292. }
  110293. /* Do the rest of the initialization under the recursive mutex so
  110294. ** that we will be able to handle recursive calls into
  110295. ** sqlite3_initialize(). The recursive calls normally come through
  110296. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  110297. ** recursive calls might also be possible.
  110298. **
  110299. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  110300. ** to the xInit method, so the xInit method need not be threadsafe.
  110301. **
  110302. ** The following mutex is what serializes access to the appdef pcache xInit
  110303. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  110304. ** call to sqlite3PcacheInitialize().
  110305. */
  110306. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  110307. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  110308. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  110309. sqlite3GlobalConfig.inProgress = 1;
  110310. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  110311. sqlite3RegisterGlobalFunctions();
  110312. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  110313. rc = sqlite3PcacheInitialize();
  110314. }
  110315. if( rc==SQLITE_OK ){
  110316. sqlite3GlobalConfig.isPCacheInit = 1;
  110317. rc = sqlite3OsInit();
  110318. }
  110319. if( rc==SQLITE_OK ){
  110320. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  110321. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  110322. sqlite3GlobalConfig.isInit = 1;
  110323. #ifdef SQLITE_EXTRA_INIT
  110324. bRunExtraInit = 1;
  110325. #endif
  110326. }
  110327. sqlite3GlobalConfig.inProgress = 0;
  110328. }
  110329. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  110330. /* Go back under the static mutex and clean up the recursive
  110331. ** mutex to prevent a resource leak.
  110332. */
  110333. sqlite3_mutex_enter(pMaster);
  110334. sqlite3GlobalConfig.nRefInitMutex--;
  110335. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  110336. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  110337. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  110338. sqlite3GlobalConfig.pInitMutex = 0;
  110339. }
  110340. sqlite3_mutex_leave(pMaster);
  110341. /* The following is just a sanity check to make sure SQLite has
  110342. ** been compiled correctly. It is important to run this code, but
  110343. ** we don't want to run it too often and soak up CPU cycles for no
  110344. ** reason. So we run it once during initialization.
  110345. */
  110346. #ifndef NDEBUG
  110347. #ifndef SQLITE_OMIT_FLOATING_POINT
  110348. /* This section of code's only "output" is via assert() statements. */
  110349. if ( rc==SQLITE_OK ){
  110350. u64 x = (((u64)1)<<63)-1;
  110351. double y;
  110352. assert(sizeof(x)==8);
  110353. assert(sizeof(x)==sizeof(y));
  110354. memcpy(&y, &x, 8);
  110355. assert( sqlite3IsNaN(y) );
  110356. }
  110357. #endif
  110358. #endif
  110359. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  110360. ** compile-time option.
  110361. */
  110362. #ifdef SQLITE_EXTRA_INIT
  110363. if( bRunExtraInit ){
  110364. int SQLITE_EXTRA_INIT(const char*);
  110365. rc = SQLITE_EXTRA_INIT(0);
  110366. }
  110367. #endif
  110368. return rc;
  110369. }
  110370. /*
  110371. ** Undo the effects of sqlite3_initialize(). Must not be called while
  110372. ** there are outstanding database connections or memory allocations or
  110373. ** while any part of SQLite is otherwise in use in any thread. This
  110374. ** routine is not threadsafe. But it is safe to invoke this routine
  110375. ** on when SQLite is already shut down. If SQLite is already shut down
  110376. ** when this routine is invoked, then this routine is a harmless no-op.
  110377. */
  110378. SQLITE_API int sqlite3_shutdown(void){
  110379. if( sqlite3GlobalConfig.isInit ){
  110380. #ifdef SQLITE_EXTRA_SHUTDOWN
  110381. void SQLITE_EXTRA_SHUTDOWN(void);
  110382. SQLITE_EXTRA_SHUTDOWN();
  110383. #endif
  110384. sqlite3_os_end();
  110385. sqlite3_reset_auto_extension();
  110386. sqlite3GlobalConfig.isInit = 0;
  110387. }
  110388. if( sqlite3GlobalConfig.isPCacheInit ){
  110389. sqlite3PcacheShutdown();
  110390. sqlite3GlobalConfig.isPCacheInit = 0;
  110391. }
  110392. if( sqlite3GlobalConfig.isMallocInit ){
  110393. sqlite3MallocEnd();
  110394. sqlite3GlobalConfig.isMallocInit = 0;
  110395. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  110396. /* The heap subsystem has now been shutdown and these values are supposed
  110397. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  110398. ** which would rely on that heap subsystem; therefore, make sure these
  110399. ** values cannot refer to heap memory that was just invalidated when the
  110400. ** heap subsystem was shutdown. This is only done if the current call to
  110401. ** this function resulted in the heap subsystem actually being shutdown.
  110402. */
  110403. sqlite3_data_directory = 0;
  110404. sqlite3_temp_directory = 0;
  110405. #endif
  110406. }
  110407. if( sqlite3GlobalConfig.isMutexInit ){
  110408. sqlite3MutexEnd();
  110409. sqlite3GlobalConfig.isMutexInit = 0;
  110410. }
  110411. return SQLITE_OK;
  110412. }
  110413. /*
  110414. ** This API allows applications to modify the global configuration of
  110415. ** the SQLite library at run-time.
  110416. **
  110417. ** This routine should only be called when there are no outstanding
  110418. ** database connections or memory allocations. This routine is not
  110419. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  110420. ** behavior.
  110421. */
  110422. SQLITE_API int sqlite3_config(int op, ...){
  110423. va_list ap;
  110424. int rc = SQLITE_OK;
  110425. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  110426. ** the SQLite library is in use. */
  110427. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  110428. va_start(ap, op);
  110429. switch( op ){
  110430. /* Mutex configuration options are only available in a threadsafe
  110431. ** compile.
  110432. */
  110433. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  110434. case SQLITE_CONFIG_SINGLETHREAD: {
  110435. /* Disable all mutexing */
  110436. sqlite3GlobalConfig.bCoreMutex = 0;
  110437. sqlite3GlobalConfig.bFullMutex = 0;
  110438. break;
  110439. }
  110440. case SQLITE_CONFIG_MULTITHREAD: {
  110441. /* Disable mutexing of database connections */
  110442. /* Enable mutexing of core data structures */
  110443. sqlite3GlobalConfig.bCoreMutex = 1;
  110444. sqlite3GlobalConfig.bFullMutex = 0;
  110445. break;
  110446. }
  110447. case SQLITE_CONFIG_SERIALIZED: {
  110448. /* Enable all mutexing */
  110449. sqlite3GlobalConfig.bCoreMutex = 1;
  110450. sqlite3GlobalConfig.bFullMutex = 1;
  110451. break;
  110452. }
  110453. case SQLITE_CONFIG_MUTEX: {
  110454. /* Specify an alternative mutex implementation */
  110455. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  110456. break;
  110457. }
  110458. case SQLITE_CONFIG_GETMUTEX: {
  110459. /* Retrieve the current mutex implementation */
  110460. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  110461. break;
  110462. }
  110463. #endif
  110464. case SQLITE_CONFIG_MALLOC: {
  110465. /* Specify an alternative malloc implementation */
  110466. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  110467. break;
  110468. }
  110469. case SQLITE_CONFIG_GETMALLOC: {
  110470. /* Retrieve the current malloc() implementation */
  110471. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  110472. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  110473. break;
  110474. }
  110475. case SQLITE_CONFIG_MEMSTATUS: {
  110476. /* Enable or disable the malloc status collection */
  110477. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  110478. break;
  110479. }
  110480. case SQLITE_CONFIG_SCRATCH: {
  110481. /* Designate a buffer for scratch memory space */
  110482. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  110483. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  110484. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  110485. break;
  110486. }
  110487. case SQLITE_CONFIG_PAGECACHE: {
  110488. /* Designate a buffer for page cache memory space */
  110489. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  110490. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  110491. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  110492. break;
  110493. }
  110494. case SQLITE_CONFIG_PCACHE: {
  110495. /* no-op */
  110496. break;
  110497. }
  110498. case SQLITE_CONFIG_GETPCACHE: {
  110499. /* now an error */
  110500. rc = SQLITE_ERROR;
  110501. break;
  110502. }
  110503. case SQLITE_CONFIG_PCACHE2: {
  110504. /* Specify an alternative page cache implementation */
  110505. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  110506. break;
  110507. }
  110508. case SQLITE_CONFIG_GETPCACHE2: {
  110509. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  110510. sqlite3PCacheSetDefault();
  110511. }
  110512. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  110513. break;
  110514. }
  110515. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  110516. case SQLITE_CONFIG_HEAP: {
  110517. /* Designate a buffer for heap memory space */
  110518. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  110519. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  110520. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  110521. if( sqlite3GlobalConfig.mnReq<1 ){
  110522. sqlite3GlobalConfig.mnReq = 1;
  110523. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  110524. /* cap min request size at 2^12 */
  110525. sqlite3GlobalConfig.mnReq = (1<<12);
  110526. }
  110527. if( sqlite3GlobalConfig.pHeap==0 ){
  110528. /* If the heap pointer is NULL, then restore the malloc implementation
  110529. ** back to NULL pointers too. This will cause the malloc to go
  110530. ** back to its default implementation when sqlite3_initialize() is
  110531. ** run.
  110532. */
  110533. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  110534. }else{
  110535. /* The heap pointer is not NULL, then install one of the
  110536. ** mem5.c/mem3.c methods. The enclosing #if guarantees at
  110537. ** least one of these methods is currently enabled.
  110538. */
  110539. #ifdef SQLITE_ENABLE_MEMSYS3
  110540. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  110541. #endif
  110542. #ifdef SQLITE_ENABLE_MEMSYS5
  110543. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  110544. #endif
  110545. }
  110546. break;
  110547. }
  110548. #endif
  110549. case SQLITE_CONFIG_LOOKASIDE: {
  110550. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  110551. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  110552. break;
  110553. }
  110554. /* Record a pointer to the logger function and its first argument.
  110555. ** The default is NULL. Logging is disabled if the function pointer is
  110556. ** NULL.
  110557. */
  110558. case SQLITE_CONFIG_LOG: {
  110559. /* MSVC is picky about pulling func ptrs from va lists.
  110560. ** http://support.microsoft.com/kb/47961
  110561. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  110562. */
  110563. typedef void(*LOGFUNC_t)(void*,int,const char*);
  110564. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  110565. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  110566. break;
  110567. }
  110568. case SQLITE_CONFIG_URI: {
  110569. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  110570. break;
  110571. }
  110572. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  110573. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  110574. break;
  110575. }
  110576. #ifdef SQLITE_ENABLE_SQLLOG
  110577. case SQLITE_CONFIG_SQLLOG: {
  110578. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  110579. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  110580. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  110581. break;
  110582. }
  110583. #endif
  110584. case SQLITE_CONFIG_MMAP_SIZE: {
  110585. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  110586. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  110587. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  110588. mxMmap = SQLITE_MAX_MMAP_SIZE;
  110589. }
  110590. sqlite3GlobalConfig.mxMmap = mxMmap;
  110591. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  110592. if( szMmap>mxMmap) szMmap = mxMmap;
  110593. sqlite3GlobalConfig.szMmap = szMmap;
  110594. break;
  110595. }
  110596. default: {
  110597. rc = SQLITE_ERROR;
  110598. break;
  110599. }
  110600. }
  110601. va_end(ap);
  110602. return rc;
  110603. }
  110604. /*
  110605. ** Set up the lookaside buffers for a database connection.
  110606. ** Return SQLITE_OK on success.
  110607. ** If lookaside is already active, return SQLITE_BUSY.
  110608. **
  110609. ** The sz parameter is the number of bytes in each lookaside slot.
  110610. ** The cnt parameter is the number of slots. If pStart is NULL the
  110611. ** space for the lookaside memory is obtained from sqlite3_malloc().
  110612. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  110613. ** the lookaside memory.
  110614. */
  110615. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  110616. void *pStart;
  110617. if( db->lookaside.nOut ){
  110618. return SQLITE_BUSY;
  110619. }
  110620. /* Free any existing lookaside buffer for this handle before
  110621. ** allocating a new one so we don't have to have space for
  110622. ** both at the same time.
  110623. */
  110624. if( db->lookaside.bMalloced ){
  110625. sqlite3_free(db->lookaside.pStart);
  110626. }
  110627. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  110628. ** than a pointer to be useful.
  110629. */
  110630. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  110631. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  110632. if( cnt<0 ) cnt = 0;
  110633. if( sz==0 || cnt==0 ){
  110634. sz = 0;
  110635. pStart = 0;
  110636. }else if( pBuf==0 ){
  110637. sqlite3BeginBenignMalloc();
  110638. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  110639. sqlite3EndBenignMalloc();
  110640. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  110641. }else{
  110642. pStart = pBuf;
  110643. }
  110644. db->lookaside.pStart = pStart;
  110645. db->lookaside.pFree = 0;
  110646. db->lookaside.sz = (u16)sz;
  110647. if( pStart ){
  110648. int i;
  110649. LookasideSlot *p;
  110650. assert( sz > (int)sizeof(LookasideSlot*) );
  110651. p = (LookasideSlot*)pStart;
  110652. for(i=cnt-1; i>=0; i--){
  110653. p->pNext = db->lookaside.pFree;
  110654. db->lookaside.pFree = p;
  110655. p = (LookasideSlot*)&((u8*)p)[sz];
  110656. }
  110657. db->lookaside.pEnd = p;
  110658. db->lookaside.bEnabled = 1;
  110659. db->lookaside.bMalloced = pBuf==0 ?1:0;
  110660. }else{
  110661. db->lookaside.pEnd = 0;
  110662. db->lookaside.bEnabled = 0;
  110663. db->lookaside.bMalloced = 0;
  110664. }
  110665. return SQLITE_OK;
  110666. }
  110667. /*
  110668. ** Return the mutex associated with a database connection.
  110669. */
  110670. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  110671. return db->mutex;
  110672. }
  110673. /*
  110674. ** Free up as much memory as we can from the given database
  110675. ** connection.
  110676. */
  110677. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  110678. int i;
  110679. sqlite3_mutex_enter(db->mutex);
  110680. sqlite3BtreeEnterAll(db);
  110681. for(i=0; i<db->nDb; i++){
  110682. Btree *pBt = db->aDb[i].pBt;
  110683. if( pBt ){
  110684. Pager *pPager = sqlite3BtreePager(pBt);
  110685. sqlite3PagerShrink(pPager);
  110686. }
  110687. }
  110688. sqlite3BtreeLeaveAll(db);
  110689. sqlite3_mutex_leave(db->mutex);
  110690. return SQLITE_OK;
  110691. }
  110692. /*
  110693. ** Configuration settings for an individual database connection
  110694. */
  110695. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  110696. va_list ap;
  110697. int rc;
  110698. va_start(ap, op);
  110699. switch( op ){
  110700. case SQLITE_DBCONFIG_LOOKASIDE: {
  110701. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  110702. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  110703. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  110704. rc = setupLookaside(db, pBuf, sz, cnt);
  110705. break;
  110706. }
  110707. default: {
  110708. static const struct {
  110709. int op; /* The opcode */
  110710. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  110711. } aFlagOp[] = {
  110712. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  110713. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  110714. };
  110715. unsigned int i;
  110716. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  110717. for(i=0; i<ArraySize(aFlagOp); i++){
  110718. if( aFlagOp[i].op==op ){
  110719. int onoff = va_arg(ap, int);
  110720. int *pRes = va_arg(ap, int*);
  110721. int oldFlags = db->flags;
  110722. if( onoff>0 ){
  110723. db->flags |= aFlagOp[i].mask;
  110724. }else if( onoff==0 ){
  110725. db->flags &= ~aFlagOp[i].mask;
  110726. }
  110727. if( oldFlags!=db->flags ){
  110728. sqlite3ExpirePreparedStatements(db);
  110729. }
  110730. if( pRes ){
  110731. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  110732. }
  110733. rc = SQLITE_OK;
  110734. break;
  110735. }
  110736. }
  110737. break;
  110738. }
  110739. }
  110740. va_end(ap);
  110741. return rc;
  110742. }
  110743. /*
  110744. ** Return true if the buffer z[0..n-1] contains all spaces.
  110745. */
  110746. static int allSpaces(const char *z, int n){
  110747. while( n>0 && z[n-1]==' ' ){ n--; }
  110748. return n==0;
  110749. }
  110750. /*
  110751. ** This is the default collating function named "BINARY" which is always
  110752. ** available.
  110753. **
  110754. ** If the padFlag argument is not NULL then space padding at the end
  110755. ** of strings is ignored. This implements the RTRIM collation.
  110756. */
  110757. static int binCollFunc(
  110758. void *padFlag,
  110759. int nKey1, const void *pKey1,
  110760. int nKey2, const void *pKey2
  110761. ){
  110762. int rc, n;
  110763. n = nKey1<nKey2 ? nKey1 : nKey2;
  110764. rc = memcmp(pKey1, pKey2, n);
  110765. if( rc==0 ){
  110766. if( padFlag
  110767. && allSpaces(((char*)pKey1)+n, nKey1-n)
  110768. && allSpaces(((char*)pKey2)+n, nKey2-n)
  110769. ){
  110770. /* Leave rc unchanged at 0 */
  110771. }else{
  110772. rc = nKey1 - nKey2;
  110773. }
  110774. }
  110775. return rc;
  110776. }
  110777. /*
  110778. ** Another built-in collating sequence: NOCASE.
  110779. **
  110780. ** This collating sequence is intended to be used for "case independent
  110781. ** comparison". SQLite's knowledge of upper and lower case equivalents
  110782. ** extends only to the 26 characters used in the English language.
  110783. **
  110784. ** At the moment there is only a UTF-8 implementation.
  110785. */
  110786. static int nocaseCollatingFunc(
  110787. void *NotUsed,
  110788. int nKey1, const void *pKey1,
  110789. int nKey2, const void *pKey2
  110790. ){
  110791. int r = sqlite3StrNICmp(
  110792. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  110793. UNUSED_PARAMETER(NotUsed);
  110794. if( 0==r ){
  110795. r = nKey1-nKey2;
  110796. }
  110797. return r;
  110798. }
  110799. /*
  110800. ** Return the ROWID of the most recent insert
  110801. */
  110802. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  110803. return db->lastRowid;
  110804. }
  110805. /*
  110806. ** Return the number of changes in the most recent call to sqlite3_exec().
  110807. */
  110808. SQLITE_API int sqlite3_changes(sqlite3 *db){
  110809. return db->nChange;
  110810. }
  110811. /*
  110812. ** Return the number of changes since the database handle was opened.
  110813. */
  110814. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  110815. return db->nTotalChange;
  110816. }
  110817. /*
  110818. ** Close all open savepoints. This function only manipulates fields of the
  110819. ** database handle object, it does not close any savepoints that may be open
  110820. ** at the b-tree/pager level.
  110821. */
  110822. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  110823. while( db->pSavepoint ){
  110824. Savepoint *pTmp = db->pSavepoint;
  110825. db->pSavepoint = pTmp->pNext;
  110826. sqlite3DbFree(db, pTmp);
  110827. }
  110828. db->nSavepoint = 0;
  110829. db->nStatement = 0;
  110830. db->isTransactionSavepoint = 0;
  110831. }
  110832. /*
  110833. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  110834. ** if this is not the last copy of the function, do not invoke it. Multiple
  110835. ** copies of a single function are created when create_function() is called
  110836. ** with SQLITE_ANY as the encoding.
  110837. */
  110838. static void functionDestroy(sqlite3 *db, FuncDef *p){
  110839. FuncDestructor *pDestructor = p->pDestructor;
  110840. if( pDestructor ){
  110841. pDestructor->nRef--;
  110842. if( pDestructor->nRef==0 ){
  110843. pDestructor->xDestroy(pDestructor->pUserData);
  110844. sqlite3DbFree(db, pDestructor);
  110845. }
  110846. }
  110847. }
  110848. /*
  110849. ** Disconnect all sqlite3_vtab objects that belong to database connection
  110850. ** db. This is called when db is being closed.
  110851. */
  110852. static void disconnectAllVtab(sqlite3 *db){
  110853. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110854. int i;
  110855. sqlite3BtreeEnterAll(db);
  110856. for(i=0; i<db->nDb; i++){
  110857. Schema *pSchema = db->aDb[i].pSchema;
  110858. if( db->aDb[i].pSchema ){
  110859. HashElem *p;
  110860. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  110861. Table *pTab = (Table *)sqliteHashData(p);
  110862. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  110863. }
  110864. }
  110865. }
  110866. sqlite3BtreeLeaveAll(db);
  110867. #else
  110868. UNUSED_PARAMETER(db);
  110869. #endif
  110870. }
  110871. /*
  110872. ** Return TRUE if database connection db has unfinalized prepared
  110873. ** statements or unfinished sqlite3_backup objects.
  110874. */
  110875. static int connectionIsBusy(sqlite3 *db){
  110876. int j;
  110877. assert( sqlite3_mutex_held(db->mutex) );
  110878. if( db->pVdbe ) return 1;
  110879. for(j=0; j<db->nDb; j++){
  110880. Btree *pBt = db->aDb[j].pBt;
  110881. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  110882. }
  110883. return 0;
  110884. }
  110885. /*
  110886. ** Close an existing SQLite database
  110887. */
  110888. static int sqlite3Close(sqlite3 *db, int forceZombie){
  110889. if( !db ){
  110890. return SQLITE_OK;
  110891. }
  110892. if( !sqlite3SafetyCheckSickOrOk(db) ){
  110893. return SQLITE_MISUSE_BKPT;
  110894. }
  110895. sqlite3_mutex_enter(db->mutex);
  110896. /* Force xDisconnect calls on all virtual tables */
  110897. disconnectAllVtab(db);
  110898. /* If a transaction is open, the disconnectAllVtab() call above
  110899. ** will not have called the xDisconnect() method on any virtual
  110900. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  110901. ** call will do so. We need to do this before the check for active
  110902. ** SQL statements below, as the v-table implementation may be storing
  110903. ** some prepared statements internally.
  110904. */
  110905. sqlite3VtabRollback(db);
  110906. /* Legacy behavior (sqlite3_close() behavior) is to return
  110907. ** SQLITE_BUSY if the connection can not be closed immediately.
  110908. */
  110909. if( !forceZombie && connectionIsBusy(db) ){
  110910. sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
  110911. "statements or unfinished backups");
  110912. sqlite3_mutex_leave(db->mutex);
  110913. return SQLITE_BUSY;
  110914. }
  110915. #ifdef SQLITE_ENABLE_SQLLOG
  110916. if( sqlite3GlobalConfig.xSqllog ){
  110917. /* Closing the handle. Fourth parameter is passed the value 2. */
  110918. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  110919. }
  110920. #endif
  110921. /* Convert the connection into a zombie and then close it.
  110922. */
  110923. db->magic = SQLITE_MAGIC_ZOMBIE;
  110924. sqlite3LeaveMutexAndCloseZombie(db);
  110925. return SQLITE_OK;
  110926. }
  110927. /*
  110928. ** Two variations on the public interface for closing a database
  110929. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  110930. ** leaves the connection option if there are unfinalized prepared
  110931. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  110932. ** version forces the connection to become a zombie if there are
  110933. ** unclosed resources, and arranges for deallocation when the last
  110934. ** prepare statement or sqlite3_backup closes.
  110935. */
  110936. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  110937. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  110938. /*
  110939. ** Close the mutex on database connection db.
  110940. **
  110941. ** Furthermore, if database connection db is a zombie (meaning that there
  110942. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  110943. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  110944. ** finished, then free all resources.
  110945. */
  110946. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  110947. HashElem *i; /* Hash table iterator */
  110948. int j;
  110949. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  110950. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  110951. ** then just leave the mutex and return.
  110952. */
  110953. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  110954. sqlite3_mutex_leave(db->mutex);
  110955. return;
  110956. }
  110957. /* If we reach this point, it means that the database connection has
  110958. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  110959. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  110960. ** go ahead and free all resources.
  110961. */
  110962. /* If a transaction is open, roll it back. This also ensures that if
  110963. ** any database schemas have been modified by an uncommitted transaction
  110964. ** they are reset. And that the required b-tree mutex is held to make
  110965. ** the pager rollback and schema reset an atomic operation. */
  110966. sqlite3RollbackAll(db, SQLITE_OK);
  110967. /* Free any outstanding Savepoint structures. */
  110968. sqlite3CloseSavepoints(db);
  110969. /* Close all database connections */
  110970. for(j=0; j<db->nDb; j++){
  110971. struct Db *pDb = &db->aDb[j];
  110972. if( pDb->pBt ){
  110973. sqlite3BtreeClose(pDb->pBt);
  110974. pDb->pBt = 0;
  110975. if( j!=1 ){
  110976. pDb->pSchema = 0;
  110977. }
  110978. }
  110979. }
  110980. /* Clear the TEMP schema separately and last */
  110981. if( db->aDb[1].pSchema ){
  110982. sqlite3SchemaClear(db->aDb[1].pSchema);
  110983. }
  110984. sqlite3VtabUnlockList(db);
  110985. /* Free up the array of auxiliary databases */
  110986. sqlite3CollapseDatabaseArray(db);
  110987. assert( db->nDb<=2 );
  110988. assert( db->aDb==db->aDbStatic );
  110989. /* Tell the code in notify.c that the connection no longer holds any
  110990. ** locks and does not require any further unlock-notify callbacks.
  110991. */
  110992. sqlite3ConnectionClosed(db);
  110993. for(j=0; j<ArraySize(db->aFunc.a); j++){
  110994. FuncDef *pNext, *pHash, *p;
  110995. for(p=db->aFunc.a[j]; p; p=pHash){
  110996. pHash = p->pHash;
  110997. while( p ){
  110998. functionDestroy(db, p);
  110999. pNext = p->pNext;
  111000. sqlite3DbFree(db, p);
  111001. p = pNext;
  111002. }
  111003. }
  111004. }
  111005. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  111006. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  111007. /* Invoke any destructors registered for collation sequence user data. */
  111008. for(j=0; j<3; j++){
  111009. if( pColl[j].xDel ){
  111010. pColl[j].xDel(pColl[j].pUser);
  111011. }
  111012. }
  111013. sqlite3DbFree(db, pColl);
  111014. }
  111015. sqlite3HashClear(&db->aCollSeq);
  111016. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111017. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  111018. Module *pMod = (Module *)sqliteHashData(i);
  111019. if( pMod->xDestroy ){
  111020. pMod->xDestroy(pMod->pAux);
  111021. }
  111022. sqlite3DbFree(db, pMod);
  111023. }
  111024. sqlite3HashClear(&db->aModule);
  111025. #endif
  111026. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  111027. if( db->pErr ){
  111028. sqlite3ValueFree(db->pErr);
  111029. }
  111030. sqlite3CloseExtensions(db);
  111031. db->magic = SQLITE_MAGIC_ERROR;
  111032. /* The temp-database schema is allocated differently from the other schema
  111033. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  111034. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  111035. ** the same sqliteMalloc() as the one that allocates the database
  111036. ** structure?
  111037. */
  111038. sqlite3DbFree(db, db->aDb[1].pSchema);
  111039. sqlite3_mutex_leave(db->mutex);
  111040. db->magic = SQLITE_MAGIC_CLOSED;
  111041. sqlite3_mutex_free(db->mutex);
  111042. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  111043. if( db->lookaside.bMalloced ){
  111044. sqlite3_free(db->lookaside.pStart);
  111045. }
  111046. sqlite3_free(db);
  111047. }
  111048. /*
  111049. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  111050. ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
  111051. ** breaker") and made to return tripCode if there are any further
  111052. ** attempts to use that cursor.
  111053. */
  111054. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  111055. int i;
  111056. int inTrans = 0;
  111057. assert( sqlite3_mutex_held(db->mutex) );
  111058. sqlite3BeginBenignMalloc();
  111059. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  111060. ** This is important in case the transaction being rolled back has
  111061. ** modified the database schema. If the b-tree mutexes are not taken
  111062. ** here, then another shared-cache connection might sneak in between
  111063. ** the database rollback and schema reset, which can cause false
  111064. ** corruption reports in some cases. */
  111065. sqlite3BtreeEnterAll(db);
  111066. for(i=0; i<db->nDb; i++){
  111067. Btree *p = db->aDb[i].pBt;
  111068. if( p ){
  111069. if( sqlite3BtreeIsInTrans(p) ){
  111070. inTrans = 1;
  111071. }
  111072. sqlite3BtreeRollback(p, tripCode);
  111073. }
  111074. }
  111075. sqlite3VtabRollback(db);
  111076. sqlite3EndBenignMalloc();
  111077. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  111078. sqlite3ExpirePreparedStatements(db);
  111079. sqlite3ResetAllSchemasOfConnection(db);
  111080. }
  111081. sqlite3BtreeLeaveAll(db);
  111082. /* Any deferred constraint violations have now been resolved. */
  111083. db->nDeferredCons = 0;
  111084. db->nDeferredImmCons = 0;
  111085. db->flags &= ~SQLITE_DeferFKs;
  111086. /* If one has been configured, invoke the rollback-hook callback */
  111087. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  111088. db->xRollbackCallback(db->pRollbackArg);
  111089. }
  111090. }
  111091. /*
  111092. ** Return a static string containing the name corresponding to the error code
  111093. ** specified in the argument.
  111094. */
  111095. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  111096. defined(SQLITE_DEBUG_OS_TRACE)
  111097. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  111098. const char *zName = 0;
  111099. int i, origRc = rc;
  111100. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  111101. switch( rc ){
  111102. case SQLITE_OK: zName = "SQLITE_OK"; break;
  111103. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  111104. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  111105. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  111106. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  111107. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  111108. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  111109. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  111110. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  111111. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  111112. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  111113. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  111114. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  111115. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  111116. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  111117. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  111118. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  111119. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  111120. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  111121. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  111122. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  111123. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  111124. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  111125. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  111126. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  111127. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  111128. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  111129. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  111130. case SQLITE_IOERR_BLOCKED: zName = "SQLITE_IOERR_BLOCKED"; break;
  111131. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  111132. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  111133. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  111134. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  111135. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  111136. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  111137. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  111138. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  111139. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  111140. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  111141. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  111142. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  111143. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  111144. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  111145. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  111146. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  111147. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  111148. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  111149. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  111150. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  111151. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  111152. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  111153. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  111154. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  111155. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  111156. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  111157. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  111158. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  111159. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  111160. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  111161. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  111162. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  111163. case SQLITE_CONSTRAINT_FOREIGNKEY:
  111164. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  111165. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  111166. case SQLITE_CONSTRAINT_PRIMARYKEY:
  111167. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  111168. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  111169. case SQLITE_CONSTRAINT_COMMITHOOK:
  111170. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  111171. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  111172. case SQLITE_CONSTRAINT_FUNCTION:
  111173. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  111174. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  111175. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  111176. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  111177. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  111178. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  111179. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  111180. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  111181. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  111182. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  111183. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  111184. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  111185. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  111186. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  111187. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  111188. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  111189. }
  111190. }
  111191. if( zName==0 ){
  111192. static char zBuf[50];
  111193. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  111194. zName = zBuf;
  111195. }
  111196. return zName;
  111197. }
  111198. #endif
  111199. /*
  111200. ** Return a static string that describes the kind of error specified in the
  111201. ** argument.
  111202. */
  111203. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  111204. static const char* const aMsg[] = {
  111205. /* SQLITE_OK */ "not an error",
  111206. /* SQLITE_ERROR */ "SQL logic error or missing database",
  111207. /* SQLITE_INTERNAL */ 0,
  111208. /* SQLITE_PERM */ "access permission denied",
  111209. /* SQLITE_ABORT */ "callback requested query abort",
  111210. /* SQLITE_BUSY */ "database is locked",
  111211. /* SQLITE_LOCKED */ "database table is locked",
  111212. /* SQLITE_NOMEM */ "out of memory",
  111213. /* SQLITE_READONLY */ "attempt to write a readonly database",
  111214. /* SQLITE_INTERRUPT */ "interrupted",
  111215. /* SQLITE_IOERR */ "disk I/O error",
  111216. /* SQLITE_CORRUPT */ "database disk image is malformed",
  111217. /* SQLITE_NOTFOUND */ "unknown operation",
  111218. /* SQLITE_FULL */ "database or disk is full",
  111219. /* SQLITE_CANTOPEN */ "unable to open database file",
  111220. /* SQLITE_PROTOCOL */ "locking protocol",
  111221. /* SQLITE_EMPTY */ "table contains no data",
  111222. /* SQLITE_SCHEMA */ "database schema has changed",
  111223. /* SQLITE_TOOBIG */ "string or blob too big",
  111224. /* SQLITE_CONSTRAINT */ "constraint failed",
  111225. /* SQLITE_MISMATCH */ "datatype mismatch",
  111226. /* SQLITE_MISUSE */ "library routine called out of sequence",
  111227. /* SQLITE_NOLFS */ "large file support is disabled",
  111228. /* SQLITE_AUTH */ "authorization denied",
  111229. /* SQLITE_FORMAT */ "auxiliary database format error",
  111230. /* SQLITE_RANGE */ "bind or column index out of range",
  111231. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  111232. };
  111233. const char *zErr = "unknown error";
  111234. switch( rc ){
  111235. case SQLITE_ABORT_ROLLBACK: {
  111236. zErr = "abort due to ROLLBACK";
  111237. break;
  111238. }
  111239. default: {
  111240. rc &= 0xff;
  111241. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  111242. zErr = aMsg[rc];
  111243. }
  111244. break;
  111245. }
  111246. }
  111247. return zErr;
  111248. }
  111249. /*
  111250. ** This routine implements a busy callback that sleeps and tries
  111251. ** again until a timeout value is reached. The timeout value is
  111252. ** an integer number of milliseconds passed in as the first
  111253. ** argument.
  111254. */
  111255. static int sqliteDefaultBusyCallback(
  111256. void *ptr, /* Database connection */
  111257. int count /* Number of times table has been busy */
  111258. ){
  111259. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  111260. static const u8 delays[] =
  111261. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  111262. static const u8 totals[] =
  111263. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  111264. # define NDELAY ArraySize(delays)
  111265. sqlite3 *db = (sqlite3 *)ptr;
  111266. int timeout = db->busyTimeout;
  111267. int delay, prior;
  111268. assert( count>=0 );
  111269. if( count < NDELAY ){
  111270. delay = delays[count];
  111271. prior = totals[count];
  111272. }else{
  111273. delay = delays[NDELAY-1];
  111274. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  111275. }
  111276. if( prior + delay > timeout ){
  111277. delay = timeout - prior;
  111278. if( delay<=0 ) return 0;
  111279. }
  111280. sqlite3OsSleep(db->pVfs, delay*1000);
  111281. return 1;
  111282. #else
  111283. sqlite3 *db = (sqlite3 *)ptr;
  111284. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  111285. if( (count+1)*1000 > timeout ){
  111286. return 0;
  111287. }
  111288. sqlite3OsSleep(db->pVfs, 1000000);
  111289. return 1;
  111290. #endif
  111291. }
  111292. /*
  111293. ** Invoke the given busy handler.
  111294. **
  111295. ** This routine is called when an operation failed with a lock.
  111296. ** If this routine returns non-zero, the lock is retried. If it
  111297. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  111298. */
  111299. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  111300. int rc;
  111301. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  111302. rc = p->xFunc(p->pArg, p->nBusy);
  111303. if( rc==0 ){
  111304. p->nBusy = -1;
  111305. }else{
  111306. p->nBusy++;
  111307. }
  111308. return rc;
  111309. }
  111310. /*
  111311. ** This routine sets the busy callback for an Sqlite database to the
  111312. ** given callback function with the given argument.
  111313. */
  111314. SQLITE_API int sqlite3_busy_handler(
  111315. sqlite3 *db,
  111316. int (*xBusy)(void*,int),
  111317. void *pArg
  111318. ){
  111319. sqlite3_mutex_enter(db->mutex);
  111320. db->busyHandler.xFunc = xBusy;
  111321. db->busyHandler.pArg = pArg;
  111322. db->busyHandler.nBusy = 0;
  111323. db->busyTimeout = 0;
  111324. sqlite3_mutex_leave(db->mutex);
  111325. return SQLITE_OK;
  111326. }
  111327. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  111328. /*
  111329. ** This routine sets the progress callback for an Sqlite database to the
  111330. ** given callback function with the given argument. The progress callback will
  111331. ** be invoked every nOps opcodes.
  111332. */
  111333. SQLITE_API void sqlite3_progress_handler(
  111334. sqlite3 *db,
  111335. int nOps,
  111336. int (*xProgress)(void*),
  111337. void *pArg
  111338. ){
  111339. sqlite3_mutex_enter(db->mutex);
  111340. if( nOps>0 ){
  111341. db->xProgress = xProgress;
  111342. db->nProgressOps = (unsigned)nOps;
  111343. db->pProgressArg = pArg;
  111344. }else{
  111345. db->xProgress = 0;
  111346. db->nProgressOps = 0;
  111347. db->pProgressArg = 0;
  111348. }
  111349. sqlite3_mutex_leave(db->mutex);
  111350. }
  111351. #endif
  111352. /*
  111353. ** This routine installs a default busy handler that waits for the
  111354. ** specified number of milliseconds before returning 0.
  111355. */
  111356. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  111357. if( ms>0 ){
  111358. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  111359. db->busyTimeout = ms;
  111360. }else{
  111361. sqlite3_busy_handler(db, 0, 0);
  111362. }
  111363. return SQLITE_OK;
  111364. }
  111365. /*
  111366. ** Cause any pending operation to stop at its earliest opportunity.
  111367. */
  111368. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  111369. db->u1.isInterrupted = 1;
  111370. }
  111371. /*
  111372. ** This function is exactly the same as sqlite3_create_function(), except
  111373. ** that it is designed to be called by internal code. The difference is
  111374. ** that if a malloc() fails in sqlite3_create_function(), an error code
  111375. ** is returned and the mallocFailed flag cleared.
  111376. */
  111377. SQLITE_PRIVATE int sqlite3CreateFunc(
  111378. sqlite3 *db,
  111379. const char *zFunctionName,
  111380. int nArg,
  111381. int enc,
  111382. void *pUserData,
  111383. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  111384. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  111385. void (*xFinal)(sqlite3_context*),
  111386. FuncDestructor *pDestructor
  111387. ){
  111388. FuncDef *p;
  111389. int nName;
  111390. assert( sqlite3_mutex_held(db->mutex) );
  111391. if( zFunctionName==0 ||
  111392. (xFunc && (xFinal || xStep)) ||
  111393. (!xFunc && (xFinal && !xStep)) ||
  111394. (!xFunc && (!xFinal && xStep)) ||
  111395. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  111396. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  111397. return SQLITE_MISUSE_BKPT;
  111398. }
  111399. #ifndef SQLITE_OMIT_UTF16
  111400. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  111401. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  111402. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  111403. **
  111404. ** If SQLITE_ANY is specified, add three versions of the function
  111405. ** to the hash table.
  111406. */
  111407. if( enc==SQLITE_UTF16 ){
  111408. enc = SQLITE_UTF16NATIVE;
  111409. }else if( enc==SQLITE_ANY ){
  111410. int rc;
  111411. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  111412. pUserData, xFunc, xStep, xFinal, pDestructor);
  111413. if( rc==SQLITE_OK ){
  111414. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  111415. pUserData, xFunc, xStep, xFinal, pDestructor);
  111416. }
  111417. if( rc!=SQLITE_OK ){
  111418. return rc;
  111419. }
  111420. enc = SQLITE_UTF16BE;
  111421. }
  111422. #else
  111423. enc = SQLITE_UTF8;
  111424. #endif
  111425. /* Check if an existing function is being overridden or deleted. If so,
  111426. ** and there are active VMs, then return SQLITE_BUSY. If a function
  111427. ** is being overridden/deleted but there are no active VMs, allow the
  111428. ** operation to continue but invalidate all precompiled statements.
  111429. */
  111430. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  111431. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  111432. if( db->nVdbeActive ){
  111433. sqlite3Error(db, SQLITE_BUSY,
  111434. "unable to delete/modify user-function due to active statements");
  111435. assert( !db->mallocFailed );
  111436. return SQLITE_BUSY;
  111437. }else{
  111438. sqlite3ExpirePreparedStatements(db);
  111439. }
  111440. }
  111441. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  111442. assert(p || db->mallocFailed);
  111443. if( !p ){
  111444. return SQLITE_NOMEM;
  111445. }
  111446. /* If an older version of the function with a configured destructor is
  111447. ** being replaced invoke the destructor function here. */
  111448. functionDestroy(db, p);
  111449. if( pDestructor ){
  111450. pDestructor->nRef++;
  111451. }
  111452. p->pDestructor = pDestructor;
  111453. p->funcFlags &= SQLITE_FUNC_ENCMASK;
  111454. p->xFunc = xFunc;
  111455. p->xStep = xStep;
  111456. p->xFinalize = xFinal;
  111457. p->pUserData = pUserData;
  111458. p->nArg = (u16)nArg;
  111459. return SQLITE_OK;
  111460. }
  111461. /*
  111462. ** Create new user functions.
  111463. */
  111464. SQLITE_API int sqlite3_create_function(
  111465. sqlite3 *db,
  111466. const char *zFunc,
  111467. int nArg,
  111468. int enc,
  111469. void *p,
  111470. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  111471. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  111472. void (*xFinal)(sqlite3_context*)
  111473. ){
  111474. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  111475. xFinal, 0);
  111476. }
  111477. SQLITE_API int sqlite3_create_function_v2(
  111478. sqlite3 *db,
  111479. const char *zFunc,
  111480. int nArg,
  111481. int enc,
  111482. void *p,
  111483. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  111484. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  111485. void (*xFinal)(sqlite3_context*),
  111486. void (*xDestroy)(void *)
  111487. ){
  111488. int rc = SQLITE_ERROR;
  111489. FuncDestructor *pArg = 0;
  111490. sqlite3_mutex_enter(db->mutex);
  111491. if( xDestroy ){
  111492. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  111493. if( !pArg ){
  111494. xDestroy(p);
  111495. goto out;
  111496. }
  111497. pArg->xDestroy = xDestroy;
  111498. pArg->pUserData = p;
  111499. }
  111500. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  111501. if( pArg && pArg->nRef==0 ){
  111502. assert( rc!=SQLITE_OK );
  111503. xDestroy(p);
  111504. sqlite3DbFree(db, pArg);
  111505. }
  111506. out:
  111507. rc = sqlite3ApiExit(db, rc);
  111508. sqlite3_mutex_leave(db->mutex);
  111509. return rc;
  111510. }
  111511. #ifndef SQLITE_OMIT_UTF16
  111512. SQLITE_API int sqlite3_create_function16(
  111513. sqlite3 *db,
  111514. const void *zFunctionName,
  111515. int nArg,
  111516. int eTextRep,
  111517. void *p,
  111518. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  111519. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  111520. void (*xFinal)(sqlite3_context*)
  111521. ){
  111522. int rc;
  111523. char *zFunc8;
  111524. sqlite3_mutex_enter(db->mutex);
  111525. assert( !db->mallocFailed );
  111526. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  111527. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  111528. sqlite3DbFree(db, zFunc8);
  111529. rc = sqlite3ApiExit(db, rc);
  111530. sqlite3_mutex_leave(db->mutex);
  111531. return rc;
  111532. }
  111533. #endif
  111534. /*
  111535. ** Declare that a function has been overloaded by a virtual table.
  111536. **
  111537. ** If the function already exists as a regular global function, then
  111538. ** this routine is a no-op. If the function does not exist, then create
  111539. ** a new one that always throws a run-time error.
  111540. **
  111541. ** When virtual tables intend to provide an overloaded function, they
  111542. ** should call this routine to make sure the global function exists.
  111543. ** A global function must exist in order for name resolution to work
  111544. ** properly.
  111545. */
  111546. SQLITE_API int sqlite3_overload_function(
  111547. sqlite3 *db,
  111548. const char *zName,
  111549. int nArg
  111550. ){
  111551. int nName = sqlite3Strlen30(zName);
  111552. int rc = SQLITE_OK;
  111553. sqlite3_mutex_enter(db->mutex);
  111554. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  111555. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  111556. 0, sqlite3InvalidFunction, 0, 0, 0);
  111557. }
  111558. rc = sqlite3ApiExit(db, rc);
  111559. sqlite3_mutex_leave(db->mutex);
  111560. return rc;
  111561. }
  111562. #ifndef SQLITE_OMIT_TRACE
  111563. /*
  111564. ** Register a trace function. The pArg from the previously registered trace
  111565. ** is returned.
  111566. **
  111567. ** A NULL trace function means that no tracing is executes. A non-NULL
  111568. ** trace is a pointer to a function that is invoked at the start of each
  111569. ** SQL statement.
  111570. */
  111571. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  111572. void *pOld;
  111573. sqlite3_mutex_enter(db->mutex);
  111574. pOld = db->pTraceArg;
  111575. db->xTrace = xTrace;
  111576. db->pTraceArg = pArg;
  111577. sqlite3_mutex_leave(db->mutex);
  111578. return pOld;
  111579. }
  111580. /*
  111581. ** Register a profile function. The pArg from the previously registered
  111582. ** profile function is returned.
  111583. **
  111584. ** A NULL profile function means that no profiling is executes. A non-NULL
  111585. ** profile is a pointer to a function that is invoked at the conclusion of
  111586. ** each SQL statement that is run.
  111587. */
  111588. SQLITE_API void *sqlite3_profile(
  111589. sqlite3 *db,
  111590. void (*xProfile)(void*,const char*,sqlite_uint64),
  111591. void *pArg
  111592. ){
  111593. void *pOld;
  111594. sqlite3_mutex_enter(db->mutex);
  111595. pOld = db->pProfileArg;
  111596. db->xProfile = xProfile;
  111597. db->pProfileArg = pArg;
  111598. sqlite3_mutex_leave(db->mutex);
  111599. return pOld;
  111600. }
  111601. #endif /* SQLITE_OMIT_TRACE */
  111602. /*
  111603. ** Register a function to be invoked when a transaction commits.
  111604. ** If the invoked function returns non-zero, then the commit becomes a
  111605. ** rollback.
  111606. */
  111607. SQLITE_API void *sqlite3_commit_hook(
  111608. sqlite3 *db, /* Attach the hook to this database */
  111609. int (*xCallback)(void*), /* Function to invoke on each commit */
  111610. void *pArg /* Argument to the function */
  111611. ){
  111612. void *pOld;
  111613. sqlite3_mutex_enter(db->mutex);
  111614. pOld = db->pCommitArg;
  111615. db->xCommitCallback = xCallback;
  111616. db->pCommitArg = pArg;
  111617. sqlite3_mutex_leave(db->mutex);
  111618. return pOld;
  111619. }
  111620. /*
  111621. ** Register a callback to be invoked each time a row is updated,
  111622. ** inserted or deleted using this database connection.
  111623. */
  111624. SQLITE_API void *sqlite3_update_hook(
  111625. sqlite3 *db, /* Attach the hook to this database */
  111626. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  111627. void *pArg /* Argument to the function */
  111628. ){
  111629. void *pRet;
  111630. sqlite3_mutex_enter(db->mutex);
  111631. pRet = db->pUpdateArg;
  111632. db->xUpdateCallback = xCallback;
  111633. db->pUpdateArg = pArg;
  111634. sqlite3_mutex_leave(db->mutex);
  111635. return pRet;
  111636. }
  111637. /*
  111638. ** Register a callback to be invoked each time a transaction is rolled
  111639. ** back by this database connection.
  111640. */
  111641. SQLITE_API void *sqlite3_rollback_hook(
  111642. sqlite3 *db, /* Attach the hook to this database */
  111643. void (*xCallback)(void*), /* Callback function */
  111644. void *pArg /* Argument to the function */
  111645. ){
  111646. void *pRet;
  111647. sqlite3_mutex_enter(db->mutex);
  111648. pRet = db->pRollbackArg;
  111649. db->xRollbackCallback = xCallback;
  111650. db->pRollbackArg = pArg;
  111651. sqlite3_mutex_leave(db->mutex);
  111652. return pRet;
  111653. }
  111654. #ifndef SQLITE_OMIT_WAL
  111655. /*
  111656. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  111657. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  111658. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  111659. ** wal_autocheckpoint()).
  111660. */
  111661. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  111662. void *pClientData, /* Argument */
  111663. sqlite3 *db, /* Connection */
  111664. const char *zDb, /* Database */
  111665. int nFrame /* Size of WAL */
  111666. ){
  111667. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  111668. sqlite3BeginBenignMalloc();
  111669. sqlite3_wal_checkpoint(db, zDb);
  111670. sqlite3EndBenignMalloc();
  111671. }
  111672. return SQLITE_OK;
  111673. }
  111674. #endif /* SQLITE_OMIT_WAL */
  111675. /*
  111676. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  111677. ** a database after committing a transaction if there are nFrame or
  111678. ** more frames in the log file. Passing zero or a negative value as the
  111679. ** nFrame parameter disables automatic checkpoints entirely.
  111680. **
  111681. ** The callback registered by this function replaces any existing callback
  111682. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  111683. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  111684. ** configured by this function.
  111685. */
  111686. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  111687. #ifdef SQLITE_OMIT_WAL
  111688. UNUSED_PARAMETER(db);
  111689. UNUSED_PARAMETER(nFrame);
  111690. #else
  111691. if( nFrame>0 ){
  111692. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  111693. }else{
  111694. sqlite3_wal_hook(db, 0, 0);
  111695. }
  111696. #endif
  111697. return SQLITE_OK;
  111698. }
  111699. /*
  111700. ** Register a callback to be invoked each time a transaction is written
  111701. ** into the write-ahead-log by this database connection.
  111702. */
  111703. SQLITE_API void *sqlite3_wal_hook(
  111704. sqlite3 *db, /* Attach the hook to this db handle */
  111705. int(*xCallback)(void *, sqlite3*, const char*, int),
  111706. void *pArg /* First argument passed to xCallback() */
  111707. ){
  111708. #ifndef SQLITE_OMIT_WAL
  111709. void *pRet;
  111710. sqlite3_mutex_enter(db->mutex);
  111711. pRet = db->pWalArg;
  111712. db->xWalCallback = xCallback;
  111713. db->pWalArg = pArg;
  111714. sqlite3_mutex_leave(db->mutex);
  111715. return pRet;
  111716. #else
  111717. return 0;
  111718. #endif
  111719. }
  111720. /*
  111721. ** Checkpoint database zDb.
  111722. */
  111723. SQLITE_API int sqlite3_wal_checkpoint_v2(
  111724. sqlite3 *db, /* Database handle */
  111725. const char *zDb, /* Name of attached database (or NULL) */
  111726. int eMode, /* SQLITE_CHECKPOINT_* value */
  111727. int *pnLog, /* OUT: Size of WAL log in frames */
  111728. int *pnCkpt /* OUT: Total number of frames checkpointed */
  111729. ){
  111730. #ifdef SQLITE_OMIT_WAL
  111731. return SQLITE_OK;
  111732. #else
  111733. int rc; /* Return code */
  111734. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  111735. /* Initialize the output variables to -1 in case an error occurs. */
  111736. if( pnLog ) *pnLog = -1;
  111737. if( pnCkpt ) *pnCkpt = -1;
  111738. assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
  111739. assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
  111740. assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
  111741. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
  111742. return SQLITE_MISUSE;
  111743. }
  111744. sqlite3_mutex_enter(db->mutex);
  111745. if( zDb && zDb[0] ){
  111746. iDb = sqlite3FindDbName(db, zDb);
  111747. }
  111748. if( iDb<0 ){
  111749. rc = SQLITE_ERROR;
  111750. sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
  111751. }else{
  111752. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  111753. sqlite3Error(db, rc, 0);
  111754. }
  111755. rc = sqlite3ApiExit(db, rc);
  111756. sqlite3_mutex_leave(db->mutex);
  111757. return rc;
  111758. #endif
  111759. }
  111760. /*
  111761. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  111762. ** to contains a zero-length string, all attached databases are
  111763. ** checkpointed.
  111764. */
  111765. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  111766. return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
  111767. }
  111768. #ifndef SQLITE_OMIT_WAL
  111769. /*
  111770. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  111771. ** not currently open in WAL mode.
  111772. **
  111773. ** If a transaction is open on the database being checkpointed, this
  111774. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  111775. ** an error occurs while running the checkpoint, an SQLite error code is
  111776. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  111777. **
  111778. ** The mutex on database handle db should be held by the caller. The mutex
  111779. ** associated with the specific b-tree being checkpointed is taken by
  111780. ** this function while the checkpoint is running.
  111781. **
  111782. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  111783. ** checkpointed. If an error is encountered it is returned immediately -
  111784. ** no attempt is made to checkpoint any remaining databases.
  111785. **
  111786. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  111787. */
  111788. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  111789. int rc = SQLITE_OK; /* Return code */
  111790. int i; /* Used to iterate through attached dbs */
  111791. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  111792. assert( sqlite3_mutex_held(db->mutex) );
  111793. assert( !pnLog || *pnLog==-1 );
  111794. assert( !pnCkpt || *pnCkpt==-1 );
  111795. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  111796. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  111797. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  111798. pnLog = 0;
  111799. pnCkpt = 0;
  111800. if( rc==SQLITE_BUSY ){
  111801. bBusy = 1;
  111802. rc = SQLITE_OK;
  111803. }
  111804. }
  111805. }
  111806. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  111807. }
  111808. #endif /* SQLITE_OMIT_WAL */
  111809. /*
  111810. ** This function returns true if main-memory should be used instead of
  111811. ** a temporary file for transient pager files and statement journals.
  111812. ** The value returned depends on the value of db->temp_store (runtime
  111813. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  111814. ** following table describes the relationship between these two values
  111815. ** and this functions return value.
  111816. **
  111817. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  111818. ** ----------------- -------------- ------------------------------
  111819. ** 0 any file (return 0)
  111820. ** 1 1 file (return 0)
  111821. ** 1 2 memory (return 1)
  111822. ** 1 0 file (return 0)
  111823. ** 2 1 file (return 0)
  111824. ** 2 2 memory (return 1)
  111825. ** 2 0 memory (return 1)
  111826. ** 3 any memory (return 1)
  111827. */
  111828. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  111829. #if SQLITE_TEMP_STORE==1
  111830. return ( db->temp_store==2 );
  111831. #endif
  111832. #if SQLITE_TEMP_STORE==2
  111833. return ( db->temp_store!=1 );
  111834. #endif
  111835. #if SQLITE_TEMP_STORE==3
  111836. return 1;
  111837. #endif
  111838. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  111839. return 0;
  111840. #endif
  111841. }
  111842. /*
  111843. ** Return UTF-8 encoded English language explanation of the most recent
  111844. ** error.
  111845. */
  111846. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  111847. const char *z;
  111848. if( !db ){
  111849. return sqlite3ErrStr(SQLITE_NOMEM);
  111850. }
  111851. if( !sqlite3SafetyCheckSickOrOk(db) ){
  111852. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  111853. }
  111854. sqlite3_mutex_enter(db->mutex);
  111855. if( db->mallocFailed ){
  111856. z = sqlite3ErrStr(SQLITE_NOMEM);
  111857. }else{
  111858. z = (char*)sqlite3_value_text(db->pErr);
  111859. assert( !db->mallocFailed );
  111860. if( z==0 ){
  111861. z = sqlite3ErrStr(db->errCode);
  111862. }
  111863. }
  111864. sqlite3_mutex_leave(db->mutex);
  111865. return z;
  111866. }
  111867. #ifndef SQLITE_OMIT_UTF16
  111868. /*
  111869. ** Return UTF-16 encoded English language explanation of the most recent
  111870. ** error.
  111871. */
  111872. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  111873. static const u16 outOfMem[] = {
  111874. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  111875. };
  111876. static const u16 misuse[] = {
  111877. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  111878. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  111879. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  111880. 'o', 'u', 't', ' ',
  111881. 'o', 'f', ' ',
  111882. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  111883. };
  111884. const void *z;
  111885. if( !db ){
  111886. return (void *)outOfMem;
  111887. }
  111888. if( !sqlite3SafetyCheckSickOrOk(db) ){
  111889. return (void *)misuse;
  111890. }
  111891. sqlite3_mutex_enter(db->mutex);
  111892. if( db->mallocFailed ){
  111893. z = (void *)outOfMem;
  111894. }else{
  111895. z = sqlite3_value_text16(db->pErr);
  111896. if( z==0 ){
  111897. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  111898. SQLITE_UTF8, SQLITE_STATIC);
  111899. z = sqlite3_value_text16(db->pErr);
  111900. }
  111901. /* A malloc() may have failed within the call to sqlite3_value_text16()
  111902. ** above. If this is the case, then the db->mallocFailed flag needs to
  111903. ** be cleared before returning. Do this directly, instead of via
  111904. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  111905. */
  111906. db->mallocFailed = 0;
  111907. }
  111908. sqlite3_mutex_leave(db->mutex);
  111909. return z;
  111910. }
  111911. #endif /* SQLITE_OMIT_UTF16 */
  111912. /*
  111913. ** Return the most recent error code generated by an SQLite routine. If NULL is
  111914. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  111915. */
  111916. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  111917. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  111918. return SQLITE_MISUSE_BKPT;
  111919. }
  111920. if( !db || db->mallocFailed ){
  111921. return SQLITE_NOMEM;
  111922. }
  111923. return db->errCode & db->errMask;
  111924. }
  111925. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  111926. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  111927. return SQLITE_MISUSE_BKPT;
  111928. }
  111929. if( !db || db->mallocFailed ){
  111930. return SQLITE_NOMEM;
  111931. }
  111932. return db->errCode;
  111933. }
  111934. /*
  111935. ** Return a string that describes the kind of error specified in the
  111936. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  111937. ** function.
  111938. */
  111939. SQLITE_API const char *sqlite3_errstr(int rc){
  111940. return sqlite3ErrStr(rc);
  111941. }
  111942. /*
  111943. ** Create a new collating function for database "db". The name is zName
  111944. ** and the encoding is enc.
  111945. */
  111946. static int createCollation(
  111947. sqlite3* db,
  111948. const char *zName,
  111949. u8 enc,
  111950. void* pCtx,
  111951. int(*xCompare)(void*,int,const void*,int,const void*),
  111952. void(*xDel)(void*)
  111953. ){
  111954. CollSeq *pColl;
  111955. int enc2;
  111956. int nName = sqlite3Strlen30(zName);
  111957. assert( sqlite3_mutex_held(db->mutex) );
  111958. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  111959. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  111960. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  111961. */
  111962. enc2 = enc;
  111963. testcase( enc2==SQLITE_UTF16 );
  111964. testcase( enc2==SQLITE_UTF16_ALIGNED );
  111965. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  111966. enc2 = SQLITE_UTF16NATIVE;
  111967. }
  111968. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  111969. return SQLITE_MISUSE_BKPT;
  111970. }
  111971. /* Check if this call is removing or replacing an existing collation
  111972. ** sequence. If so, and there are active VMs, return busy. If there
  111973. ** are no active VMs, invalidate any pre-compiled statements.
  111974. */
  111975. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  111976. if( pColl && pColl->xCmp ){
  111977. if( db->nVdbeActive ){
  111978. sqlite3Error(db, SQLITE_BUSY,
  111979. "unable to delete/modify collation sequence due to active statements");
  111980. return SQLITE_BUSY;
  111981. }
  111982. sqlite3ExpirePreparedStatements(db);
  111983. /* If collation sequence pColl was created directly by a call to
  111984. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  111985. ** then any copies made by synthCollSeq() need to be invalidated.
  111986. ** Also, collation destructor - CollSeq.xDel() - function may need
  111987. ** to be called.
  111988. */
  111989. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  111990. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  111991. int j;
  111992. for(j=0; j<3; j++){
  111993. CollSeq *p = &aColl[j];
  111994. if( p->enc==pColl->enc ){
  111995. if( p->xDel ){
  111996. p->xDel(p->pUser);
  111997. }
  111998. p->xCmp = 0;
  111999. }
  112000. }
  112001. }
  112002. }
  112003. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  112004. if( pColl==0 ) return SQLITE_NOMEM;
  112005. pColl->xCmp = xCompare;
  112006. pColl->pUser = pCtx;
  112007. pColl->xDel = xDel;
  112008. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  112009. sqlite3Error(db, SQLITE_OK, 0);
  112010. return SQLITE_OK;
  112011. }
  112012. /*
  112013. ** This array defines hard upper bounds on limit values. The
  112014. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  112015. ** #defines in sqlite3.h.
  112016. */
  112017. static const int aHardLimit[] = {
  112018. SQLITE_MAX_LENGTH,
  112019. SQLITE_MAX_SQL_LENGTH,
  112020. SQLITE_MAX_COLUMN,
  112021. SQLITE_MAX_EXPR_DEPTH,
  112022. SQLITE_MAX_COMPOUND_SELECT,
  112023. SQLITE_MAX_VDBE_OP,
  112024. SQLITE_MAX_FUNCTION_ARG,
  112025. SQLITE_MAX_ATTACHED,
  112026. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  112027. SQLITE_MAX_VARIABLE_NUMBER,
  112028. SQLITE_MAX_TRIGGER_DEPTH,
  112029. };
  112030. /*
  112031. ** Make sure the hard limits are set to reasonable values
  112032. */
  112033. #if SQLITE_MAX_LENGTH<100
  112034. # error SQLITE_MAX_LENGTH must be at least 100
  112035. #endif
  112036. #if SQLITE_MAX_SQL_LENGTH<100
  112037. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  112038. #endif
  112039. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  112040. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  112041. #endif
  112042. #if SQLITE_MAX_COMPOUND_SELECT<2
  112043. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  112044. #endif
  112045. #if SQLITE_MAX_VDBE_OP<40
  112046. # error SQLITE_MAX_VDBE_OP must be at least 40
  112047. #endif
  112048. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  112049. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  112050. #endif
  112051. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
  112052. # error SQLITE_MAX_ATTACHED must be between 0 and 62
  112053. #endif
  112054. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  112055. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  112056. #endif
  112057. #if SQLITE_MAX_COLUMN>32767
  112058. # error SQLITE_MAX_COLUMN must not exceed 32767
  112059. #endif
  112060. #if SQLITE_MAX_TRIGGER_DEPTH<1
  112061. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  112062. #endif
  112063. /*
  112064. ** Change the value of a limit. Report the old value.
  112065. ** If an invalid limit index is supplied, report -1.
  112066. ** Make no changes but still report the old value if the
  112067. ** new limit is negative.
  112068. **
  112069. ** A new lower limit does not shrink existing constructs.
  112070. ** It merely prevents new constructs that exceed the limit
  112071. ** from forming.
  112072. */
  112073. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  112074. int oldLimit;
  112075. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  112076. ** there is a hard upper bound set at compile-time by a C preprocessor
  112077. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  112078. ** "_MAX_".)
  112079. */
  112080. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  112081. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  112082. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  112083. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  112084. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  112085. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  112086. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  112087. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  112088. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  112089. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  112090. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  112091. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  112092. assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
  112093. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  112094. return -1;
  112095. }
  112096. oldLimit = db->aLimit[limitId];
  112097. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  112098. if( newLimit>aHardLimit[limitId] ){
  112099. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  112100. }
  112101. db->aLimit[limitId] = newLimit;
  112102. }
  112103. return oldLimit; /* IMP: R-53341-35419 */
  112104. }
  112105. /*
  112106. ** This function is used to parse both URIs and non-URI filenames passed by the
  112107. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  112108. ** URIs specified as part of ATTACH statements.
  112109. **
  112110. ** The first argument to this function is the name of the VFS to use (or
  112111. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  112112. ** query parameter. The second argument contains the URI (or non-URI filename)
  112113. ** itself. When this function is called the *pFlags variable should contain
  112114. ** the default flags to open the database handle with. The value stored in
  112115. ** *pFlags may be updated before returning if the URI filename contains
  112116. ** "cache=xxx" or "mode=xxx" query parameters.
  112117. **
  112118. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  112119. ** the VFS that should be used to open the database file. *pzFile is set to
  112120. ** point to a buffer containing the name of the file to open. It is the
  112121. ** responsibility of the caller to eventually call sqlite3_free() to release
  112122. ** this buffer.
  112123. **
  112124. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  112125. ** may be set to point to a buffer containing an English language error
  112126. ** message. It is the responsibility of the caller to eventually release
  112127. ** this buffer by calling sqlite3_free().
  112128. */
  112129. SQLITE_PRIVATE int sqlite3ParseUri(
  112130. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  112131. const char *zUri, /* Nul-terminated URI to parse */
  112132. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  112133. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  112134. char **pzFile, /* OUT: Filename component of URI */
  112135. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  112136. ){
  112137. int rc = SQLITE_OK;
  112138. unsigned int flags = *pFlags;
  112139. const char *zVfs = zDefaultVfs;
  112140. char *zFile;
  112141. char c;
  112142. int nUri = sqlite3Strlen30(zUri);
  112143. assert( *pzErrMsg==0 );
  112144. if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
  112145. && nUri>=5 && memcmp(zUri, "file:", 5)==0
  112146. ){
  112147. char *zOpt;
  112148. int eState; /* Parser state when parsing URI */
  112149. int iIn; /* Input character index */
  112150. int iOut = 0; /* Output character index */
  112151. int nByte = nUri+2; /* Bytes of space to allocate */
  112152. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  112153. ** method that there may be extra parameters following the file-name. */
  112154. flags |= SQLITE_OPEN_URI;
  112155. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  112156. zFile = sqlite3_malloc(nByte);
  112157. if( !zFile ) return SQLITE_NOMEM;
  112158. iIn = 5;
  112159. #ifndef SQLITE_ALLOW_URI_AUTHORITY
  112160. /* Discard the scheme and authority segments of the URI. */
  112161. if( zUri[5]=='/' && zUri[6]=='/' ){
  112162. iIn = 7;
  112163. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  112164. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  112165. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  112166. iIn-7, &zUri[7]);
  112167. rc = SQLITE_ERROR;
  112168. goto parse_uri_out;
  112169. }
  112170. }
  112171. #endif
  112172. /* Copy the filename and any query parameters into the zFile buffer.
  112173. ** Decode %HH escape codes along the way.
  112174. **
  112175. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  112176. ** on the parsing context. As follows:
  112177. **
  112178. ** 0: Parsing file-name.
  112179. ** 1: Parsing name section of a name=value query parameter.
  112180. ** 2: Parsing value section of a name=value query parameter.
  112181. */
  112182. eState = 0;
  112183. while( (c = zUri[iIn])!=0 && c!='#' ){
  112184. iIn++;
  112185. if( c=='%'
  112186. && sqlite3Isxdigit(zUri[iIn])
  112187. && sqlite3Isxdigit(zUri[iIn+1])
  112188. ){
  112189. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  112190. octet += sqlite3HexToInt(zUri[iIn++]);
  112191. assert( octet>=0 && octet<256 );
  112192. if( octet==0 ){
  112193. /* This branch is taken when "%00" appears within the URI. In this
  112194. ** case we ignore all text in the remainder of the path, name or
  112195. ** value currently being parsed. So ignore the current character
  112196. ** and skip to the next "?", "=" or "&", as appropriate. */
  112197. while( (c = zUri[iIn])!=0 && c!='#'
  112198. && (eState!=0 || c!='?')
  112199. && (eState!=1 || (c!='=' && c!='&'))
  112200. && (eState!=2 || c!='&')
  112201. ){
  112202. iIn++;
  112203. }
  112204. continue;
  112205. }
  112206. c = octet;
  112207. }else if( eState==1 && (c=='&' || c=='=') ){
  112208. if( zFile[iOut-1]==0 ){
  112209. /* An empty option name. Ignore this option altogether. */
  112210. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  112211. continue;
  112212. }
  112213. if( c=='&' ){
  112214. zFile[iOut++] = '\0';
  112215. }else{
  112216. eState = 2;
  112217. }
  112218. c = 0;
  112219. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  112220. c = 0;
  112221. eState = 1;
  112222. }
  112223. zFile[iOut++] = c;
  112224. }
  112225. if( eState==1 ) zFile[iOut++] = '\0';
  112226. zFile[iOut++] = '\0';
  112227. zFile[iOut++] = '\0';
  112228. /* Check if there were any options specified that should be interpreted
  112229. ** here. Options that are interpreted here include "vfs" and those that
  112230. ** correspond to flags that may be passed to the sqlite3_open_v2()
  112231. ** method. */
  112232. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  112233. while( zOpt[0] ){
  112234. int nOpt = sqlite3Strlen30(zOpt);
  112235. char *zVal = &zOpt[nOpt+1];
  112236. int nVal = sqlite3Strlen30(zVal);
  112237. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  112238. zVfs = zVal;
  112239. }else{
  112240. struct OpenMode {
  112241. const char *z;
  112242. int mode;
  112243. } *aMode = 0;
  112244. char *zModeType = 0;
  112245. int mask = 0;
  112246. int limit = 0;
  112247. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  112248. static struct OpenMode aCacheMode[] = {
  112249. { "shared", SQLITE_OPEN_SHAREDCACHE },
  112250. { "private", SQLITE_OPEN_PRIVATECACHE },
  112251. { 0, 0 }
  112252. };
  112253. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  112254. aMode = aCacheMode;
  112255. limit = mask;
  112256. zModeType = "cache";
  112257. }
  112258. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  112259. static struct OpenMode aOpenMode[] = {
  112260. { "ro", SQLITE_OPEN_READONLY },
  112261. { "rw", SQLITE_OPEN_READWRITE },
  112262. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  112263. { "memory", SQLITE_OPEN_MEMORY },
  112264. { 0, 0 }
  112265. };
  112266. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  112267. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  112268. aMode = aOpenMode;
  112269. limit = mask & flags;
  112270. zModeType = "access";
  112271. }
  112272. if( aMode ){
  112273. int i;
  112274. int mode = 0;
  112275. for(i=0; aMode[i].z; i++){
  112276. const char *z = aMode[i].z;
  112277. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  112278. mode = aMode[i].mode;
  112279. break;
  112280. }
  112281. }
  112282. if( mode==0 ){
  112283. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  112284. rc = SQLITE_ERROR;
  112285. goto parse_uri_out;
  112286. }
  112287. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  112288. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  112289. zModeType, zVal);
  112290. rc = SQLITE_PERM;
  112291. goto parse_uri_out;
  112292. }
  112293. flags = (flags & ~mask) | mode;
  112294. }
  112295. }
  112296. zOpt = &zVal[nVal+1];
  112297. }
  112298. }else{
  112299. zFile = sqlite3_malloc(nUri+2);
  112300. if( !zFile ) return SQLITE_NOMEM;
  112301. memcpy(zFile, zUri, nUri);
  112302. zFile[nUri] = '\0';
  112303. zFile[nUri+1] = '\0';
  112304. flags &= ~SQLITE_OPEN_URI;
  112305. }
  112306. *ppVfs = sqlite3_vfs_find(zVfs);
  112307. if( *ppVfs==0 ){
  112308. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  112309. rc = SQLITE_ERROR;
  112310. }
  112311. parse_uri_out:
  112312. if( rc!=SQLITE_OK ){
  112313. sqlite3_free(zFile);
  112314. zFile = 0;
  112315. }
  112316. *pFlags = flags;
  112317. *pzFile = zFile;
  112318. return rc;
  112319. }
  112320. /*
  112321. ** This routine does the work of opening a database on behalf of
  112322. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  112323. ** is UTF-8 encoded.
  112324. */
  112325. static int openDatabase(
  112326. const char *zFilename, /* Database filename UTF-8 encoded */
  112327. sqlite3 **ppDb, /* OUT: Returned database handle */
  112328. unsigned int flags, /* Operational flags */
  112329. const char *zVfs /* Name of the VFS to use */
  112330. ){
  112331. sqlite3 *db; /* Store allocated handle here */
  112332. int rc; /* Return code */
  112333. int isThreadsafe; /* True for threadsafe connections */
  112334. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  112335. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  112336. *ppDb = 0;
  112337. #ifndef SQLITE_OMIT_AUTOINIT
  112338. rc = sqlite3_initialize();
  112339. if( rc ) return rc;
  112340. #endif
  112341. /* Only allow sensible combinations of bits in the flags argument.
  112342. ** Throw an error if any non-sense combination is used. If we
  112343. ** do not block illegal combinations here, it could trigger
  112344. ** assert() statements in deeper layers. Sensible combinations
  112345. ** are:
  112346. **
  112347. ** 1: SQLITE_OPEN_READONLY
  112348. ** 2: SQLITE_OPEN_READWRITE
  112349. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  112350. */
  112351. assert( SQLITE_OPEN_READONLY == 0x01 );
  112352. assert( SQLITE_OPEN_READWRITE == 0x02 );
  112353. assert( SQLITE_OPEN_CREATE == 0x04 );
  112354. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  112355. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  112356. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  112357. if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
  112358. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  112359. isThreadsafe = 0;
  112360. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  112361. isThreadsafe = 0;
  112362. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  112363. isThreadsafe = 1;
  112364. }else{
  112365. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  112366. }
  112367. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  112368. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  112369. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  112370. flags |= SQLITE_OPEN_SHAREDCACHE;
  112371. }
  112372. /* Remove harmful bits from the flags parameter
  112373. **
  112374. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  112375. ** dealt with in the previous code block. Besides these, the only
  112376. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  112377. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  112378. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  112379. ** off all other flags.
  112380. */
  112381. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  112382. SQLITE_OPEN_EXCLUSIVE |
  112383. SQLITE_OPEN_MAIN_DB |
  112384. SQLITE_OPEN_TEMP_DB |
  112385. SQLITE_OPEN_TRANSIENT_DB |
  112386. SQLITE_OPEN_MAIN_JOURNAL |
  112387. SQLITE_OPEN_TEMP_JOURNAL |
  112388. SQLITE_OPEN_SUBJOURNAL |
  112389. SQLITE_OPEN_MASTER_JOURNAL |
  112390. SQLITE_OPEN_NOMUTEX |
  112391. SQLITE_OPEN_FULLMUTEX |
  112392. SQLITE_OPEN_WAL
  112393. );
  112394. /* Allocate the sqlite data structure */
  112395. db = sqlite3MallocZero( sizeof(sqlite3) );
  112396. if( db==0 ) goto opendb_out;
  112397. if( isThreadsafe ){
  112398. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  112399. if( db->mutex==0 ){
  112400. sqlite3_free(db);
  112401. db = 0;
  112402. goto opendb_out;
  112403. }
  112404. }
  112405. sqlite3_mutex_enter(db->mutex);
  112406. db->errMask = 0xff;
  112407. db->nDb = 2;
  112408. db->magic = SQLITE_MAGIC_BUSY;
  112409. db->aDb = db->aDbStatic;
  112410. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  112411. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  112412. db->autoCommit = 1;
  112413. db->nextAutovac = -1;
  112414. db->szMmap = sqlite3GlobalConfig.szMmap;
  112415. db->nextPagesize = 0;
  112416. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  112417. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  112418. | SQLITE_AutoIndex
  112419. #endif
  112420. #if SQLITE_DEFAULT_FILE_FORMAT<4
  112421. | SQLITE_LegacyFileFmt
  112422. #endif
  112423. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  112424. | SQLITE_LoadExtension
  112425. #endif
  112426. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  112427. | SQLITE_RecTriggers
  112428. #endif
  112429. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  112430. | SQLITE_ForeignKeys
  112431. #endif
  112432. ;
  112433. sqlite3HashInit(&db->aCollSeq);
  112434. #ifndef SQLITE_OMIT_VIRTUALTABLE
  112435. sqlite3HashInit(&db->aModule);
  112436. #endif
  112437. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  112438. ** and UTF-16, so add a version for each to avoid any unnecessary
  112439. ** conversions. The only error that can occur here is a malloc() failure.
  112440. */
  112441. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  112442. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  112443. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  112444. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  112445. if( db->mallocFailed ){
  112446. goto opendb_out;
  112447. }
  112448. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  112449. assert( db->pDfltColl!=0 );
  112450. /* Also add a UTF-8 case-insensitive collation sequence. */
  112451. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  112452. /* Parse the filename/URI argument. */
  112453. db->openFlags = flags;
  112454. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  112455. if( rc!=SQLITE_OK ){
  112456. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  112457. sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  112458. sqlite3_free(zErrMsg);
  112459. goto opendb_out;
  112460. }
  112461. /* Open the backend database driver */
  112462. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  112463. flags | SQLITE_OPEN_MAIN_DB);
  112464. if( rc!=SQLITE_OK ){
  112465. if( rc==SQLITE_IOERR_NOMEM ){
  112466. rc = SQLITE_NOMEM;
  112467. }
  112468. sqlite3Error(db, rc, 0);
  112469. goto opendb_out;
  112470. }
  112471. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  112472. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  112473. /* The default safety_level for the main database is 'full'; for the temp
  112474. ** database it is 'NONE'. This matches the pager layer defaults.
  112475. */
  112476. db->aDb[0].zName = "main";
  112477. db->aDb[0].safety_level = 3;
  112478. db->aDb[1].zName = "temp";
  112479. db->aDb[1].safety_level = 1;
  112480. db->magic = SQLITE_MAGIC_OPEN;
  112481. if( db->mallocFailed ){
  112482. goto opendb_out;
  112483. }
  112484. /* Register all built-in functions, but do not attempt to read the
  112485. ** database schema yet. This is delayed until the first time the database
  112486. ** is accessed.
  112487. */
  112488. sqlite3Error(db, SQLITE_OK, 0);
  112489. sqlite3RegisterBuiltinFunctions(db);
  112490. /* Load automatic extensions - extensions that have been registered
  112491. ** using the sqlite3_automatic_extension() API.
  112492. */
  112493. rc = sqlite3_errcode(db);
  112494. if( rc==SQLITE_OK ){
  112495. sqlite3AutoLoadExtensions(db);
  112496. rc = sqlite3_errcode(db);
  112497. if( rc!=SQLITE_OK ){
  112498. goto opendb_out;
  112499. }
  112500. }
  112501. #ifdef SQLITE_ENABLE_FTS1
  112502. if( !db->mallocFailed ){
  112503. extern int sqlite3Fts1Init(sqlite3*);
  112504. rc = sqlite3Fts1Init(db);
  112505. }
  112506. #endif
  112507. #ifdef SQLITE_ENABLE_FTS2
  112508. if( !db->mallocFailed && rc==SQLITE_OK ){
  112509. extern int sqlite3Fts2Init(sqlite3*);
  112510. rc = sqlite3Fts2Init(db);
  112511. }
  112512. #endif
  112513. #ifdef SQLITE_ENABLE_FTS3
  112514. if( !db->mallocFailed && rc==SQLITE_OK ){
  112515. rc = sqlite3Fts3Init(db);
  112516. }
  112517. #endif
  112518. #ifdef SQLITE_ENABLE_ICU
  112519. if( !db->mallocFailed && rc==SQLITE_OK ){
  112520. rc = sqlite3IcuInit(db);
  112521. }
  112522. #endif
  112523. #ifdef SQLITE_ENABLE_RTREE
  112524. if( !db->mallocFailed && rc==SQLITE_OK){
  112525. rc = sqlite3RtreeInit(db);
  112526. }
  112527. #endif
  112528. sqlite3Error(db, rc, 0);
  112529. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  112530. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  112531. ** mode. Doing nothing at all also makes NORMAL the default.
  112532. */
  112533. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  112534. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  112535. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  112536. SQLITE_DEFAULT_LOCKING_MODE);
  112537. #endif
  112538. /* Enable the lookaside-malloc subsystem */
  112539. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  112540. sqlite3GlobalConfig.nLookaside);
  112541. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  112542. opendb_out:
  112543. sqlite3_free(zOpen);
  112544. if( db ){
  112545. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  112546. sqlite3_mutex_leave(db->mutex);
  112547. }
  112548. rc = sqlite3_errcode(db);
  112549. assert( db!=0 || rc==SQLITE_NOMEM );
  112550. if( rc==SQLITE_NOMEM ){
  112551. sqlite3_close(db);
  112552. db = 0;
  112553. }else if( rc!=SQLITE_OK ){
  112554. db->magic = SQLITE_MAGIC_SICK;
  112555. }
  112556. *ppDb = db;
  112557. #ifdef SQLITE_ENABLE_SQLLOG
  112558. if( sqlite3GlobalConfig.xSqllog ){
  112559. /* Opening a db handle. Fourth parameter is passed 0. */
  112560. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  112561. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  112562. }
  112563. #endif
  112564. return sqlite3ApiExit(0, rc);
  112565. }
  112566. /*
  112567. ** Open a new database handle.
  112568. */
  112569. SQLITE_API int sqlite3_open(
  112570. const char *zFilename,
  112571. sqlite3 **ppDb
  112572. ){
  112573. return openDatabase(zFilename, ppDb,
  112574. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  112575. }
  112576. SQLITE_API int sqlite3_open_v2(
  112577. const char *filename, /* Database filename (UTF-8) */
  112578. sqlite3 **ppDb, /* OUT: SQLite db handle */
  112579. int flags, /* Flags */
  112580. const char *zVfs /* Name of VFS module to use */
  112581. ){
  112582. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  112583. }
  112584. #ifndef SQLITE_OMIT_UTF16
  112585. /*
  112586. ** Open a new database handle.
  112587. */
  112588. SQLITE_API int sqlite3_open16(
  112589. const void *zFilename,
  112590. sqlite3 **ppDb
  112591. ){
  112592. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  112593. sqlite3_value *pVal;
  112594. int rc;
  112595. assert( zFilename );
  112596. assert( ppDb );
  112597. *ppDb = 0;
  112598. #ifndef SQLITE_OMIT_AUTOINIT
  112599. rc = sqlite3_initialize();
  112600. if( rc ) return rc;
  112601. #endif
  112602. pVal = sqlite3ValueNew(0);
  112603. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  112604. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  112605. if( zFilename8 ){
  112606. rc = openDatabase(zFilename8, ppDb,
  112607. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  112608. assert( *ppDb || rc==SQLITE_NOMEM );
  112609. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  112610. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  112611. }
  112612. }else{
  112613. rc = SQLITE_NOMEM;
  112614. }
  112615. sqlite3ValueFree(pVal);
  112616. return sqlite3ApiExit(0, rc);
  112617. }
  112618. #endif /* SQLITE_OMIT_UTF16 */
  112619. /*
  112620. ** Register a new collation sequence with the database handle db.
  112621. */
  112622. SQLITE_API int sqlite3_create_collation(
  112623. sqlite3* db,
  112624. const char *zName,
  112625. int enc,
  112626. void* pCtx,
  112627. int(*xCompare)(void*,int,const void*,int,const void*)
  112628. ){
  112629. int rc;
  112630. sqlite3_mutex_enter(db->mutex);
  112631. assert( !db->mallocFailed );
  112632. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
  112633. rc = sqlite3ApiExit(db, rc);
  112634. sqlite3_mutex_leave(db->mutex);
  112635. return rc;
  112636. }
  112637. /*
  112638. ** Register a new collation sequence with the database handle db.
  112639. */
  112640. SQLITE_API int sqlite3_create_collation_v2(
  112641. sqlite3* db,
  112642. const char *zName,
  112643. int enc,
  112644. void* pCtx,
  112645. int(*xCompare)(void*,int,const void*,int,const void*),
  112646. void(*xDel)(void*)
  112647. ){
  112648. int rc;
  112649. sqlite3_mutex_enter(db->mutex);
  112650. assert( !db->mallocFailed );
  112651. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  112652. rc = sqlite3ApiExit(db, rc);
  112653. sqlite3_mutex_leave(db->mutex);
  112654. return rc;
  112655. }
  112656. #ifndef SQLITE_OMIT_UTF16
  112657. /*
  112658. ** Register a new collation sequence with the database handle db.
  112659. */
  112660. SQLITE_API int sqlite3_create_collation16(
  112661. sqlite3* db,
  112662. const void *zName,
  112663. int enc,
  112664. void* pCtx,
  112665. int(*xCompare)(void*,int,const void*,int,const void*)
  112666. ){
  112667. int rc = SQLITE_OK;
  112668. char *zName8;
  112669. sqlite3_mutex_enter(db->mutex);
  112670. assert( !db->mallocFailed );
  112671. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  112672. if( zName8 ){
  112673. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  112674. sqlite3DbFree(db, zName8);
  112675. }
  112676. rc = sqlite3ApiExit(db, rc);
  112677. sqlite3_mutex_leave(db->mutex);
  112678. return rc;
  112679. }
  112680. #endif /* SQLITE_OMIT_UTF16 */
  112681. /*
  112682. ** Register a collation sequence factory callback with the database handle
  112683. ** db. Replace any previously installed collation sequence factory.
  112684. */
  112685. SQLITE_API int sqlite3_collation_needed(
  112686. sqlite3 *db,
  112687. void *pCollNeededArg,
  112688. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  112689. ){
  112690. sqlite3_mutex_enter(db->mutex);
  112691. db->xCollNeeded = xCollNeeded;
  112692. db->xCollNeeded16 = 0;
  112693. db->pCollNeededArg = pCollNeededArg;
  112694. sqlite3_mutex_leave(db->mutex);
  112695. return SQLITE_OK;
  112696. }
  112697. #ifndef SQLITE_OMIT_UTF16
  112698. /*
  112699. ** Register a collation sequence factory callback with the database handle
  112700. ** db. Replace any previously installed collation sequence factory.
  112701. */
  112702. SQLITE_API int sqlite3_collation_needed16(
  112703. sqlite3 *db,
  112704. void *pCollNeededArg,
  112705. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  112706. ){
  112707. sqlite3_mutex_enter(db->mutex);
  112708. db->xCollNeeded = 0;
  112709. db->xCollNeeded16 = xCollNeeded16;
  112710. db->pCollNeededArg = pCollNeededArg;
  112711. sqlite3_mutex_leave(db->mutex);
  112712. return SQLITE_OK;
  112713. }
  112714. #endif /* SQLITE_OMIT_UTF16 */
  112715. #ifndef SQLITE_OMIT_DEPRECATED
  112716. /*
  112717. ** This function is now an anachronism. It used to be used to recover from a
  112718. ** malloc() failure, but SQLite now does this automatically.
  112719. */
  112720. SQLITE_API int sqlite3_global_recover(void){
  112721. return SQLITE_OK;
  112722. }
  112723. #endif
  112724. /*
  112725. ** Test to see whether or not the database connection is in autocommit
  112726. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  112727. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  112728. ** by the next COMMIT or ROLLBACK.
  112729. */
  112730. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  112731. return db->autoCommit;
  112732. }
  112733. /*
  112734. ** The following routines are subtitutes for constants SQLITE_CORRUPT,
  112735. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  112736. ** constants. They server two purposes:
  112737. **
  112738. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  112739. ** to detect when version error conditions occurs.
  112740. **
  112741. ** 2. Invoke sqlite3_log() to provide the source code location where
  112742. ** a low-level error is first detected.
  112743. */
  112744. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  112745. testcase( sqlite3GlobalConfig.xLog!=0 );
  112746. sqlite3_log(SQLITE_CORRUPT,
  112747. "database corruption at line %d of [%.10s]",
  112748. lineno, 20+sqlite3_sourceid());
  112749. return SQLITE_CORRUPT;
  112750. }
  112751. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  112752. testcase( sqlite3GlobalConfig.xLog!=0 );
  112753. sqlite3_log(SQLITE_MISUSE,
  112754. "misuse at line %d of [%.10s]",
  112755. lineno, 20+sqlite3_sourceid());
  112756. return SQLITE_MISUSE;
  112757. }
  112758. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  112759. testcase( sqlite3GlobalConfig.xLog!=0 );
  112760. sqlite3_log(SQLITE_CANTOPEN,
  112761. "cannot open file at line %d of [%.10s]",
  112762. lineno, 20+sqlite3_sourceid());
  112763. return SQLITE_CANTOPEN;
  112764. }
  112765. #ifndef SQLITE_OMIT_DEPRECATED
  112766. /*
  112767. ** This is a convenience routine that makes sure that all thread-specific
  112768. ** data for this thread has been deallocated.
  112769. **
  112770. ** SQLite no longer uses thread-specific data so this routine is now a
  112771. ** no-op. It is retained for historical compatibility.
  112772. */
  112773. SQLITE_API void sqlite3_thread_cleanup(void){
  112774. }
  112775. #endif
  112776. /*
  112777. ** Return meta information about a specific column of a database table.
  112778. ** See comment in sqlite3.h (sqlite.h.in) for details.
  112779. */
  112780. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  112781. SQLITE_API int sqlite3_table_column_metadata(
  112782. sqlite3 *db, /* Connection handle */
  112783. const char *zDbName, /* Database name or NULL */
  112784. const char *zTableName, /* Table name */
  112785. const char *zColumnName, /* Column name */
  112786. char const **pzDataType, /* OUTPUT: Declared data type */
  112787. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  112788. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  112789. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  112790. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  112791. ){
  112792. int rc;
  112793. char *zErrMsg = 0;
  112794. Table *pTab = 0;
  112795. Column *pCol = 0;
  112796. int iCol;
  112797. char const *zDataType = 0;
  112798. char const *zCollSeq = 0;
  112799. int notnull = 0;
  112800. int primarykey = 0;
  112801. int autoinc = 0;
  112802. /* Ensure the database schema has been loaded */
  112803. sqlite3_mutex_enter(db->mutex);
  112804. sqlite3BtreeEnterAll(db);
  112805. rc = sqlite3Init(db, &zErrMsg);
  112806. if( SQLITE_OK!=rc ){
  112807. goto error_out;
  112808. }
  112809. /* Locate the table in question */
  112810. pTab = sqlite3FindTable(db, zTableName, zDbName);
  112811. if( !pTab || pTab->pSelect ){
  112812. pTab = 0;
  112813. goto error_out;
  112814. }
  112815. /* Find the column for which info is requested */
  112816. if( sqlite3IsRowid(zColumnName) ){
  112817. iCol = pTab->iPKey;
  112818. if( iCol>=0 ){
  112819. pCol = &pTab->aCol[iCol];
  112820. }
  112821. }else{
  112822. for(iCol=0; iCol<pTab->nCol; iCol++){
  112823. pCol = &pTab->aCol[iCol];
  112824. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  112825. break;
  112826. }
  112827. }
  112828. if( iCol==pTab->nCol ){
  112829. pTab = 0;
  112830. goto error_out;
  112831. }
  112832. }
  112833. /* The following block stores the meta information that will be returned
  112834. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  112835. ** and autoinc. At this point there are two possibilities:
  112836. **
  112837. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  112838. ** and there is no explicitly declared IPK column.
  112839. **
  112840. ** 2. The table is not a view and the column name identified an
  112841. ** explicitly declared column. Copy meta information from *pCol.
  112842. */
  112843. if( pCol ){
  112844. zDataType = pCol->zType;
  112845. zCollSeq = pCol->zColl;
  112846. notnull = pCol->notNull!=0;
  112847. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  112848. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  112849. }else{
  112850. zDataType = "INTEGER";
  112851. primarykey = 1;
  112852. }
  112853. if( !zCollSeq ){
  112854. zCollSeq = "BINARY";
  112855. }
  112856. error_out:
  112857. sqlite3BtreeLeaveAll(db);
  112858. /* Whether the function call succeeded or failed, set the output parameters
  112859. ** to whatever their local counterparts contain. If an error did occur,
  112860. ** this has the effect of zeroing all output parameters.
  112861. */
  112862. if( pzDataType ) *pzDataType = zDataType;
  112863. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  112864. if( pNotNull ) *pNotNull = notnull;
  112865. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  112866. if( pAutoinc ) *pAutoinc = autoinc;
  112867. if( SQLITE_OK==rc && !pTab ){
  112868. sqlite3DbFree(db, zErrMsg);
  112869. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  112870. zColumnName);
  112871. rc = SQLITE_ERROR;
  112872. }
  112873. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  112874. sqlite3DbFree(db, zErrMsg);
  112875. rc = sqlite3ApiExit(db, rc);
  112876. sqlite3_mutex_leave(db->mutex);
  112877. return rc;
  112878. }
  112879. #endif
  112880. /*
  112881. ** Sleep for a little while. Return the amount of time slept.
  112882. */
  112883. SQLITE_API int sqlite3_sleep(int ms){
  112884. sqlite3_vfs *pVfs;
  112885. int rc;
  112886. pVfs = sqlite3_vfs_find(0);
  112887. if( pVfs==0 ) return 0;
  112888. /* This function works in milliseconds, but the underlying OsSleep()
  112889. ** API uses microseconds. Hence the 1000's.
  112890. */
  112891. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  112892. return rc;
  112893. }
  112894. /*
  112895. ** Enable or disable the extended result codes.
  112896. */
  112897. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  112898. sqlite3_mutex_enter(db->mutex);
  112899. db->errMask = onoff ? 0xffffffff : 0xff;
  112900. sqlite3_mutex_leave(db->mutex);
  112901. return SQLITE_OK;
  112902. }
  112903. /*
  112904. ** Invoke the xFileControl method on a particular database.
  112905. */
  112906. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  112907. int rc = SQLITE_ERROR;
  112908. Btree *pBtree;
  112909. sqlite3_mutex_enter(db->mutex);
  112910. pBtree = sqlite3DbNameToBtree(db, zDbName);
  112911. if( pBtree ){
  112912. Pager *pPager;
  112913. sqlite3_file *fd;
  112914. sqlite3BtreeEnter(pBtree);
  112915. pPager = sqlite3BtreePager(pBtree);
  112916. assert( pPager!=0 );
  112917. fd = sqlite3PagerFile(pPager);
  112918. assert( fd!=0 );
  112919. if( op==SQLITE_FCNTL_FILE_POINTER ){
  112920. *(sqlite3_file**)pArg = fd;
  112921. rc = SQLITE_OK;
  112922. }else if( fd->pMethods ){
  112923. rc = sqlite3OsFileControl(fd, op, pArg);
  112924. }else{
  112925. rc = SQLITE_NOTFOUND;
  112926. }
  112927. sqlite3BtreeLeave(pBtree);
  112928. }
  112929. sqlite3_mutex_leave(db->mutex);
  112930. return rc;
  112931. }
  112932. /*
  112933. ** Interface to the testing logic.
  112934. */
  112935. SQLITE_API int sqlite3_test_control(int op, ...){
  112936. int rc = 0;
  112937. #ifndef SQLITE_OMIT_BUILTIN_TEST
  112938. va_list ap;
  112939. va_start(ap, op);
  112940. switch( op ){
  112941. /*
  112942. ** Save the current state of the PRNG.
  112943. */
  112944. case SQLITE_TESTCTRL_PRNG_SAVE: {
  112945. sqlite3PrngSaveState();
  112946. break;
  112947. }
  112948. /*
  112949. ** Restore the state of the PRNG to the last state saved using
  112950. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  112951. ** this verb acts like PRNG_RESET.
  112952. */
  112953. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  112954. sqlite3PrngRestoreState();
  112955. break;
  112956. }
  112957. /*
  112958. ** Reset the PRNG back to its uninitialized state. The next call
  112959. ** to sqlite3_randomness() will reseed the PRNG using a single call
  112960. ** to the xRandomness method of the default VFS.
  112961. */
  112962. case SQLITE_TESTCTRL_PRNG_RESET: {
  112963. sqlite3PrngResetState();
  112964. break;
  112965. }
  112966. /*
  112967. ** sqlite3_test_control(BITVEC_TEST, size, program)
  112968. **
  112969. ** Run a test against a Bitvec object of size. The program argument
  112970. ** is an array of integers that defines the test. Return -1 on a
  112971. ** memory allocation error, 0 on success, or non-zero for an error.
  112972. ** See the sqlite3BitvecBuiltinTest() for additional information.
  112973. */
  112974. case SQLITE_TESTCTRL_BITVEC_TEST: {
  112975. int sz = va_arg(ap, int);
  112976. int *aProg = va_arg(ap, int*);
  112977. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  112978. break;
  112979. }
  112980. /*
  112981. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  112982. **
  112983. ** Register hooks to call to indicate which malloc() failures
  112984. ** are benign.
  112985. */
  112986. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  112987. typedef void (*void_function)(void);
  112988. void_function xBenignBegin;
  112989. void_function xBenignEnd;
  112990. xBenignBegin = va_arg(ap, void_function);
  112991. xBenignEnd = va_arg(ap, void_function);
  112992. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  112993. break;
  112994. }
  112995. /*
  112996. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  112997. **
  112998. ** Set the PENDING byte to the value in the argument, if X>0.
  112999. ** Make no changes if X==0. Return the value of the pending byte
  113000. ** as it existing before this routine was called.
  113001. **
  113002. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  113003. ** an incompatible database file format. Changing the PENDING byte
  113004. ** while any database connection is open results in undefined and
  113005. ** dileterious behavior.
  113006. */
  113007. case SQLITE_TESTCTRL_PENDING_BYTE: {
  113008. rc = PENDING_BYTE;
  113009. #ifndef SQLITE_OMIT_WSD
  113010. {
  113011. unsigned int newVal = va_arg(ap, unsigned int);
  113012. if( newVal ) sqlite3PendingByte = newVal;
  113013. }
  113014. #endif
  113015. break;
  113016. }
  113017. /*
  113018. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  113019. **
  113020. ** This action provides a run-time test to see whether or not
  113021. ** assert() was enabled at compile-time. If X is true and assert()
  113022. ** is enabled, then the return value is true. If X is true and
  113023. ** assert() is disabled, then the return value is zero. If X is
  113024. ** false and assert() is enabled, then the assertion fires and the
  113025. ** process aborts. If X is false and assert() is disabled, then the
  113026. ** return value is zero.
  113027. */
  113028. case SQLITE_TESTCTRL_ASSERT: {
  113029. volatile int x = 0;
  113030. assert( (x = va_arg(ap,int))!=0 );
  113031. rc = x;
  113032. break;
  113033. }
  113034. /*
  113035. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  113036. **
  113037. ** This action provides a run-time test to see how the ALWAYS and
  113038. ** NEVER macros were defined at compile-time.
  113039. **
  113040. ** The return value is ALWAYS(X).
  113041. **
  113042. ** The recommended test is X==2. If the return value is 2, that means
  113043. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  113044. ** default setting. If the return value is 1, then ALWAYS() is either
  113045. ** hard-coded to true or else it asserts if its argument is false.
  113046. ** The first behavior (hard-coded to true) is the case if
  113047. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  113048. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  113049. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  113050. **
  113051. ** The run-time test procedure might look something like this:
  113052. **
  113053. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  113054. ** // ALWAYS() and NEVER() are no-op pass-through macros
  113055. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  113056. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  113057. ** }else{
  113058. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  113059. ** }
  113060. */
  113061. case SQLITE_TESTCTRL_ALWAYS: {
  113062. int x = va_arg(ap,int);
  113063. rc = ALWAYS(x);
  113064. break;
  113065. }
  113066. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  113067. **
  113068. ** Set the nReserve size to N for the main database on the database
  113069. ** connection db.
  113070. */
  113071. case SQLITE_TESTCTRL_RESERVE: {
  113072. sqlite3 *db = va_arg(ap, sqlite3*);
  113073. int x = va_arg(ap,int);
  113074. sqlite3_mutex_enter(db->mutex);
  113075. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  113076. sqlite3_mutex_leave(db->mutex);
  113077. break;
  113078. }
  113079. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  113080. **
  113081. ** Enable or disable various optimizations for testing purposes. The
  113082. ** argument N is a bitmask of optimizations to be disabled. For normal
  113083. ** operation N should be 0. The idea is that a test program (like the
  113084. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  113085. ** with various optimizations disabled to verify that the same answer
  113086. ** is obtained in every case.
  113087. */
  113088. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  113089. sqlite3 *db = va_arg(ap, sqlite3*);
  113090. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  113091. break;
  113092. }
  113093. #ifdef SQLITE_N_KEYWORD
  113094. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  113095. **
  113096. ** If zWord is a keyword recognized by the parser, then return the
  113097. ** number of keywords. Or if zWord is not a keyword, return 0.
  113098. **
  113099. ** This test feature is only available in the amalgamation since
  113100. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  113101. ** is built using separate source files.
  113102. */
  113103. case SQLITE_TESTCTRL_ISKEYWORD: {
  113104. const char *zWord = va_arg(ap, const char*);
  113105. int n = sqlite3Strlen30(zWord);
  113106. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  113107. break;
  113108. }
  113109. #endif
  113110. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  113111. **
  113112. ** Pass pFree into sqlite3ScratchFree().
  113113. ** If sz>0 then allocate a scratch buffer into pNew.
  113114. */
  113115. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  113116. void *pFree, **ppNew;
  113117. int sz;
  113118. sz = va_arg(ap, int);
  113119. ppNew = va_arg(ap, void**);
  113120. pFree = va_arg(ap, void*);
  113121. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  113122. sqlite3ScratchFree(pFree);
  113123. break;
  113124. }
  113125. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  113126. **
  113127. ** If parameter onoff is non-zero, configure the wrappers so that all
  113128. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  113129. ** undo this setting.
  113130. */
  113131. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  113132. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  113133. break;
  113134. }
  113135. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  113136. /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
  113137. ** sqlite3_stmt*,const char**);
  113138. **
  113139. ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
  113140. ** a string that describes the optimized parse tree. This test-control
  113141. ** returns a pointer to that string.
  113142. */
  113143. case SQLITE_TESTCTRL_EXPLAIN_STMT: {
  113144. sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
  113145. const char **pzRet = va_arg(ap, const char**);
  113146. *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
  113147. break;
  113148. }
  113149. #endif
  113150. }
  113151. va_end(ap);
  113152. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  113153. return rc;
  113154. }
  113155. /*
  113156. ** This is a utility routine, useful to VFS implementations, that checks
  113157. ** to see if a database file was a URI that contained a specific query
  113158. ** parameter, and if so obtains the value of the query parameter.
  113159. **
  113160. ** The zFilename argument is the filename pointer passed into the xOpen()
  113161. ** method of a VFS implementation. The zParam argument is the name of the
  113162. ** query parameter we seek. This routine returns the value of the zParam
  113163. ** parameter if it exists. If the parameter does not exist, this routine
  113164. ** returns a NULL pointer.
  113165. */
  113166. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  113167. if( zFilename==0 ) return 0;
  113168. zFilename += sqlite3Strlen30(zFilename) + 1;
  113169. while( zFilename[0] ){
  113170. int x = strcmp(zFilename, zParam);
  113171. zFilename += sqlite3Strlen30(zFilename) + 1;
  113172. if( x==0 ) return zFilename;
  113173. zFilename += sqlite3Strlen30(zFilename) + 1;
  113174. }
  113175. return 0;
  113176. }
  113177. /*
  113178. ** Return a boolean value for a query parameter.
  113179. */
  113180. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  113181. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  113182. bDflt = bDflt!=0;
  113183. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  113184. }
  113185. /*
  113186. ** Return a 64-bit integer value for a query parameter.
  113187. */
  113188. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  113189. const char *zFilename, /* Filename as passed to xOpen */
  113190. const char *zParam, /* URI parameter sought */
  113191. sqlite3_int64 bDflt /* return if parameter is missing */
  113192. ){
  113193. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  113194. sqlite3_int64 v;
  113195. if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
  113196. bDflt = v;
  113197. }
  113198. return bDflt;
  113199. }
  113200. /*
  113201. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  113202. */
  113203. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  113204. int i;
  113205. for(i=0; i<db->nDb; i++){
  113206. if( db->aDb[i].pBt
  113207. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  113208. ){
  113209. return db->aDb[i].pBt;
  113210. }
  113211. }
  113212. return 0;
  113213. }
  113214. /*
  113215. ** Return the filename of the database associated with a database
  113216. ** connection.
  113217. */
  113218. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  113219. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  113220. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  113221. }
  113222. /*
  113223. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  113224. ** no such database exists.
  113225. */
  113226. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  113227. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  113228. return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
  113229. }
  113230. /************** End of main.c ************************************************/
  113231. /************** Begin file notify.c ******************************************/
  113232. /*
  113233. ** 2009 March 3
  113234. **
  113235. ** The author disclaims copyright to this source code. In place of
  113236. ** a legal notice, here is a blessing:
  113237. **
  113238. ** May you do good and not evil.
  113239. ** May you find forgiveness for yourself and forgive others.
  113240. ** May you share freely, never taking more than you give.
  113241. **
  113242. *************************************************************************
  113243. **
  113244. ** This file contains the implementation of the sqlite3_unlock_notify()
  113245. ** API method and its associated functionality.
  113246. */
  113247. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  113248. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  113249. /*
  113250. ** Public interfaces:
  113251. **
  113252. ** sqlite3ConnectionBlocked()
  113253. ** sqlite3ConnectionUnlocked()
  113254. ** sqlite3ConnectionClosed()
  113255. ** sqlite3_unlock_notify()
  113256. */
  113257. #define assertMutexHeld() \
  113258. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  113259. /*
  113260. ** Head of a linked list of all sqlite3 objects created by this process
  113261. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  113262. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  113263. ** mutex is held.
  113264. */
  113265. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  113266. #ifndef NDEBUG
  113267. /*
  113268. ** This function is a complex assert() that verifies the following
  113269. ** properties of the blocked connections list:
  113270. **
  113271. ** 1) Each entry in the list has a non-NULL value for either
  113272. ** pUnlockConnection or pBlockingConnection, or both.
  113273. **
  113274. ** 2) All entries in the list that share a common value for
  113275. ** xUnlockNotify are grouped together.
  113276. **
  113277. ** 3) If the argument db is not NULL, then none of the entries in the
  113278. ** blocked connections list have pUnlockConnection or pBlockingConnection
  113279. ** set to db. This is used when closing connection db.
  113280. */
  113281. static void checkListProperties(sqlite3 *db){
  113282. sqlite3 *p;
  113283. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  113284. int seen = 0;
  113285. sqlite3 *p2;
  113286. /* Verify property (1) */
  113287. assert( p->pUnlockConnection || p->pBlockingConnection );
  113288. /* Verify property (2) */
  113289. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  113290. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  113291. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  113292. assert( db==0 || p->pUnlockConnection!=db );
  113293. assert( db==0 || p->pBlockingConnection!=db );
  113294. }
  113295. }
  113296. }
  113297. #else
  113298. # define checkListProperties(x)
  113299. #endif
  113300. /*
  113301. ** Remove connection db from the blocked connections list. If connection
  113302. ** db is not currently a part of the list, this function is a no-op.
  113303. */
  113304. static void removeFromBlockedList(sqlite3 *db){
  113305. sqlite3 **pp;
  113306. assertMutexHeld();
  113307. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  113308. if( *pp==db ){
  113309. *pp = (*pp)->pNextBlocked;
  113310. break;
  113311. }
  113312. }
  113313. }
  113314. /*
  113315. ** Add connection db to the blocked connections list. It is assumed
  113316. ** that it is not already a part of the list.
  113317. */
  113318. static void addToBlockedList(sqlite3 *db){
  113319. sqlite3 **pp;
  113320. assertMutexHeld();
  113321. for(
  113322. pp=&sqlite3BlockedList;
  113323. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  113324. pp=&(*pp)->pNextBlocked
  113325. );
  113326. db->pNextBlocked = *pp;
  113327. *pp = db;
  113328. }
  113329. /*
  113330. ** Obtain the STATIC_MASTER mutex.
  113331. */
  113332. static void enterMutex(void){
  113333. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  113334. checkListProperties(0);
  113335. }
  113336. /*
  113337. ** Release the STATIC_MASTER mutex.
  113338. */
  113339. static void leaveMutex(void){
  113340. assertMutexHeld();
  113341. checkListProperties(0);
  113342. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  113343. }
  113344. /*
  113345. ** Register an unlock-notify callback.
  113346. **
  113347. ** This is called after connection "db" has attempted some operation
  113348. ** but has received an SQLITE_LOCKED error because another connection
  113349. ** (call it pOther) in the same process was busy using the same shared
  113350. ** cache. pOther is found by looking at db->pBlockingConnection.
  113351. **
  113352. ** If there is no blocking connection, the callback is invoked immediately,
  113353. ** before this routine returns.
  113354. **
  113355. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  113356. ** a deadlock.
  113357. **
  113358. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  113359. ** its locks.
  113360. **
  113361. ** Each call to this routine overrides any prior callbacks registered
  113362. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  113363. ** cancelled.
  113364. */
  113365. SQLITE_API int sqlite3_unlock_notify(
  113366. sqlite3 *db,
  113367. void (*xNotify)(void **, int),
  113368. void *pArg
  113369. ){
  113370. int rc = SQLITE_OK;
  113371. sqlite3_mutex_enter(db->mutex);
  113372. enterMutex();
  113373. if( xNotify==0 ){
  113374. removeFromBlockedList(db);
  113375. db->pBlockingConnection = 0;
  113376. db->pUnlockConnection = 0;
  113377. db->xUnlockNotify = 0;
  113378. db->pUnlockArg = 0;
  113379. }else if( 0==db->pBlockingConnection ){
  113380. /* The blocking transaction has been concluded. Or there never was a
  113381. ** blocking transaction. In either case, invoke the notify callback
  113382. ** immediately.
  113383. */
  113384. xNotify(&pArg, 1);
  113385. }else{
  113386. sqlite3 *p;
  113387. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  113388. if( p ){
  113389. rc = SQLITE_LOCKED; /* Deadlock detected. */
  113390. }else{
  113391. db->pUnlockConnection = db->pBlockingConnection;
  113392. db->xUnlockNotify = xNotify;
  113393. db->pUnlockArg = pArg;
  113394. removeFromBlockedList(db);
  113395. addToBlockedList(db);
  113396. }
  113397. }
  113398. leaveMutex();
  113399. assert( !db->mallocFailed );
  113400. sqlite3Error(db, rc, (rc?"database is deadlocked":0));
  113401. sqlite3_mutex_leave(db->mutex);
  113402. return rc;
  113403. }
  113404. /*
  113405. ** This function is called while stepping or preparing a statement
  113406. ** associated with connection db. The operation will return SQLITE_LOCKED
  113407. ** to the user because it requires a lock that will not be available
  113408. ** until connection pBlocker concludes its current transaction.
  113409. */
  113410. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  113411. enterMutex();
  113412. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  113413. addToBlockedList(db);
  113414. }
  113415. db->pBlockingConnection = pBlocker;
  113416. leaveMutex();
  113417. }
  113418. /*
  113419. ** This function is called when
  113420. ** the transaction opened by database db has just finished. Locks held
  113421. ** by database connection db have been released.
  113422. **
  113423. ** This function loops through each entry in the blocked connections
  113424. ** list and does the following:
  113425. **
  113426. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  113427. ** set to db, then set pBlockingConnection=0.
  113428. **
  113429. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  113430. ** set to db, then invoke the configured unlock-notify callback and
  113431. ** set pUnlockConnection=0.
  113432. **
  113433. ** 3) If the two steps above mean that pBlockingConnection==0 and
  113434. ** pUnlockConnection==0, remove the entry from the blocked connections
  113435. ** list.
  113436. */
  113437. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  113438. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  113439. int nArg = 0; /* Number of entries in aArg[] */
  113440. sqlite3 **pp; /* Iterator variable */
  113441. void **aArg; /* Arguments to the unlock callback */
  113442. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  113443. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  113444. aArg = aStatic;
  113445. enterMutex(); /* Enter STATIC_MASTER mutex */
  113446. /* This loop runs once for each entry in the blocked-connections list. */
  113447. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  113448. sqlite3 *p = *pp;
  113449. /* Step 1. */
  113450. if( p->pBlockingConnection==db ){
  113451. p->pBlockingConnection = 0;
  113452. }
  113453. /* Step 2. */
  113454. if( p->pUnlockConnection==db ){
  113455. assert( p->xUnlockNotify );
  113456. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  113457. xUnlockNotify(aArg, nArg);
  113458. nArg = 0;
  113459. }
  113460. sqlite3BeginBenignMalloc();
  113461. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  113462. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  113463. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  113464. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  113465. ){
  113466. /* The aArg[] array needs to grow. */
  113467. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  113468. if( pNew ){
  113469. memcpy(pNew, aArg, nArg*sizeof(void *));
  113470. sqlite3_free(aDyn);
  113471. aDyn = aArg = pNew;
  113472. }else{
  113473. /* This occurs when the array of context pointers that need to
  113474. ** be passed to the unlock-notify callback is larger than the
  113475. ** aStatic[] array allocated on the stack and the attempt to
  113476. ** allocate a larger array from the heap has failed.
  113477. **
  113478. ** This is a difficult situation to handle. Returning an error
  113479. ** code to the caller is insufficient, as even if an error code
  113480. ** is returned the transaction on connection db will still be
  113481. ** closed and the unlock-notify callbacks on blocked connections
  113482. ** will go unissued. This might cause the application to wait
  113483. ** indefinitely for an unlock-notify callback that will never
  113484. ** arrive.
  113485. **
  113486. ** Instead, invoke the unlock-notify callback with the context
  113487. ** array already accumulated. We can then clear the array and
  113488. ** begin accumulating any further context pointers without
  113489. ** requiring any dynamic allocation. This is sub-optimal because
  113490. ** it means that instead of one callback with a large array of
  113491. ** context pointers the application will receive two or more
  113492. ** callbacks with smaller arrays of context pointers, which will
  113493. ** reduce the applications ability to prioritize multiple
  113494. ** connections. But it is the best that can be done under the
  113495. ** circumstances.
  113496. */
  113497. xUnlockNotify(aArg, nArg);
  113498. nArg = 0;
  113499. }
  113500. }
  113501. sqlite3EndBenignMalloc();
  113502. aArg[nArg++] = p->pUnlockArg;
  113503. xUnlockNotify = p->xUnlockNotify;
  113504. p->pUnlockConnection = 0;
  113505. p->xUnlockNotify = 0;
  113506. p->pUnlockArg = 0;
  113507. }
  113508. /* Step 3. */
  113509. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  113510. /* Remove connection p from the blocked connections list. */
  113511. *pp = p->pNextBlocked;
  113512. p->pNextBlocked = 0;
  113513. }else{
  113514. pp = &p->pNextBlocked;
  113515. }
  113516. }
  113517. if( nArg!=0 ){
  113518. xUnlockNotify(aArg, nArg);
  113519. }
  113520. sqlite3_free(aDyn);
  113521. leaveMutex(); /* Leave STATIC_MASTER mutex */
  113522. }
  113523. /*
  113524. ** This is called when the database connection passed as an argument is
  113525. ** being closed. The connection is removed from the blocked list.
  113526. */
  113527. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  113528. sqlite3ConnectionUnlocked(db);
  113529. enterMutex();
  113530. removeFromBlockedList(db);
  113531. checkListProperties(db);
  113532. leaveMutex();
  113533. }
  113534. #endif
  113535. /************** End of notify.c **********************************************/
  113536. /************** Begin file fts3.c ********************************************/
  113537. /*
  113538. ** 2006 Oct 10
  113539. **
  113540. ** The author disclaims copyright to this source code. In place of
  113541. ** a legal notice, here is a blessing:
  113542. **
  113543. ** May you do good and not evil.
  113544. ** May you find forgiveness for yourself and forgive others.
  113545. ** May you share freely, never taking more than you give.
  113546. **
  113547. ******************************************************************************
  113548. **
  113549. ** This is an SQLite module implementing full-text search.
  113550. */
  113551. /*
  113552. ** The code in this file is only compiled if:
  113553. **
  113554. ** * The FTS3 module is being built as an extension
  113555. ** (in which case SQLITE_CORE is not defined), or
  113556. **
  113557. ** * The FTS3 module is being built into the core of
  113558. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  113559. */
  113560. /* The full-text index is stored in a series of b+tree (-like)
  113561. ** structures called segments which map terms to doclists. The
  113562. ** structures are like b+trees in layout, but are constructed from the
  113563. ** bottom up in optimal fashion and are not updatable. Since trees
  113564. ** are built from the bottom up, things will be described from the
  113565. ** bottom up.
  113566. **
  113567. **
  113568. **** Varints ****
  113569. ** The basic unit of encoding is a variable-length integer called a
  113570. ** varint. We encode variable-length integers in little-endian order
  113571. ** using seven bits * per byte as follows:
  113572. **
  113573. ** KEY:
  113574. ** A = 0xxxxxxx 7 bits of data and one flag bit
  113575. ** B = 1xxxxxxx 7 bits of data and one flag bit
  113576. **
  113577. ** 7 bits - A
  113578. ** 14 bits - BA
  113579. ** 21 bits - BBA
  113580. ** and so on.
  113581. **
  113582. ** This is similar in concept to how sqlite encodes "varints" but
  113583. ** the encoding is not the same. SQLite varints are big-endian
  113584. ** are are limited to 9 bytes in length whereas FTS3 varints are
  113585. ** little-endian and can be up to 10 bytes in length (in theory).
  113586. **
  113587. ** Example encodings:
  113588. **
  113589. ** 1: 0x01
  113590. ** 127: 0x7f
  113591. ** 128: 0x81 0x00
  113592. **
  113593. **
  113594. **** Document lists ****
  113595. ** A doclist (document list) holds a docid-sorted list of hits for a
  113596. ** given term. Doclists hold docids and associated token positions.
  113597. ** A docid is the unique integer identifier for a single document.
  113598. ** A position is the index of a word within the document. The first
  113599. ** word of the document has a position of 0.
  113600. **
  113601. ** FTS3 used to optionally store character offsets using a compile-time
  113602. ** option. But that functionality is no longer supported.
  113603. **
  113604. ** A doclist is stored like this:
  113605. **
  113606. ** array {
  113607. ** varint docid; (delta from previous doclist)
  113608. ** array { (position list for column 0)
  113609. ** varint position; (2 more than the delta from previous position)
  113610. ** }
  113611. ** array {
  113612. ** varint POS_COLUMN; (marks start of position list for new column)
  113613. ** varint column; (index of new column)
  113614. ** array {
  113615. ** varint position; (2 more than the delta from previous position)
  113616. ** }
  113617. ** }
  113618. ** varint POS_END; (marks end of positions for this document.
  113619. ** }
  113620. **
  113621. ** Here, array { X } means zero or more occurrences of X, adjacent in
  113622. ** memory. A "position" is an index of a token in the token stream
  113623. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  113624. ** in the same logical place as the position element, and act as sentinals
  113625. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  113626. ** The positions numbers are not stored literally but rather as two more
  113627. ** than the difference from the prior position, or the just the position plus
  113628. ** 2 for the first position. Example:
  113629. **
  113630. ** label: A B C D E F G H I J K
  113631. ** value: 123 5 9 1 1 14 35 0 234 72 0
  113632. **
  113633. ** The 123 value is the first docid. For column zero in this document
  113634. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  113635. ** at D signals the start of a new column; the 1 at E indicates that the
  113636. ** new column is column number 1. There are two positions at 12 and 45
  113637. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  113638. ** 234 at I is the delta to next docid (357). It has one position 70
  113639. ** (72-2) and then terminates with the 0 at K.
  113640. **
  113641. ** A "position-list" is the list of positions for multiple columns for
  113642. ** a single docid. A "column-list" is the set of positions for a single
  113643. ** column. Hence, a position-list consists of one or more column-lists,
  113644. ** a document record consists of a docid followed by a position-list and
  113645. ** a doclist consists of one or more document records.
  113646. **
  113647. ** A bare doclist omits the position information, becoming an
  113648. ** array of varint-encoded docids.
  113649. **
  113650. **** Segment leaf nodes ****
  113651. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  113652. ** nodes are written using LeafWriter, and read using LeafReader (to
  113653. ** iterate through a single leaf node's data) and LeavesReader (to
  113654. ** iterate through a segment's entire leaf layer). Leaf nodes have
  113655. ** the format:
  113656. **
  113657. ** varint iHeight; (height from leaf level, always 0)
  113658. ** varint nTerm; (length of first term)
  113659. ** char pTerm[nTerm]; (content of first term)
  113660. ** varint nDoclist; (length of term's associated doclist)
  113661. ** char pDoclist[nDoclist]; (content of doclist)
  113662. ** array {
  113663. ** (further terms are delta-encoded)
  113664. ** varint nPrefix; (length of prefix shared with previous term)
  113665. ** varint nSuffix; (length of unshared suffix)
  113666. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  113667. ** varint nDoclist; (length of term's associated doclist)
  113668. ** char pDoclist[nDoclist]; (content of doclist)
  113669. ** }
  113670. **
  113671. ** Here, array { X } means zero or more occurrences of X, adjacent in
  113672. ** memory.
  113673. **
  113674. ** Leaf nodes are broken into blocks which are stored contiguously in
  113675. ** the %_segments table in sorted order. This means that when the end
  113676. ** of a node is reached, the next term is in the node with the next
  113677. ** greater node id.
  113678. **
  113679. ** New data is spilled to a new leaf node when the current node
  113680. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  113681. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  113682. ** node (a leaf node with a single term and doclist). The goal of
  113683. ** these settings is to pack together groups of small doclists while
  113684. ** making it efficient to directly access large doclists. The
  113685. ** assumption is that large doclists represent terms which are more
  113686. ** likely to be query targets.
  113687. **
  113688. ** TODO(shess) It may be useful for blocking decisions to be more
  113689. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  113690. ** node rather than splitting into 2k and .5k nodes. My intuition is
  113691. ** that this might extend through 2x or 4x the pagesize.
  113692. **
  113693. **
  113694. **** Segment interior nodes ****
  113695. ** Segment interior nodes store blockids for subtree nodes and terms
  113696. ** to describe what data is stored by the each subtree. Interior
  113697. ** nodes are written using InteriorWriter, and read using
  113698. ** InteriorReader. InteriorWriters are created as needed when
  113699. ** SegmentWriter creates new leaf nodes, or when an interior node
  113700. ** itself grows too big and must be split. The format of interior
  113701. ** nodes:
  113702. **
  113703. ** varint iHeight; (height from leaf level, always >0)
  113704. ** varint iBlockid; (block id of node's leftmost subtree)
  113705. ** optional {
  113706. ** varint nTerm; (length of first term)
  113707. ** char pTerm[nTerm]; (content of first term)
  113708. ** array {
  113709. ** (further terms are delta-encoded)
  113710. ** varint nPrefix; (length of shared prefix with previous term)
  113711. ** varint nSuffix; (length of unshared suffix)
  113712. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  113713. ** }
  113714. ** }
  113715. **
  113716. ** Here, optional { X } means an optional element, while array { X }
  113717. ** means zero or more occurrences of X, adjacent in memory.
  113718. **
  113719. ** An interior node encodes n terms separating n+1 subtrees. The
  113720. ** subtree blocks are contiguous, so only the first subtree's blockid
  113721. ** is encoded. The subtree at iBlockid will contain all terms less
  113722. ** than the first term encoded (or all terms if no term is encoded).
  113723. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  113724. ** than pTerm[i+1], the subtree for that term will be rooted at
  113725. ** iBlockid+i. Interior nodes only store enough term data to
  113726. ** distinguish adjacent children (if the rightmost term of the left
  113727. ** child is "something", and the leftmost term of the right child is
  113728. ** "wicked", only "w" is stored).
  113729. **
  113730. ** New data is spilled to a new interior node at the same height when
  113731. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  113732. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  113733. ** interior nodes and making the tree too skinny. The interior nodes
  113734. ** at a given height are naturally tracked by interior nodes at
  113735. ** height+1, and so on.
  113736. **
  113737. **
  113738. **** Segment directory ****
  113739. ** The segment directory in table %_segdir stores meta-information for
  113740. ** merging and deleting segments, and also the root node of the
  113741. ** segment's tree.
  113742. **
  113743. ** The root node is the top node of the segment's tree after encoding
  113744. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  113745. ** This could be either a leaf node or an interior node. If the top
  113746. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  113747. ** and a new root interior node is generated (which should always fit
  113748. ** within ROOT_MAX because it only needs space for 2 varints, the
  113749. ** height and the blockid of the previous root).
  113750. **
  113751. ** The meta-information in the segment directory is:
  113752. ** level - segment level (see below)
  113753. ** idx - index within level
  113754. ** - (level,idx uniquely identify a segment)
  113755. ** start_block - first leaf node
  113756. ** leaves_end_block - last leaf node
  113757. ** end_block - last block (including interior nodes)
  113758. ** root - contents of root node
  113759. **
  113760. ** If the root node is a leaf node, then start_block,
  113761. ** leaves_end_block, and end_block are all 0.
  113762. **
  113763. **
  113764. **** Segment merging ****
  113765. ** To amortize update costs, segments are grouped into levels and
  113766. ** merged in batches. Each increase in level represents exponentially
  113767. ** more documents.
  113768. **
  113769. ** New documents (actually, document updates) are tokenized and
  113770. ** written individually (using LeafWriter) to a level 0 segment, with
  113771. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  113772. ** level 0 segments are merged into a single level 1 segment. Level 1
  113773. ** is populated like level 0, and eventually MERGE_COUNT level 1
  113774. ** segments are merged to a single level 2 segment (representing
  113775. ** MERGE_COUNT^2 updates), and so on.
  113776. **
  113777. ** A segment merge traverses all segments at a given level in
  113778. ** parallel, performing a straightforward sorted merge. Since segment
  113779. ** leaf nodes are written in to the %_segments table in order, this
  113780. ** merge traverses the underlying sqlite disk structures efficiently.
  113781. ** After the merge, all segment blocks from the merged level are
  113782. ** deleted.
  113783. **
  113784. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  113785. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  113786. ** very similar performance numbers to 16 on insertion, though they're
  113787. ** a tiny bit slower (perhaps due to more overhead in merge-time
  113788. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  113789. ** 16, 2 about 66% slower than 16.
  113790. **
  113791. ** At query time, high MERGE_COUNT increases the number of segments
  113792. ** which need to be scanned and merged. For instance, with 100k docs
  113793. ** inserted:
  113794. **
  113795. ** MERGE_COUNT segments
  113796. ** 16 25
  113797. ** 8 12
  113798. ** 4 10
  113799. ** 2 6
  113800. **
  113801. ** This appears to have only a moderate impact on queries for very
  113802. ** frequent terms (which are somewhat dominated by segment merge
  113803. ** costs), and infrequent and non-existent terms still seem to be fast
  113804. ** even with many segments.
  113805. **
  113806. ** TODO(shess) That said, it would be nice to have a better query-side
  113807. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  113808. ** optimizations to things like doclist merging will swing the sweet
  113809. ** spot around.
  113810. **
  113811. **
  113812. **
  113813. **** Handling of deletions and updates ****
  113814. ** Since we're using a segmented structure, with no docid-oriented
  113815. ** index into the term index, we clearly cannot simply update the term
  113816. ** index when a document is deleted or updated. For deletions, we
  113817. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  113818. ** we simply write the new doclist. Segment merges overwrite older
  113819. ** data for a particular docid with newer data, so deletes or updates
  113820. ** will eventually overtake the earlier data and knock it out. The
  113821. ** query logic likewise merges doclists so that newer data knocks out
  113822. ** older data.
  113823. */
  113824. /************** Include fts3Int.h in the middle of fts3.c ********************/
  113825. /************** Begin file fts3Int.h *****************************************/
  113826. /*
  113827. ** 2009 Nov 12
  113828. **
  113829. ** The author disclaims copyright to this source code. In place of
  113830. ** a legal notice, here is a blessing:
  113831. **
  113832. ** May you do good and not evil.
  113833. ** May you find forgiveness for yourself and forgive others.
  113834. ** May you share freely, never taking more than you give.
  113835. **
  113836. ******************************************************************************
  113837. **
  113838. */
  113839. #ifndef _FTSINT_H
  113840. #define _FTSINT_H
  113841. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  113842. # define NDEBUG 1
  113843. #endif
  113844. /*
  113845. ** FTS4 is really an extension for FTS3. It is enabled using the
  113846. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  113847. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  113848. */
  113849. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  113850. # define SQLITE_ENABLE_FTS3
  113851. #endif
  113852. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  113853. /* If not building as part of the core, include sqlite3ext.h. */
  113854. #ifndef SQLITE_CORE
  113855. SQLITE_EXTENSION_INIT3
  113856. #endif
  113857. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  113858. /************** Begin file fts3_tokenizer.h **********************************/
  113859. /*
  113860. ** 2006 July 10
  113861. **
  113862. ** The author disclaims copyright to this source code.
  113863. **
  113864. *************************************************************************
  113865. ** Defines the interface to tokenizers used by fulltext-search. There
  113866. ** are three basic components:
  113867. **
  113868. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  113869. ** interface functions. This is essentially the class structure for
  113870. ** tokenizers.
  113871. **
  113872. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  113873. ** including customization information defined at creation time.
  113874. **
  113875. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  113876. ** tokens from a particular input.
  113877. */
  113878. #ifndef _FTS3_TOKENIZER_H_
  113879. #define _FTS3_TOKENIZER_H_
  113880. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  113881. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  113882. ** we will need a way to register the API consistently.
  113883. */
  113884. /*
  113885. ** Structures used by the tokenizer interface. When a new tokenizer
  113886. ** implementation is registered, the caller provides a pointer to
  113887. ** an sqlite3_tokenizer_module containing pointers to the callback
  113888. ** functions that make up an implementation.
  113889. **
  113890. ** When an fts3 table is created, it passes any arguments passed to
  113891. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  113892. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  113893. ** implementation. The xCreate() function in turn returns an
  113894. ** sqlite3_tokenizer structure representing the specific tokenizer to
  113895. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  113896. **
  113897. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  113898. ** method is called. It returns an sqlite3_tokenizer_cursor object
  113899. ** that may be used to tokenize a specific input buffer based on
  113900. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  113901. ** object.
  113902. */
  113903. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  113904. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  113905. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  113906. struct sqlite3_tokenizer_module {
  113907. /*
  113908. ** Structure version. Should always be set to 0 or 1.
  113909. */
  113910. int iVersion;
  113911. /*
  113912. ** Create a new tokenizer. The values in the argv[] array are the
  113913. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  113914. ** TABLE statement that created the fts3 table. For example, if
  113915. ** the following SQL is executed:
  113916. **
  113917. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  113918. **
  113919. ** then argc is set to 2, and the argv[] array contains pointers
  113920. ** to the strings "arg1" and "arg2".
  113921. **
  113922. ** This method should return either SQLITE_OK (0), or an SQLite error
  113923. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  113924. ** to point at the newly created tokenizer structure. The generic
  113925. ** sqlite3_tokenizer.pModule variable should not be initialized by
  113926. ** this callback. The caller will do so.
  113927. */
  113928. int (*xCreate)(
  113929. int argc, /* Size of argv array */
  113930. const char *const*argv, /* Tokenizer argument strings */
  113931. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  113932. );
  113933. /*
  113934. ** Destroy an existing tokenizer. The fts3 module calls this method
  113935. ** exactly once for each successful call to xCreate().
  113936. */
  113937. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  113938. /*
  113939. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  113940. ** is responsible for ensuring that the input buffer remains valid
  113941. ** until the cursor is closed (using the xClose() method).
  113942. */
  113943. int (*xOpen)(
  113944. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  113945. const char *pInput, int nBytes, /* Input buffer */
  113946. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  113947. );
  113948. /*
  113949. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  113950. ** method exactly once for each successful call to xOpen().
  113951. */
  113952. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  113953. /*
  113954. ** Retrieve the next token from the tokenizer cursor pCursor. This
  113955. ** method should either return SQLITE_OK and set the values of the
  113956. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  113957. ** the end of the buffer has been reached, or an SQLite error code.
  113958. **
  113959. ** *ppToken should be set to point at a buffer containing the
  113960. ** normalized version of the token (i.e. after any case-folding and/or
  113961. ** stemming has been performed). *pnBytes should be set to the length
  113962. ** of this buffer in bytes. The input text that generated the token is
  113963. ** identified by the byte offsets returned in *piStartOffset and
  113964. ** *piEndOffset. *piStartOffset should be set to the index of the first
  113965. ** byte of the token in the input buffer. *piEndOffset should be set
  113966. ** to the index of the first byte just past the end of the token in
  113967. ** the input buffer.
  113968. **
  113969. ** The buffer *ppToken is set to point at is managed by the tokenizer
  113970. ** implementation. It is only required to be valid until the next call
  113971. ** to xNext() or xClose().
  113972. */
  113973. /* TODO(shess) current implementation requires pInput to be
  113974. ** nul-terminated. This should either be fixed, or pInput/nBytes
  113975. ** should be converted to zInput.
  113976. */
  113977. int (*xNext)(
  113978. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  113979. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  113980. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  113981. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  113982. int *piPosition /* OUT: Number of tokens returned before this one */
  113983. );
  113984. /***********************************************************************
  113985. ** Methods below this point are only available if iVersion>=1.
  113986. */
  113987. /*
  113988. ** Configure the language id of a tokenizer cursor.
  113989. */
  113990. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  113991. };
  113992. struct sqlite3_tokenizer {
  113993. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  113994. /* Tokenizer implementations will typically add additional fields */
  113995. };
  113996. struct sqlite3_tokenizer_cursor {
  113997. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  113998. /* Tokenizer implementations will typically add additional fields */
  113999. };
  114000. int fts3_global_term_cnt(int iTerm, int iCol);
  114001. int fts3_term_cnt(int iTerm, int iCol);
  114002. #endif /* _FTS3_TOKENIZER_H_ */
  114003. /************** End of fts3_tokenizer.h **************************************/
  114004. /************** Continuing where we left off in fts3Int.h ********************/
  114005. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  114006. /************** Begin file fts3_hash.h ***************************************/
  114007. /*
  114008. ** 2001 September 22
  114009. **
  114010. ** The author disclaims copyright to this source code. In place of
  114011. ** a legal notice, here is a blessing:
  114012. **
  114013. ** May you do good and not evil.
  114014. ** May you find forgiveness for yourself and forgive others.
  114015. ** May you share freely, never taking more than you give.
  114016. **
  114017. *************************************************************************
  114018. ** This is the header file for the generic hash-table implementation
  114019. ** used in SQLite. We've modified it slightly to serve as a standalone
  114020. ** hash table implementation for the full-text indexing module.
  114021. **
  114022. */
  114023. #ifndef _FTS3_HASH_H_
  114024. #define _FTS3_HASH_H_
  114025. /* Forward declarations of structures. */
  114026. typedef struct Fts3Hash Fts3Hash;
  114027. typedef struct Fts3HashElem Fts3HashElem;
  114028. /* A complete hash table is an instance of the following structure.
  114029. ** The internals of this structure are intended to be opaque -- client
  114030. ** code should not attempt to access or modify the fields of this structure
  114031. ** directly. Change this structure only by using the routines below.
  114032. ** However, many of the "procedures" and "functions" for modifying and
  114033. ** accessing this structure are really macros, so we can't really make
  114034. ** this structure opaque.
  114035. */
  114036. struct Fts3Hash {
  114037. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  114038. char copyKey; /* True if copy of key made on insert */
  114039. int count; /* Number of entries in this table */
  114040. Fts3HashElem *first; /* The first element of the array */
  114041. int htsize; /* Number of buckets in the hash table */
  114042. struct _fts3ht { /* the hash table */
  114043. int count; /* Number of entries with this hash */
  114044. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  114045. } *ht;
  114046. };
  114047. /* Each element in the hash table is an instance of the following
  114048. ** structure. All elements are stored on a single doubly-linked list.
  114049. **
  114050. ** Again, this structure is intended to be opaque, but it can't really
  114051. ** be opaque because it is used by macros.
  114052. */
  114053. struct Fts3HashElem {
  114054. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  114055. void *data; /* Data associated with this element */
  114056. void *pKey; int nKey; /* Key associated with this element */
  114057. };
  114058. /*
  114059. ** There are 2 different modes of operation for a hash table:
  114060. **
  114061. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  114062. ** (including the null-terminator, if any). Case
  114063. ** is respected in comparisons.
  114064. **
  114065. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  114066. ** memcmp() is used to compare keys.
  114067. **
  114068. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  114069. */
  114070. #define FTS3_HASH_STRING 1
  114071. #define FTS3_HASH_BINARY 2
  114072. /*
  114073. ** Access routines. To delete, insert a NULL pointer.
  114074. */
  114075. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  114076. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  114077. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  114078. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  114079. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  114080. /*
  114081. ** Shorthand for the functions above
  114082. */
  114083. #define fts3HashInit sqlite3Fts3HashInit
  114084. #define fts3HashInsert sqlite3Fts3HashInsert
  114085. #define fts3HashFind sqlite3Fts3HashFind
  114086. #define fts3HashClear sqlite3Fts3HashClear
  114087. #define fts3HashFindElem sqlite3Fts3HashFindElem
  114088. /*
  114089. ** Macros for looping over all elements of a hash table. The idiom is
  114090. ** like this:
  114091. **
  114092. ** Fts3Hash h;
  114093. ** Fts3HashElem *p;
  114094. ** ...
  114095. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  114096. ** SomeStructure *pData = fts3HashData(p);
  114097. ** // do something with pData
  114098. ** }
  114099. */
  114100. #define fts3HashFirst(H) ((H)->first)
  114101. #define fts3HashNext(E) ((E)->next)
  114102. #define fts3HashData(E) ((E)->data)
  114103. #define fts3HashKey(E) ((E)->pKey)
  114104. #define fts3HashKeysize(E) ((E)->nKey)
  114105. /*
  114106. ** Number of entries in a hash table
  114107. */
  114108. #define fts3HashCount(H) ((H)->count)
  114109. #endif /* _FTS3_HASH_H_ */
  114110. /************** End of fts3_hash.h *******************************************/
  114111. /************** Continuing where we left off in fts3Int.h ********************/
  114112. /*
  114113. ** This constant determines the maximum depth of an FTS expression tree
  114114. ** that the library will create and use. FTS uses recursion to perform
  114115. ** various operations on the query tree, so the disadvantage of a large
  114116. ** limit is that it may allow very large queries to use large amounts
  114117. ** of stack space (perhaps causing a stack overflow).
  114118. */
  114119. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  114120. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  114121. #endif
  114122. /*
  114123. ** This constant controls how often segments are merged. Once there are
  114124. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  114125. ** segment of level N+1.
  114126. */
  114127. #define FTS3_MERGE_COUNT 16
  114128. /*
  114129. ** This is the maximum amount of data (in bytes) to store in the
  114130. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  114131. ** populated as documents are inserted/updated/deleted in a transaction
  114132. ** and used to create a new segment when the transaction is committed.
  114133. ** However if this limit is reached midway through a transaction, a new
  114134. ** segment is created and the hash table cleared immediately.
  114135. */
  114136. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  114137. /*
  114138. ** Macro to return the number of elements in an array. SQLite has a
  114139. ** similar macro called ArraySize(). Use a different name to avoid
  114140. ** a collision when building an amalgamation with built-in FTS3.
  114141. */
  114142. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  114143. #ifndef MIN
  114144. # define MIN(x,y) ((x)<(y)?(x):(y))
  114145. #endif
  114146. #ifndef MAX
  114147. # define MAX(x,y) ((x)>(y)?(x):(y))
  114148. #endif
  114149. /*
  114150. ** Maximum length of a varint encoded integer. The varint format is different
  114151. ** from that used by SQLite, so the maximum length is 10, not 9.
  114152. */
  114153. #define FTS3_VARINT_MAX 10
  114154. /*
  114155. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  114156. ** in the document set and zero or more prefix indexes. All indexes are stored
  114157. ** as one or more b+-trees in the %_segments and %_segdir tables.
  114158. **
  114159. ** It is possible to determine which index a b+-tree belongs to based on the
  114160. ** value stored in the "%_segdir.level" column. Given this value L, the index
  114161. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  114162. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  114163. ** between 1024 and 2047 to index 1, and so on.
  114164. **
  114165. ** It is considered impossible for an index to use more than 1024 levels. In
  114166. ** theory though this may happen, but only after at least
  114167. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  114168. */
  114169. #define FTS3_SEGDIR_MAXLEVEL 1024
  114170. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  114171. /*
  114172. ** The testcase() macro is only used by the amalgamation. If undefined,
  114173. ** make it a no-op.
  114174. */
  114175. #ifndef testcase
  114176. # define testcase(X)
  114177. #endif
  114178. /*
  114179. ** Terminator values for position-lists and column-lists.
  114180. */
  114181. #define POS_COLUMN (1) /* Column-list terminator */
  114182. #define POS_END (0) /* Position-list terminator */
  114183. /*
  114184. ** This section provides definitions to allow the
  114185. ** FTS3 extension to be compiled outside of the
  114186. ** amalgamation.
  114187. */
  114188. #ifndef SQLITE_AMALGAMATION
  114189. /*
  114190. ** Macros indicating that conditional expressions are always true or
  114191. ** false.
  114192. */
  114193. #ifdef SQLITE_COVERAGE_TEST
  114194. # define ALWAYS(x) (1)
  114195. # define NEVER(X) (0)
  114196. #else
  114197. # define ALWAYS(x) (x)
  114198. # define NEVER(x) (x)
  114199. #endif
  114200. /*
  114201. ** Internal types used by SQLite.
  114202. */
  114203. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  114204. typedef short int i16; /* 2-byte (or larger) signed integer */
  114205. typedef unsigned int u32; /* 4-byte unsigned integer */
  114206. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  114207. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  114208. /*
  114209. ** Macro used to suppress compiler warnings for unused parameters.
  114210. */
  114211. #define UNUSED_PARAMETER(x) (void)(x)
  114212. /*
  114213. ** Activate assert() only if SQLITE_TEST is enabled.
  114214. */
  114215. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  114216. # define NDEBUG 1
  114217. #endif
  114218. /*
  114219. ** The TESTONLY macro is used to enclose variable declarations or
  114220. ** other bits of code that are needed to support the arguments
  114221. ** within testcase() and assert() macros.
  114222. */
  114223. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  114224. # define TESTONLY(X) X
  114225. #else
  114226. # define TESTONLY(X)
  114227. #endif
  114228. #endif /* SQLITE_AMALGAMATION */
  114229. #ifdef SQLITE_DEBUG
  114230. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  114231. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  114232. #else
  114233. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  114234. #endif
  114235. typedef struct Fts3Table Fts3Table;
  114236. typedef struct Fts3Cursor Fts3Cursor;
  114237. typedef struct Fts3Expr Fts3Expr;
  114238. typedef struct Fts3Phrase Fts3Phrase;
  114239. typedef struct Fts3PhraseToken Fts3PhraseToken;
  114240. typedef struct Fts3Doclist Fts3Doclist;
  114241. typedef struct Fts3SegFilter Fts3SegFilter;
  114242. typedef struct Fts3DeferredToken Fts3DeferredToken;
  114243. typedef struct Fts3SegReader Fts3SegReader;
  114244. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  114245. /*
  114246. ** A connection to a fulltext index is an instance of the following
  114247. ** structure. The xCreate and xConnect methods create an instance
  114248. ** of this structure and xDestroy and xDisconnect free that instance.
  114249. ** All other methods receive a pointer to the structure as one of their
  114250. ** arguments.
  114251. */
  114252. struct Fts3Table {
  114253. sqlite3_vtab base; /* Base class used by SQLite core */
  114254. sqlite3 *db; /* The database connection */
  114255. const char *zDb; /* logical database name */
  114256. const char *zName; /* virtual table name */
  114257. int nColumn; /* number of named columns in virtual table */
  114258. char **azColumn; /* column names. malloced */
  114259. u8 *abNotindexed; /* True for 'notindexed' columns */
  114260. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  114261. char *zContentTbl; /* content=xxx option, or NULL */
  114262. char *zLanguageid; /* languageid=xxx option, or NULL */
  114263. u8 bAutoincrmerge; /* True if automerge=1 */
  114264. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  114265. /* Precompiled statements used by the implementation. Each of these
  114266. ** statements is run and reset within a single virtual table API call.
  114267. */
  114268. sqlite3_stmt *aStmt[37];
  114269. char *zReadExprlist;
  114270. char *zWriteExprlist;
  114271. int nNodeSize; /* Soft limit for node size */
  114272. u8 bFts4; /* True for FTS4, false for FTS3 */
  114273. u8 bHasStat; /* True if %_stat table exists */
  114274. u8 bHasDocsize; /* True if %_docsize table exists */
  114275. u8 bDescIdx; /* True if doclists are in reverse order */
  114276. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  114277. int nPgsz; /* Page size for host database */
  114278. char *zSegmentsTbl; /* Name of %_segments table */
  114279. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  114280. /*
  114281. ** The following array of hash tables is used to buffer pending index
  114282. ** updates during transactions. All pending updates buffered at any one
  114283. ** time must share a common language-id (see the FTS4 langid= feature).
  114284. ** The current language id is stored in variable iPrevLangid.
  114285. **
  114286. ** A single FTS4 table may have multiple full-text indexes. For each index
  114287. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  114288. ** terms that appear in the document set. Each subsequent index in aIndex[]
  114289. ** is an index of prefixes of a specific length.
  114290. **
  114291. ** Variable nPendingData contains an estimate the memory consumed by the
  114292. ** pending data structures, including hash table overhead, but not including
  114293. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  114294. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  114295. ** recently inserted record.
  114296. */
  114297. int nIndex; /* Size of aIndex[] */
  114298. struct Fts3Index {
  114299. int nPrefix; /* Prefix length (0 for main terms index) */
  114300. Fts3Hash hPending; /* Pending terms table for this index */
  114301. } *aIndex;
  114302. int nMaxPendingData; /* Max pending data before flush to disk */
  114303. int nPendingData; /* Current bytes of pending data */
  114304. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  114305. int iPrevLangid; /* Langid of recently inserted document */
  114306. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  114307. /* State variables used for validating that the transaction control
  114308. ** methods of the virtual table are called at appropriate times. These
  114309. ** values do not contribute to FTS functionality; they are used for
  114310. ** verifying the operation of the SQLite core.
  114311. */
  114312. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  114313. int mxSavepoint; /* Largest valid xSavepoint integer */
  114314. #endif
  114315. #ifdef SQLITE_TEST
  114316. /* True to disable the incremental doclist optimization. This is controled
  114317. ** by special insert command 'test-no-incr-doclist'. */
  114318. int bNoIncrDoclist;
  114319. #endif
  114320. };
  114321. /*
  114322. ** When the core wants to read from the virtual table, it creates a
  114323. ** virtual table cursor (an instance of the following structure) using
  114324. ** the xOpen method. Cursors are destroyed using the xClose method.
  114325. */
  114326. struct Fts3Cursor {
  114327. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  114328. i16 eSearch; /* Search strategy (see below) */
  114329. u8 isEof; /* True if at End Of Results */
  114330. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  114331. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  114332. Fts3Expr *pExpr; /* Parsed MATCH query string */
  114333. int iLangid; /* Language being queried for */
  114334. int nPhrase; /* Number of matchable phrases in query */
  114335. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  114336. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  114337. char *pNextId; /* Pointer into the body of aDoclist */
  114338. char *aDoclist; /* List of docids for full-text queries */
  114339. int nDoclist; /* Size of buffer at aDoclist */
  114340. u8 bDesc; /* True to sort in descending order */
  114341. int eEvalmode; /* An FTS3_EVAL_XX constant */
  114342. int nRowAvg; /* Average size of database rows, in pages */
  114343. sqlite3_int64 nDoc; /* Documents in table */
  114344. i64 iMinDocid; /* Minimum docid to return */
  114345. i64 iMaxDocid; /* Maximum docid to return */
  114346. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  114347. u32 *aMatchinfo; /* Information about most recent match */
  114348. int nMatchinfo; /* Number of elements in aMatchinfo[] */
  114349. char *zMatchinfo; /* Matchinfo specification */
  114350. };
  114351. #define FTS3_EVAL_FILTER 0
  114352. #define FTS3_EVAL_NEXT 1
  114353. #define FTS3_EVAL_MATCHINFO 2
  114354. /*
  114355. ** The Fts3Cursor.eSearch member is always set to one of the following.
  114356. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  114357. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  114358. ** of the column to be searched. For example, in
  114359. **
  114360. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  114361. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  114362. **
  114363. ** Because the LHS of the MATCH operator is 2nd column "b",
  114364. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  114365. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  114366. ** indicating that all columns should be searched,
  114367. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  114368. */
  114369. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  114370. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  114371. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  114372. /*
  114373. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  114374. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  114375. ** above. The upper 16-bits contain a combination of the following
  114376. ** bits, used to describe extra constraints on full-text searches.
  114377. */
  114378. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  114379. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  114380. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  114381. struct Fts3Doclist {
  114382. char *aAll; /* Array containing doclist (or NULL) */
  114383. int nAll; /* Size of a[] in bytes */
  114384. char *pNextDocid; /* Pointer to next docid */
  114385. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  114386. int bFreeList; /* True if pList should be sqlite3_free()d */
  114387. char *pList; /* Pointer to position list following iDocid */
  114388. int nList; /* Length of position list */
  114389. };
  114390. /*
  114391. ** A "phrase" is a sequence of one or more tokens that must match in
  114392. ** sequence. A single token is the base case and the most common case.
  114393. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  114394. ** nToken will be the number of tokens in the string.
  114395. */
  114396. struct Fts3PhraseToken {
  114397. char *z; /* Text of the token */
  114398. int n; /* Number of bytes in buffer z */
  114399. int isPrefix; /* True if token ends with a "*" character */
  114400. int bFirst; /* True if token must appear at position 0 */
  114401. /* Variables above this point are populated when the expression is
  114402. ** parsed (by code in fts3_expr.c). Below this point the variables are
  114403. ** used when evaluating the expression. */
  114404. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  114405. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  114406. };
  114407. struct Fts3Phrase {
  114408. /* Cache of doclist for this phrase. */
  114409. Fts3Doclist doclist;
  114410. int bIncr; /* True if doclist is loaded incrementally */
  114411. int iDoclistToken;
  114412. /* Variables below this point are populated by fts3_expr.c when parsing
  114413. ** a MATCH expression. Everything above is part of the evaluation phase.
  114414. */
  114415. int nToken; /* Number of tokens in the phrase */
  114416. int iColumn; /* Index of column this phrase must match */
  114417. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  114418. };
  114419. /*
  114420. ** A tree of these objects forms the RHS of a MATCH operator.
  114421. **
  114422. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  114423. ** points to a malloced buffer, size nDoclist bytes, containing the results
  114424. ** of this phrase query in FTS3 doclist format. As usual, the initial
  114425. ** "Length" field found in doclists stored on disk is omitted from this
  114426. ** buffer.
  114427. **
  114428. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  114429. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  114430. ** where nCol is the number of columns in the queried FTS table. The array
  114431. ** is populated as follows:
  114432. **
  114433. ** aMI[iCol*3 + 0] = Undefined
  114434. ** aMI[iCol*3 + 1] = Number of occurrences
  114435. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  114436. **
  114437. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  114438. ** when the expression node is.
  114439. */
  114440. struct Fts3Expr {
  114441. int eType; /* One of the FTSQUERY_XXX values defined below */
  114442. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  114443. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  114444. Fts3Expr *pLeft; /* Left operand */
  114445. Fts3Expr *pRight; /* Right operand */
  114446. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  114447. /* The following are used by the fts3_eval.c module. */
  114448. sqlite3_int64 iDocid; /* Current docid */
  114449. u8 bEof; /* True this expression is at EOF already */
  114450. u8 bStart; /* True if iDocid is valid */
  114451. u8 bDeferred; /* True if this expression is entirely deferred */
  114452. u32 *aMI;
  114453. };
  114454. /*
  114455. ** Candidate values for Fts3Query.eType. Note that the order of the first
  114456. ** four values is in order of precedence when parsing expressions. For
  114457. ** example, the following:
  114458. **
  114459. ** "a OR b AND c NOT d NEAR e"
  114460. **
  114461. ** is equivalent to:
  114462. **
  114463. ** "a OR (b AND (c NOT (d NEAR e)))"
  114464. */
  114465. #define FTSQUERY_NEAR 1
  114466. #define FTSQUERY_NOT 2
  114467. #define FTSQUERY_AND 3
  114468. #define FTSQUERY_OR 4
  114469. #define FTSQUERY_PHRASE 5
  114470. /* fts3_write.c */
  114471. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  114472. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  114473. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  114474. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  114475. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  114476. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  114477. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  114478. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  114479. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  114480. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  114481. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  114482. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  114483. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  114484. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  114485. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  114486. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  114487. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  114488. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  114489. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  114490. #else
  114491. # define sqlite3Fts3FreeDeferredTokens(x)
  114492. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  114493. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  114494. # define sqlite3Fts3FreeDeferredDoclists(x)
  114495. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  114496. #endif
  114497. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  114498. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  114499. /* Special values interpreted by sqlite3SegReaderCursor() */
  114500. #define FTS3_SEGCURSOR_PENDING -1
  114501. #define FTS3_SEGCURSOR_ALL -2
  114502. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  114503. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  114504. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  114505. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  114506. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  114507. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  114508. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  114509. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  114510. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  114511. #define FTS3_SEGMENT_PREFIX 0x00000008
  114512. #define FTS3_SEGMENT_SCAN 0x00000010
  114513. #define FTS3_SEGMENT_FIRST 0x00000020
  114514. /* Type passed as 4th argument to SegmentReaderIterate() */
  114515. struct Fts3SegFilter {
  114516. const char *zTerm;
  114517. int nTerm;
  114518. int iCol;
  114519. int flags;
  114520. };
  114521. struct Fts3MultiSegReader {
  114522. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  114523. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  114524. int nSegment; /* Size of apSegment array */
  114525. int nAdvance; /* How many seg-readers to advance */
  114526. Fts3SegFilter *pFilter; /* Pointer to filter object */
  114527. char *aBuffer; /* Buffer to merge doclists in */
  114528. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  114529. int iColFilter; /* If >=0, filter for this column */
  114530. int bRestart;
  114531. /* Used by fts3.c only. */
  114532. int nCost; /* Cost of running iterator */
  114533. int bLookup; /* True if a lookup of a single entry. */
  114534. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  114535. char *zTerm; /* Pointer to term buffer */
  114536. int nTerm; /* Size of zTerm in bytes */
  114537. char *aDoclist; /* Pointer to doclist buffer */
  114538. int nDoclist; /* Size of aDoclist[] in bytes */
  114539. };
  114540. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  114541. /* fts3.c */
  114542. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  114543. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  114544. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  114545. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  114546. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  114547. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  114548. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  114549. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  114550. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  114551. /* fts3_tokenizer.c */
  114552. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  114553. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  114554. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  114555. sqlite3_tokenizer **, char **
  114556. );
  114557. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  114558. /* fts3_snippet.c */
  114559. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  114560. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  114561. const char *, const char *, int, int
  114562. );
  114563. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  114564. /* fts3_expr.c */
  114565. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  114566. char **, int, int, int, const char *, int, Fts3Expr **, char **
  114567. );
  114568. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  114569. #ifdef SQLITE_TEST
  114570. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  114571. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  114572. #endif
  114573. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  114574. sqlite3_tokenizer_cursor **
  114575. );
  114576. /* fts3_aux.c */
  114577. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  114578. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  114579. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  114580. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  114581. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  114582. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  114583. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  114584. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  114585. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  114586. /* fts3_tokenize_vtab.c */
  114587. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  114588. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  114589. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  114590. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  114591. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  114592. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  114593. #endif
  114594. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  114595. #endif /* _FTSINT_H */
  114596. /************** End of fts3Int.h *********************************************/
  114597. /************** Continuing where we left off in fts3.c ***********************/
  114598. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  114599. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  114600. # define SQLITE_CORE 1
  114601. #endif
  114602. /* #include <assert.h> */
  114603. /* #include <stdlib.h> */
  114604. /* #include <stddef.h> */
  114605. /* #include <stdio.h> */
  114606. /* #include <string.h> */
  114607. /* #include <stdarg.h> */
  114608. #ifndef SQLITE_CORE
  114609. SQLITE_EXTENSION_INIT1
  114610. #endif
  114611. static int fts3EvalNext(Fts3Cursor *pCsr);
  114612. static int fts3EvalStart(Fts3Cursor *pCsr);
  114613. static int fts3TermSegReaderCursor(
  114614. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  114615. /*
  114616. ** Write a 64-bit variable-length integer to memory starting at p[0].
  114617. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  114618. ** The number of bytes written is returned.
  114619. */
  114620. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  114621. unsigned char *q = (unsigned char *) p;
  114622. sqlite_uint64 vu = v;
  114623. do{
  114624. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  114625. vu >>= 7;
  114626. }while( vu!=0 );
  114627. q[-1] &= 0x7f; /* turn off high bit in final byte */
  114628. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  114629. return (int) (q - (unsigned char *)p);
  114630. }
  114631. /*
  114632. ** Read a 64-bit variable-length integer from memory starting at p[0].
  114633. ** Return the number of bytes read, or 0 on error.
  114634. ** The value is stored in *v.
  114635. */
  114636. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  114637. const unsigned char *q = (const unsigned char *) p;
  114638. sqlite_uint64 x = 0, y = 1;
  114639. while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
  114640. x += y * (*q++ & 0x7f);
  114641. y <<= 7;
  114642. }
  114643. x += y * (*q++);
  114644. *v = (sqlite_int64) x;
  114645. return (int) (q - (unsigned char *)p);
  114646. }
  114647. /*
  114648. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  114649. ** 32-bit integer before it is returned.
  114650. */
  114651. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  114652. sqlite_int64 i;
  114653. int ret = sqlite3Fts3GetVarint(p, &i);
  114654. *pi = (int) i;
  114655. return ret;
  114656. }
  114657. /*
  114658. ** Return the number of bytes required to encode v as a varint
  114659. */
  114660. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  114661. int i = 0;
  114662. do{
  114663. i++;
  114664. v >>= 7;
  114665. }while( v!=0 );
  114666. return i;
  114667. }
  114668. /*
  114669. ** Convert an SQL-style quoted string into a normal string by removing
  114670. ** the quote characters. The conversion is done in-place. If the
  114671. ** input does not begin with a quote character, then this routine
  114672. ** is a no-op.
  114673. **
  114674. ** Examples:
  114675. **
  114676. ** "abc" becomes abc
  114677. ** 'xyz' becomes xyz
  114678. ** [pqr] becomes pqr
  114679. ** `mno` becomes mno
  114680. **
  114681. */
  114682. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  114683. char quote; /* Quote character (if any ) */
  114684. quote = z[0];
  114685. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  114686. int iIn = 1; /* Index of next byte to read from input */
  114687. int iOut = 0; /* Index of next byte to write to output */
  114688. /* If the first byte was a '[', then the close-quote character is a ']' */
  114689. if( quote=='[' ) quote = ']';
  114690. while( ALWAYS(z[iIn]) ){
  114691. if( z[iIn]==quote ){
  114692. if( z[iIn+1]!=quote ) break;
  114693. z[iOut++] = quote;
  114694. iIn += 2;
  114695. }else{
  114696. z[iOut++] = z[iIn++];
  114697. }
  114698. }
  114699. z[iOut] = '\0';
  114700. }
  114701. }
  114702. /*
  114703. ** Read a single varint from the doclist at *pp and advance *pp to point
  114704. ** to the first byte past the end of the varint. Add the value of the varint
  114705. ** to *pVal.
  114706. */
  114707. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  114708. sqlite3_int64 iVal;
  114709. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  114710. *pVal += iVal;
  114711. }
  114712. /*
  114713. ** When this function is called, *pp points to the first byte following a
  114714. ** varint that is part of a doclist (or position-list, or any other list
  114715. ** of varints). This function moves *pp to point to the start of that varint,
  114716. ** and sets *pVal by the varint value.
  114717. **
  114718. ** Argument pStart points to the first byte of the doclist that the
  114719. ** varint is part of.
  114720. */
  114721. static void fts3GetReverseVarint(
  114722. char **pp,
  114723. char *pStart,
  114724. sqlite3_int64 *pVal
  114725. ){
  114726. sqlite3_int64 iVal;
  114727. char *p;
  114728. /* Pointer p now points at the first byte past the varint we are
  114729. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  114730. ** clear on character p[-1]. */
  114731. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  114732. p++;
  114733. *pp = p;
  114734. sqlite3Fts3GetVarint(p, &iVal);
  114735. *pVal = iVal;
  114736. }
  114737. /*
  114738. ** The xDisconnect() virtual table method.
  114739. */
  114740. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  114741. Fts3Table *p = (Fts3Table *)pVtab;
  114742. int i;
  114743. assert( p->nPendingData==0 );
  114744. assert( p->pSegments==0 );
  114745. /* Free any prepared statements held */
  114746. for(i=0; i<SizeofArray(p->aStmt); i++){
  114747. sqlite3_finalize(p->aStmt[i]);
  114748. }
  114749. sqlite3_free(p->zSegmentsTbl);
  114750. sqlite3_free(p->zReadExprlist);
  114751. sqlite3_free(p->zWriteExprlist);
  114752. sqlite3_free(p->zContentTbl);
  114753. sqlite3_free(p->zLanguageid);
  114754. /* Invoke the tokenizer destructor to free the tokenizer. */
  114755. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  114756. sqlite3_free(p);
  114757. return SQLITE_OK;
  114758. }
  114759. /*
  114760. ** Construct one or more SQL statements from the format string given
  114761. ** and then evaluate those statements. The success code is written
  114762. ** into *pRc.
  114763. **
  114764. ** If *pRc is initially non-zero then this routine is a no-op.
  114765. */
  114766. static void fts3DbExec(
  114767. int *pRc, /* Success code */
  114768. sqlite3 *db, /* Database in which to run SQL */
  114769. const char *zFormat, /* Format string for SQL */
  114770. ... /* Arguments to the format string */
  114771. ){
  114772. va_list ap;
  114773. char *zSql;
  114774. if( *pRc ) return;
  114775. va_start(ap, zFormat);
  114776. zSql = sqlite3_vmprintf(zFormat, ap);
  114777. va_end(ap);
  114778. if( zSql==0 ){
  114779. *pRc = SQLITE_NOMEM;
  114780. }else{
  114781. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  114782. sqlite3_free(zSql);
  114783. }
  114784. }
  114785. /*
  114786. ** The xDestroy() virtual table method.
  114787. */
  114788. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  114789. Fts3Table *p = (Fts3Table *)pVtab;
  114790. int rc = SQLITE_OK; /* Return code */
  114791. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  114792. sqlite3 *db = p->db; /* Database handle */
  114793. /* Drop the shadow tables */
  114794. if( p->zContentTbl==0 ){
  114795. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  114796. }
  114797. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  114798. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  114799. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  114800. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  114801. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  114802. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  114803. ** Otherwise, return an SQLite error code.
  114804. */
  114805. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  114806. }
  114807. /*
  114808. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  114809. ** passed as the first argument. This is done as part of the xConnect()
  114810. ** and xCreate() methods.
  114811. **
  114812. ** If *pRc is non-zero when this function is called, it is a no-op.
  114813. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  114814. ** before returning.
  114815. */
  114816. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  114817. if( *pRc==SQLITE_OK ){
  114818. int i; /* Iterator variable */
  114819. int rc; /* Return code */
  114820. char *zSql; /* SQL statement passed to declare_vtab() */
  114821. char *zCols; /* List of user defined columns */
  114822. const char *zLanguageid;
  114823. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  114824. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  114825. /* Create a list of user columns for the virtual table */
  114826. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  114827. for(i=1; zCols && i<p->nColumn; i++){
  114828. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  114829. }
  114830. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  114831. zSql = sqlite3_mprintf(
  114832. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  114833. zCols, p->zName, zLanguageid
  114834. );
  114835. if( !zCols || !zSql ){
  114836. rc = SQLITE_NOMEM;
  114837. }else{
  114838. rc = sqlite3_declare_vtab(p->db, zSql);
  114839. }
  114840. sqlite3_free(zSql);
  114841. sqlite3_free(zCols);
  114842. *pRc = rc;
  114843. }
  114844. }
  114845. /*
  114846. ** Create the %_stat table if it does not already exist.
  114847. */
  114848. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  114849. fts3DbExec(pRc, p->db,
  114850. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  114851. "(id INTEGER PRIMARY KEY, value BLOB);",
  114852. p->zDb, p->zName
  114853. );
  114854. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  114855. }
  114856. /*
  114857. ** Create the backing store tables (%_content, %_segments and %_segdir)
  114858. ** required by the FTS3 table passed as the only argument. This is done
  114859. ** as part of the vtab xCreate() method.
  114860. **
  114861. ** If the p->bHasDocsize boolean is true (indicating that this is an
  114862. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  114863. ** %_stat tables required by FTS4.
  114864. */
  114865. static int fts3CreateTables(Fts3Table *p){
  114866. int rc = SQLITE_OK; /* Return code */
  114867. int i; /* Iterator variable */
  114868. sqlite3 *db = p->db; /* The database connection */
  114869. if( p->zContentTbl==0 ){
  114870. const char *zLanguageid = p->zLanguageid;
  114871. char *zContentCols; /* Columns of %_content table */
  114872. /* Create a list of user columns for the content table */
  114873. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  114874. for(i=0; zContentCols && i<p->nColumn; i++){
  114875. char *z = p->azColumn[i];
  114876. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  114877. }
  114878. if( zLanguageid && zContentCols ){
  114879. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  114880. }
  114881. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  114882. /* Create the content table */
  114883. fts3DbExec(&rc, db,
  114884. "CREATE TABLE %Q.'%q_content'(%s)",
  114885. p->zDb, p->zName, zContentCols
  114886. );
  114887. sqlite3_free(zContentCols);
  114888. }
  114889. /* Create other tables */
  114890. fts3DbExec(&rc, db,
  114891. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  114892. p->zDb, p->zName
  114893. );
  114894. fts3DbExec(&rc, db,
  114895. "CREATE TABLE %Q.'%q_segdir'("
  114896. "level INTEGER,"
  114897. "idx INTEGER,"
  114898. "start_block INTEGER,"
  114899. "leaves_end_block INTEGER,"
  114900. "end_block INTEGER,"
  114901. "root BLOB,"
  114902. "PRIMARY KEY(level, idx)"
  114903. ");",
  114904. p->zDb, p->zName
  114905. );
  114906. if( p->bHasDocsize ){
  114907. fts3DbExec(&rc, db,
  114908. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  114909. p->zDb, p->zName
  114910. );
  114911. }
  114912. assert( p->bHasStat==p->bFts4 );
  114913. if( p->bHasStat ){
  114914. sqlite3Fts3CreateStatTable(&rc, p);
  114915. }
  114916. return rc;
  114917. }
  114918. /*
  114919. ** Store the current database page-size in bytes in p->nPgsz.
  114920. **
  114921. ** If *pRc is non-zero when this function is called, it is a no-op.
  114922. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  114923. ** before returning.
  114924. */
  114925. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  114926. if( *pRc==SQLITE_OK ){
  114927. int rc; /* Return code */
  114928. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  114929. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  114930. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  114931. if( !zSql ){
  114932. rc = SQLITE_NOMEM;
  114933. }else{
  114934. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  114935. if( rc==SQLITE_OK ){
  114936. sqlite3_step(pStmt);
  114937. p->nPgsz = sqlite3_column_int(pStmt, 0);
  114938. rc = sqlite3_finalize(pStmt);
  114939. }else if( rc==SQLITE_AUTH ){
  114940. p->nPgsz = 1024;
  114941. rc = SQLITE_OK;
  114942. }
  114943. }
  114944. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  114945. sqlite3_free(zSql);
  114946. *pRc = rc;
  114947. }
  114948. }
  114949. /*
  114950. ** "Special" FTS4 arguments are column specifications of the following form:
  114951. **
  114952. ** <key> = <value>
  114953. **
  114954. ** There may not be whitespace surrounding the "=" character. The <value>
  114955. ** term may be quoted, but the <key> may not.
  114956. */
  114957. static int fts3IsSpecialColumn(
  114958. const char *z,
  114959. int *pnKey,
  114960. char **pzValue
  114961. ){
  114962. char *zValue;
  114963. const char *zCsr = z;
  114964. while( *zCsr!='=' ){
  114965. if( *zCsr=='\0' ) return 0;
  114966. zCsr++;
  114967. }
  114968. *pnKey = (int)(zCsr-z);
  114969. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  114970. if( zValue ){
  114971. sqlite3Fts3Dequote(zValue);
  114972. }
  114973. *pzValue = zValue;
  114974. return 1;
  114975. }
  114976. /*
  114977. ** Append the output of a printf() style formatting to an existing string.
  114978. */
  114979. static void fts3Appendf(
  114980. int *pRc, /* IN/OUT: Error code */
  114981. char **pz, /* IN/OUT: Pointer to string buffer */
  114982. const char *zFormat, /* Printf format string to append */
  114983. ... /* Arguments for printf format string */
  114984. ){
  114985. if( *pRc==SQLITE_OK ){
  114986. va_list ap;
  114987. char *z;
  114988. va_start(ap, zFormat);
  114989. z = sqlite3_vmprintf(zFormat, ap);
  114990. va_end(ap);
  114991. if( z && *pz ){
  114992. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  114993. sqlite3_free(z);
  114994. z = z2;
  114995. }
  114996. if( z==0 ) *pRc = SQLITE_NOMEM;
  114997. sqlite3_free(*pz);
  114998. *pz = z;
  114999. }
  115000. }
  115001. /*
  115002. ** Return a copy of input string zInput enclosed in double-quotes (") and
  115003. ** with all double quote characters escaped. For example:
  115004. **
  115005. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  115006. **
  115007. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  115008. ** is the callers responsibility to call sqlite3_free() to release this
  115009. ** memory.
  115010. */
  115011. static char *fts3QuoteId(char const *zInput){
  115012. int nRet;
  115013. char *zRet;
  115014. nRet = 2 + (int)strlen(zInput)*2 + 1;
  115015. zRet = sqlite3_malloc(nRet);
  115016. if( zRet ){
  115017. int i;
  115018. char *z = zRet;
  115019. *(z++) = '"';
  115020. for(i=0; zInput[i]; i++){
  115021. if( zInput[i]=='"' ) *(z++) = '"';
  115022. *(z++) = zInput[i];
  115023. }
  115024. *(z++) = '"';
  115025. *(z++) = '\0';
  115026. }
  115027. return zRet;
  115028. }
  115029. /*
  115030. ** Return a list of comma separated SQL expressions and a FROM clause that
  115031. ** could be used in a SELECT statement such as the following:
  115032. **
  115033. ** SELECT <list of expressions> FROM %_content AS x ...
  115034. **
  115035. ** to return the docid, followed by each column of text data in order
  115036. ** from left to write. If parameter zFunc is not NULL, then instead of
  115037. ** being returned directly each column of text data is passed to an SQL
  115038. ** function named zFunc first. For example, if zFunc is "unzip" and the
  115039. ** table has the three user-defined columns "a", "b", and "c", the following
  115040. ** string is returned:
  115041. **
  115042. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  115043. **
  115044. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  115045. ** is the responsibility of the caller to eventually free it.
  115046. **
  115047. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  115048. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  115049. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  115050. ** no error occurs, *pRc is left unmodified.
  115051. */
  115052. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  115053. char *zRet = 0;
  115054. char *zFree = 0;
  115055. char *zFunction;
  115056. int i;
  115057. if( p->zContentTbl==0 ){
  115058. if( !zFunc ){
  115059. zFunction = "";
  115060. }else{
  115061. zFree = zFunction = fts3QuoteId(zFunc);
  115062. }
  115063. fts3Appendf(pRc, &zRet, "docid");
  115064. for(i=0; i<p->nColumn; i++){
  115065. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  115066. }
  115067. if( p->zLanguageid ){
  115068. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  115069. }
  115070. sqlite3_free(zFree);
  115071. }else{
  115072. fts3Appendf(pRc, &zRet, "rowid");
  115073. for(i=0; i<p->nColumn; i++){
  115074. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  115075. }
  115076. if( p->zLanguageid ){
  115077. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  115078. }
  115079. }
  115080. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  115081. p->zDb,
  115082. (p->zContentTbl ? p->zContentTbl : p->zName),
  115083. (p->zContentTbl ? "" : "_content")
  115084. );
  115085. return zRet;
  115086. }
  115087. /*
  115088. ** Return a list of N comma separated question marks, where N is the number
  115089. ** of columns in the %_content table (one for the docid plus one for each
  115090. ** user-defined text column).
  115091. **
  115092. ** If argument zFunc is not NULL, then all but the first question mark
  115093. ** is preceded by zFunc and an open bracket, and followed by a closed
  115094. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  115095. ** user-defined text columns, the following string is returned:
  115096. **
  115097. ** "?, zip(?), zip(?), zip(?)"
  115098. **
  115099. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  115100. ** is the responsibility of the caller to eventually free it.
  115101. **
  115102. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  115103. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  115104. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  115105. ** no error occurs, *pRc is left unmodified.
  115106. */
  115107. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  115108. char *zRet = 0;
  115109. char *zFree = 0;
  115110. char *zFunction;
  115111. int i;
  115112. if( !zFunc ){
  115113. zFunction = "";
  115114. }else{
  115115. zFree = zFunction = fts3QuoteId(zFunc);
  115116. }
  115117. fts3Appendf(pRc, &zRet, "?");
  115118. for(i=0; i<p->nColumn; i++){
  115119. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  115120. }
  115121. if( p->zLanguageid ){
  115122. fts3Appendf(pRc, &zRet, ", ?");
  115123. }
  115124. sqlite3_free(zFree);
  115125. return zRet;
  115126. }
  115127. /*
  115128. ** This function interprets the string at (*pp) as a non-negative integer
  115129. ** value. It reads the integer and sets *pnOut to the value read, then
  115130. ** sets *pp to point to the byte immediately following the last byte of
  115131. ** the integer value.
  115132. **
  115133. ** Only decimal digits ('0'..'9') may be part of an integer value.
  115134. **
  115135. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  115136. ** the output value undefined. Otherwise SQLITE_OK is returned.
  115137. **
  115138. ** This function is used when parsing the "prefix=" FTS4 parameter.
  115139. */
  115140. static int fts3GobbleInt(const char **pp, int *pnOut){
  115141. const char *p; /* Iterator pointer */
  115142. int nInt = 0; /* Output value */
  115143. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  115144. nInt = nInt * 10 + (p[0] - '0');
  115145. }
  115146. if( p==*pp ) return SQLITE_ERROR;
  115147. *pnOut = nInt;
  115148. *pp = p;
  115149. return SQLITE_OK;
  115150. }
  115151. /*
  115152. ** This function is called to allocate an array of Fts3Index structures
  115153. ** representing the indexes maintained by the current FTS table. FTS tables
  115154. ** always maintain the main "terms" index, but may also maintain one or
  115155. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  115156. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  115157. **
  115158. ** Argument zParam is passed the value of the "prefix=" option if one was
  115159. ** specified, or NULL otherwise.
  115160. **
  115161. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  115162. ** the allocated array. *pnIndex is set to the number of elements in the
  115163. ** array. If an error does occur, an SQLite error code is returned.
  115164. **
  115165. ** Regardless of whether or not an error is returned, it is the responsibility
  115166. ** of the caller to call sqlite3_free() on the output array to free it.
  115167. */
  115168. static int fts3PrefixParameter(
  115169. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  115170. int *pnIndex, /* OUT: size of *apIndex[] array */
  115171. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  115172. ){
  115173. struct Fts3Index *aIndex; /* Allocated array */
  115174. int nIndex = 1; /* Number of entries in array */
  115175. if( zParam && zParam[0] ){
  115176. const char *p;
  115177. nIndex++;
  115178. for(p=zParam; *p; p++){
  115179. if( *p==',' ) nIndex++;
  115180. }
  115181. }
  115182. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  115183. *apIndex = aIndex;
  115184. *pnIndex = nIndex;
  115185. if( !aIndex ){
  115186. return SQLITE_NOMEM;
  115187. }
  115188. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  115189. if( zParam ){
  115190. const char *p = zParam;
  115191. int i;
  115192. for(i=1; i<nIndex; i++){
  115193. int nPrefix;
  115194. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  115195. aIndex[i].nPrefix = nPrefix;
  115196. p++;
  115197. }
  115198. }
  115199. return SQLITE_OK;
  115200. }
  115201. /*
  115202. ** This function is called when initializing an FTS4 table that uses the
  115203. ** content=xxx option. It determines the number of and names of the columns
  115204. ** of the new FTS4 table.
  115205. **
  115206. ** The third argument passed to this function is the value passed to the
  115207. ** config=xxx option (i.e. "xxx"). This function queries the database for
  115208. ** a table of that name. If found, the output variables are populated
  115209. ** as follows:
  115210. **
  115211. ** *pnCol: Set to the number of columns table xxx has,
  115212. **
  115213. ** *pnStr: Set to the total amount of space required to store a copy
  115214. ** of each columns name, including the nul-terminator.
  115215. **
  115216. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  115217. ** the name of the corresponding column in table xxx. The array
  115218. ** and its contents are allocated using a single allocation. It
  115219. ** is the responsibility of the caller to free this allocation
  115220. ** by eventually passing the *pazCol value to sqlite3_free().
  115221. **
  115222. ** If the table cannot be found, an error code is returned and the output
  115223. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  115224. ** returned (and the output variables are undefined).
  115225. */
  115226. static int fts3ContentColumns(
  115227. sqlite3 *db, /* Database handle */
  115228. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  115229. const char *zTbl, /* Name of content table */
  115230. const char ***pazCol, /* OUT: Malloc'd array of column names */
  115231. int *pnCol, /* OUT: Size of array *pazCol */
  115232. int *pnStr /* OUT: Bytes of string content */
  115233. ){
  115234. int rc = SQLITE_OK; /* Return code */
  115235. char *zSql; /* "SELECT *" statement on zTbl */
  115236. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  115237. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  115238. if( !zSql ){
  115239. rc = SQLITE_NOMEM;
  115240. }else{
  115241. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  115242. }
  115243. sqlite3_free(zSql);
  115244. if( rc==SQLITE_OK ){
  115245. const char **azCol; /* Output array */
  115246. int nStr = 0; /* Size of all column names (incl. 0x00) */
  115247. int nCol; /* Number of table columns */
  115248. int i; /* Used to iterate through columns */
  115249. /* Loop through the returned columns. Set nStr to the number of bytes of
  115250. ** space required to store a copy of each column name, including the
  115251. ** nul-terminator byte. */
  115252. nCol = sqlite3_column_count(pStmt);
  115253. for(i=0; i<nCol; i++){
  115254. const char *zCol = sqlite3_column_name(pStmt, i);
  115255. nStr += (int)strlen(zCol) + 1;
  115256. }
  115257. /* Allocate and populate the array to return. */
  115258. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  115259. if( azCol==0 ){
  115260. rc = SQLITE_NOMEM;
  115261. }else{
  115262. char *p = (char *)&azCol[nCol];
  115263. for(i=0; i<nCol; i++){
  115264. const char *zCol = sqlite3_column_name(pStmt, i);
  115265. int n = (int)strlen(zCol)+1;
  115266. memcpy(p, zCol, n);
  115267. azCol[i] = p;
  115268. p += n;
  115269. }
  115270. }
  115271. sqlite3_finalize(pStmt);
  115272. /* Set the output variables. */
  115273. *pnCol = nCol;
  115274. *pnStr = nStr;
  115275. *pazCol = azCol;
  115276. }
  115277. return rc;
  115278. }
  115279. /*
  115280. ** This function is the implementation of both the xConnect and xCreate
  115281. ** methods of the FTS3 virtual table.
  115282. **
  115283. ** The argv[] array contains the following:
  115284. **
  115285. ** argv[0] -> module name ("fts3" or "fts4")
  115286. ** argv[1] -> database name
  115287. ** argv[2] -> table name
  115288. ** argv[...] -> "column name" and other module argument fields.
  115289. */
  115290. static int fts3InitVtab(
  115291. int isCreate, /* True for xCreate, false for xConnect */
  115292. sqlite3 *db, /* The SQLite database connection */
  115293. void *pAux, /* Hash table containing tokenizers */
  115294. int argc, /* Number of elements in argv array */
  115295. const char * const *argv, /* xCreate/xConnect argument array */
  115296. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  115297. char **pzErr /* Write any error message here */
  115298. ){
  115299. Fts3Hash *pHash = (Fts3Hash *)pAux;
  115300. Fts3Table *p = 0; /* Pointer to allocated vtab */
  115301. int rc = SQLITE_OK; /* Return code */
  115302. int i; /* Iterator variable */
  115303. int nByte; /* Size of allocation used for *p */
  115304. int iCol; /* Column index */
  115305. int nString = 0; /* Bytes required to hold all column names */
  115306. int nCol = 0; /* Number of columns in the FTS table */
  115307. char *zCsr; /* Space for holding column names */
  115308. int nDb; /* Bytes required to hold database name */
  115309. int nName; /* Bytes required to hold table name */
  115310. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  115311. const char **aCol; /* Array of column names */
  115312. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  115313. int nIndex; /* Size of aIndex[] array */
  115314. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  115315. /* The results of parsing supported FTS4 key=value options: */
  115316. int bNoDocsize = 0; /* True to omit %_docsize table */
  115317. int bDescIdx = 0; /* True to store descending indexes */
  115318. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  115319. char *zCompress = 0; /* compress=? parameter (or NULL) */
  115320. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  115321. char *zContent = 0; /* content=? parameter (or NULL) */
  115322. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  115323. char **azNotindexed = 0; /* The set of notindexed= columns */
  115324. int nNotindexed = 0; /* Size of azNotindexed[] array */
  115325. assert( strlen(argv[0])==4 );
  115326. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  115327. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  115328. );
  115329. nDb = (int)strlen(argv[1]) + 1;
  115330. nName = (int)strlen(argv[2]) + 1;
  115331. nByte = sizeof(const char *) * (argc-2);
  115332. aCol = (const char **)sqlite3_malloc(nByte);
  115333. if( aCol ){
  115334. memset((void*)aCol, 0, nByte);
  115335. azNotindexed = (char **)sqlite3_malloc(nByte);
  115336. }
  115337. if( azNotindexed ){
  115338. memset(azNotindexed, 0, nByte);
  115339. }
  115340. if( !aCol || !azNotindexed ){
  115341. rc = SQLITE_NOMEM;
  115342. goto fts3_init_out;
  115343. }
  115344. /* Loop through all of the arguments passed by the user to the FTS3/4
  115345. ** module (i.e. all the column names and special arguments). This loop
  115346. ** does the following:
  115347. **
  115348. ** + Figures out the number of columns the FTSX table will have, and
  115349. ** the number of bytes of space that must be allocated to store copies
  115350. ** of the column names.
  115351. **
  115352. ** + If there is a tokenizer specification included in the arguments,
  115353. ** initializes the tokenizer pTokenizer.
  115354. */
  115355. for(i=3; rc==SQLITE_OK && i<argc; i++){
  115356. char const *z = argv[i];
  115357. int nKey;
  115358. char *zVal;
  115359. /* Check if this is a tokenizer specification */
  115360. if( !pTokenizer
  115361. && strlen(z)>8
  115362. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  115363. && 0==sqlite3Fts3IsIdChar(z[8])
  115364. ){
  115365. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  115366. }
  115367. /* Check if it is an FTS4 special argument. */
  115368. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  115369. struct Fts4Option {
  115370. const char *zOpt;
  115371. int nOpt;
  115372. } aFts4Opt[] = {
  115373. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  115374. { "prefix", 6 }, /* 1 -> PREFIX */
  115375. { "compress", 8 }, /* 2 -> COMPRESS */
  115376. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  115377. { "order", 5 }, /* 4 -> ORDER */
  115378. { "content", 7 }, /* 5 -> CONTENT */
  115379. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  115380. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  115381. };
  115382. int iOpt;
  115383. if( !zVal ){
  115384. rc = SQLITE_NOMEM;
  115385. }else{
  115386. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  115387. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  115388. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  115389. break;
  115390. }
  115391. }
  115392. if( iOpt==SizeofArray(aFts4Opt) ){
  115393. *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
  115394. rc = SQLITE_ERROR;
  115395. }else{
  115396. switch( iOpt ){
  115397. case 0: /* MATCHINFO */
  115398. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  115399. *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
  115400. rc = SQLITE_ERROR;
  115401. }
  115402. bNoDocsize = 1;
  115403. break;
  115404. case 1: /* PREFIX */
  115405. sqlite3_free(zPrefix);
  115406. zPrefix = zVal;
  115407. zVal = 0;
  115408. break;
  115409. case 2: /* COMPRESS */
  115410. sqlite3_free(zCompress);
  115411. zCompress = zVal;
  115412. zVal = 0;
  115413. break;
  115414. case 3: /* UNCOMPRESS */
  115415. sqlite3_free(zUncompress);
  115416. zUncompress = zVal;
  115417. zVal = 0;
  115418. break;
  115419. case 4: /* ORDER */
  115420. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  115421. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  115422. ){
  115423. *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
  115424. rc = SQLITE_ERROR;
  115425. }
  115426. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  115427. break;
  115428. case 5: /* CONTENT */
  115429. sqlite3_free(zContent);
  115430. zContent = zVal;
  115431. zVal = 0;
  115432. break;
  115433. case 6: /* LANGUAGEID */
  115434. assert( iOpt==6 );
  115435. sqlite3_free(zLanguageid);
  115436. zLanguageid = zVal;
  115437. zVal = 0;
  115438. break;
  115439. case 7: /* NOTINDEXED */
  115440. azNotindexed[nNotindexed++] = zVal;
  115441. zVal = 0;
  115442. break;
  115443. }
  115444. }
  115445. sqlite3_free(zVal);
  115446. }
  115447. }
  115448. /* Otherwise, the argument is a column name. */
  115449. else {
  115450. nString += (int)(strlen(z) + 1);
  115451. aCol[nCol++] = z;
  115452. }
  115453. }
  115454. /* If a content=xxx option was specified, the following:
  115455. **
  115456. ** 1. Ignore any compress= and uncompress= options.
  115457. **
  115458. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  115459. ** TABLE statement, use all columns from the content table.
  115460. */
  115461. if( rc==SQLITE_OK && zContent ){
  115462. sqlite3_free(zCompress);
  115463. sqlite3_free(zUncompress);
  115464. zCompress = 0;
  115465. zUncompress = 0;
  115466. if( nCol==0 ){
  115467. sqlite3_free((void*)aCol);
  115468. aCol = 0;
  115469. rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
  115470. /* If a languageid= option was specified, remove the language id
  115471. ** column from the aCol[] array. */
  115472. if( rc==SQLITE_OK && zLanguageid ){
  115473. int j;
  115474. for(j=0; j<nCol; j++){
  115475. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  115476. int k;
  115477. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  115478. nCol--;
  115479. break;
  115480. }
  115481. }
  115482. }
  115483. }
  115484. }
  115485. if( rc!=SQLITE_OK ) goto fts3_init_out;
  115486. if( nCol==0 ){
  115487. assert( nString==0 );
  115488. aCol[0] = "content";
  115489. nString = 8;
  115490. nCol = 1;
  115491. }
  115492. if( pTokenizer==0 ){
  115493. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  115494. if( rc!=SQLITE_OK ) goto fts3_init_out;
  115495. }
  115496. assert( pTokenizer );
  115497. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  115498. if( rc==SQLITE_ERROR ){
  115499. assert( zPrefix );
  115500. *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
  115501. }
  115502. if( rc!=SQLITE_OK ) goto fts3_init_out;
  115503. /* Allocate and populate the Fts3Table structure. */
  115504. nByte = sizeof(Fts3Table) + /* Fts3Table */
  115505. nCol * sizeof(char *) + /* azColumn */
  115506. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  115507. nCol * sizeof(u8) + /* abNotindexed */
  115508. nName + /* zName */
  115509. nDb + /* zDb */
  115510. nString; /* Space for azColumn strings */
  115511. p = (Fts3Table*)sqlite3_malloc(nByte);
  115512. if( p==0 ){
  115513. rc = SQLITE_NOMEM;
  115514. goto fts3_init_out;
  115515. }
  115516. memset(p, 0, nByte);
  115517. p->db = db;
  115518. p->nColumn = nCol;
  115519. p->nPendingData = 0;
  115520. p->azColumn = (char **)&p[1];
  115521. p->pTokenizer = pTokenizer;
  115522. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  115523. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  115524. p->bHasStat = isFts4;
  115525. p->bFts4 = isFts4;
  115526. p->bDescIdx = bDescIdx;
  115527. p->bAutoincrmerge = 0xff; /* 0xff means setting unknown */
  115528. p->zContentTbl = zContent;
  115529. p->zLanguageid = zLanguageid;
  115530. zContent = 0;
  115531. zLanguageid = 0;
  115532. TESTONLY( p->inTransaction = -1 );
  115533. TESTONLY( p->mxSavepoint = -1 );
  115534. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  115535. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  115536. p->nIndex = nIndex;
  115537. for(i=0; i<nIndex; i++){
  115538. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  115539. }
  115540. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  115541. /* Fill in the zName and zDb fields of the vtab structure. */
  115542. zCsr = (char *)&p->abNotindexed[nCol];
  115543. p->zName = zCsr;
  115544. memcpy(zCsr, argv[2], nName);
  115545. zCsr += nName;
  115546. p->zDb = zCsr;
  115547. memcpy(zCsr, argv[1], nDb);
  115548. zCsr += nDb;
  115549. /* Fill in the azColumn array */
  115550. for(iCol=0; iCol<nCol; iCol++){
  115551. char *z;
  115552. int n = 0;
  115553. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  115554. memcpy(zCsr, z, n);
  115555. zCsr[n] = '\0';
  115556. sqlite3Fts3Dequote(zCsr);
  115557. p->azColumn[iCol] = zCsr;
  115558. zCsr += n+1;
  115559. assert( zCsr <= &((char *)p)[nByte] );
  115560. }
  115561. /* Fill in the abNotindexed array */
  115562. for(iCol=0; iCol<nCol; iCol++){
  115563. int n = (int)strlen(p->azColumn[iCol]);
  115564. for(i=0; i<nNotindexed; i++){
  115565. char *zNot = azNotindexed[i];
  115566. if( zNot && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) ){
  115567. p->abNotindexed[iCol] = 1;
  115568. sqlite3_free(zNot);
  115569. azNotindexed[i] = 0;
  115570. }
  115571. }
  115572. }
  115573. for(i=0; i<nNotindexed; i++){
  115574. if( azNotindexed[i] ){
  115575. *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
  115576. rc = SQLITE_ERROR;
  115577. }
  115578. }
  115579. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  115580. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  115581. rc = SQLITE_ERROR;
  115582. *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
  115583. }
  115584. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  115585. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  115586. if( rc!=SQLITE_OK ) goto fts3_init_out;
  115587. /* If this is an xCreate call, create the underlying tables in the
  115588. ** database. TODO: For xConnect(), it could verify that said tables exist.
  115589. */
  115590. if( isCreate ){
  115591. rc = fts3CreateTables(p);
  115592. }
  115593. /* Check to see if a legacy fts3 table has been "upgraded" by the
  115594. ** addition of a %_stat table so that it can use incremental merge.
  115595. */
  115596. if( !isFts4 && !isCreate ){
  115597. int rc2 = SQLITE_OK;
  115598. fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
  115599. p->zDb, p->zName);
  115600. if( rc2==SQLITE_OK ) p->bHasStat = 1;
  115601. }
  115602. /* Figure out the page-size for the database. This is required in order to
  115603. ** estimate the cost of loading large doclists from the database. */
  115604. fts3DatabasePageSize(&rc, p);
  115605. p->nNodeSize = p->nPgsz-35;
  115606. /* Declare the table schema to SQLite. */
  115607. fts3DeclareVtab(&rc, p);
  115608. fts3_init_out:
  115609. sqlite3_free(zPrefix);
  115610. sqlite3_free(aIndex);
  115611. sqlite3_free(zCompress);
  115612. sqlite3_free(zUncompress);
  115613. sqlite3_free(zContent);
  115614. sqlite3_free(zLanguageid);
  115615. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  115616. sqlite3_free((void *)aCol);
  115617. sqlite3_free((void *)azNotindexed);
  115618. if( rc!=SQLITE_OK ){
  115619. if( p ){
  115620. fts3DisconnectMethod((sqlite3_vtab *)p);
  115621. }else if( pTokenizer ){
  115622. pTokenizer->pModule->xDestroy(pTokenizer);
  115623. }
  115624. }else{
  115625. assert( p->pSegments==0 );
  115626. *ppVTab = &p->base;
  115627. }
  115628. return rc;
  115629. }
  115630. /*
  115631. ** The xConnect() and xCreate() methods for the virtual table. All the
  115632. ** work is done in function fts3InitVtab().
  115633. */
  115634. static int fts3ConnectMethod(
  115635. sqlite3 *db, /* Database connection */
  115636. void *pAux, /* Pointer to tokenizer hash table */
  115637. int argc, /* Number of elements in argv array */
  115638. const char * const *argv, /* xCreate/xConnect argument array */
  115639. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  115640. char **pzErr /* OUT: sqlite3_malloc'd error message */
  115641. ){
  115642. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  115643. }
  115644. static int fts3CreateMethod(
  115645. sqlite3 *db, /* Database connection */
  115646. void *pAux, /* Pointer to tokenizer hash table */
  115647. int argc, /* Number of elements in argv array */
  115648. const char * const *argv, /* xCreate/xConnect argument array */
  115649. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  115650. char **pzErr /* OUT: sqlite3_malloc'd error message */
  115651. ){
  115652. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  115653. }
  115654. /*
  115655. ** Implementation of the xBestIndex method for FTS3 tables. There
  115656. ** are three possible strategies, in order of preference:
  115657. **
  115658. ** 1. Direct lookup by rowid or docid.
  115659. ** 2. Full-text search using a MATCH operator on a non-docid column.
  115660. ** 3. Linear scan of %_content table.
  115661. */
  115662. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  115663. Fts3Table *p = (Fts3Table *)pVTab;
  115664. int i; /* Iterator variable */
  115665. int iCons = -1; /* Index of constraint to use */
  115666. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  115667. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  115668. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  115669. int iIdx;
  115670. /* By default use a full table scan. This is an expensive option,
  115671. ** so search through the constraints to see if a more efficient
  115672. ** strategy is possible.
  115673. */
  115674. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  115675. pInfo->estimatedCost = 5000000;
  115676. for(i=0; i<pInfo->nConstraint; i++){
  115677. int bDocid; /* True if this constraint is on docid */
  115678. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  115679. if( pCons->usable==0 ) continue;
  115680. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  115681. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  115682. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  115683. pInfo->idxNum = FTS3_DOCID_SEARCH;
  115684. pInfo->estimatedCost = 1.0;
  115685. iCons = i;
  115686. }
  115687. /* A MATCH constraint. Use a full-text search.
  115688. **
  115689. ** If there is more than one MATCH constraint available, use the first
  115690. ** one encountered. If there is both a MATCH constraint and a direct
  115691. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  115692. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  115693. ** it would lead to an "unable to use function MATCH in the requested
  115694. ** context" error.
  115695. */
  115696. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  115697. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  115698. ){
  115699. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  115700. pInfo->estimatedCost = 2.0;
  115701. iCons = i;
  115702. }
  115703. /* Equality constraint on the langid column */
  115704. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  115705. && pCons->iColumn==p->nColumn + 2
  115706. ){
  115707. iLangidCons = i;
  115708. }
  115709. if( bDocid ){
  115710. switch( pCons->op ){
  115711. case SQLITE_INDEX_CONSTRAINT_GE:
  115712. case SQLITE_INDEX_CONSTRAINT_GT:
  115713. iDocidGe = i;
  115714. break;
  115715. case SQLITE_INDEX_CONSTRAINT_LE:
  115716. case SQLITE_INDEX_CONSTRAINT_LT:
  115717. iDocidLe = i;
  115718. break;
  115719. }
  115720. }
  115721. }
  115722. iIdx = 1;
  115723. if( iCons>=0 ){
  115724. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  115725. pInfo->aConstraintUsage[iCons].omit = 1;
  115726. }
  115727. if( iLangidCons>=0 ){
  115728. pInfo->idxNum |= FTS3_HAVE_LANGID;
  115729. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  115730. }
  115731. if( iDocidGe>=0 ){
  115732. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  115733. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  115734. }
  115735. if( iDocidLe>=0 ){
  115736. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  115737. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  115738. }
  115739. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  115740. ** docid) order. Both ascending and descending are possible.
  115741. */
  115742. if( pInfo->nOrderBy==1 ){
  115743. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  115744. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  115745. if( pOrder->desc ){
  115746. pInfo->idxStr = "DESC";
  115747. }else{
  115748. pInfo->idxStr = "ASC";
  115749. }
  115750. pInfo->orderByConsumed = 1;
  115751. }
  115752. }
  115753. assert( p->pSegments==0 );
  115754. return SQLITE_OK;
  115755. }
  115756. /*
  115757. ** Implementation of xOpen method.
  115758. */
  115759. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  115760. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  115761. UNUSED_PARAMETER(pVTab);
  115762. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  115763. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  115764. ** if the allocation fails, return SQLITE_NOMEM.
  115765. */
  115766. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  115767. if( !pCsr ){
  115768. return SQLITE_NOMEM;
  115769. }
  115770. memset(pCsr, 0, sizeof(Fts3Cursor));
  115771. return SQLITE_OK;
  115772. }
  115773. /*
  115774. ** Close the cursor. For additional information see the documentation
  115775. ** on the xClose method of the virtual table interface.
  115776. */
  115777. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  115778. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  115779. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  115780. sqlite3_finalize(pCsr->pStmt);
  115781. sqlite3Fts3ExprFree(pCsr->pExpr);
  115782. sqlite3Fts3FreeDeferredTokens(pCsr);
  115783. sqlite3_free(pCsr->aDoclist);
  115784. sqlite3_free(pCsr->aMatchinfo);
  115785. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  115786. sqlite3_free(pCsr);
  115787. return SQLITE_OK;
  115788. }
  115789. /*
  115790. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  115791. ** compose and prepare an SQL statement of the form:
  115792. **
  115793. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  115794. **
  115795. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  115796. ** it. If an error occurs, return an SQLite error code.
  115797. **
  115798. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  115799. */
  115800. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  115801. int rc = SQLITE_OK;
  115802. if( pCsr->pStmt==0 ){
  115803. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  115804. char *zSql;
  115805. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  115806. if( !zSql ) return SQLITE_NOMEM;
  115807. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  115808. sqlite3_free(zSql);
  115809. }
  115810. *ppStmt = pCsr->pStmt;
  115811. return rc;
  115812. }
  115813. /*
  115814. ** Position the pCsr->pStmt statement so that it is on the row
  115815. ** of the %_content table that contains the last match. Return
  115816. ** SQLITE_OK on success.
  115817. */
  115818. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  115819. int rc = SQLITE_OK;
  115820. if( pCsr->isRequireSeek ){
  115821. sqlite3_stmt *pStmt = 0;
  115822. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  115823. if( rc==SQLITE_OK ){
  115824. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  115825. pCsr->isRequireSeek = 0;
  115826. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  115827. return SQLITE_OK;
  115828. }else{
  115829. rc = sqlite3_reset(pCsr->pStmt);
  115830. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  115831. /* If no row was found and no error has occurred, then the %_content
  115832. ** table is missing a row that is present in the full-text index.
  115833. ** The data structures are corrupt. */
  115834. rc = FTS_CORRUPT_VTAB;
  115835. pCsr->isEof = 1;
  115836. }
  115837. }
  115838. }
  115839. }
  115840. if( rc!=SQLITE_OK && pContext ){
  115841. sqlite3_result_error_code(pContext, rc);
  115842. }
  115843. return rc;
  115844. }
  115845. /*
  115846. ** This function is used to process a single interior node when searching
  115847. ** a b-tree for a term or term prefix. The node data is passed to this
  115848. ** function via the zNode/nNode parameters. The term to search for is
  115849. ** passed in zTerm/nTerm.
  115850. **
  115851. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  115852. ** of the child node that heads the sub-tree that may contain the term.
  115853. **
  115854. ** If piLast is not NULL, then *piLast is set to the right-most child node
  115855. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  115856. ** a prefix.
  115857. **
  115858. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  115859. */
  115860. static int fts3ScanInteriorNode(
  115861. const char *zTerm, /* Term to select leaves for */
  115862. int nTerm, /* Size of term zTerm in bytes */
  115863. const char *zNode, /* Buffer containing segment interior node */
  115864. int nNode, /* Size of buffer at zNode */
  115865. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  115866. sqlite3_int64 *piLast /* OUT: Selected child node */
  115867. ){
  115868. int rc = SQLITE_OK; /* Return code */
  115869. const char *zCsr = zNode; /* Cursor to iterate through node */
  115870. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  115871. char *zBuffer = 0; /* Buffer to load terms into */
  115872. int nAlloc = 0; /* Size of allocated buffer */
  115873. int isFirstTerm = 1; /* True when processing first term on page */
  115874. sqlite3_int64 iChild; /* Block id of child node to descend to */
  115875. /* Skip over the 'height' varint that occurs at the start of every
  115876. ** interior node. Then load the blockid of the left-child of the b-tree
  115877. ** node into variable iChild.
  115878. **
  115879. ** Even if the data structure on disk is corrupted, this (reading two
  115880. ** varints from the buffer) does not risk an overread. If zNode is a
  115881. ** root node, then the buffer comes from a SELECT statement. SQLite does
  115882. ** not make this guarantee explicitly, but in practice there are always
  115883. ** either more than 20 bytes of allocated space following the nNode bytes of
  115884. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  115885. ** table, then there are always 20 bytes of zeroed padding following the
  115886. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  115887. */
  115888. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  115889. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  115890. if( zCsr>zEnd ){
  115891. return FTS_CORRUPT_VTAB;
  115892. }
  115893. while( zCsr<zEnd && (piFirst || piLast) ){
  115894. int cmp; /* memcmp() result */
  115895. int nSuffix; /* Size of term suffix */
  115896. int nPrefix = 0; /* Size of term prefix */
  115897. int nBuffer; /* Total term size */
  115898. /* Load the next term on the node into zBuffer. Use realloc() to expand
  115899. ** the size of zBuffer if required. */
  115900. if( !isFirstTerm ){
  115901. zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
  115902. }
  115903. isFirstTerm = 0;
  115904. zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
  115905. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  115906. rc = FTS_CORRUPT_VTAB;
  115907. goto finish_scan;
  115908. }
  115909. if( nPrefix+nSuffix>nAlloc ){
  115910. char *zNew;
  115911. nAlloc = (nPrefix+nSuffix) * 2;
  115912. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  115913. if( !zNew ){
  115914. rc = SQLITE_NOMEM;
  115915. goto finish_scan;
  115916. }
  115917. zBuffer = zNew;
  115918. }
  115919. assert( zBuffer );
  115920. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  115921. nBuffer = nPrefix + nSuffix;
  115922. zCsr += nSuffix;
  115923. /* Compare the term we are searching for with the term just loaded from
  115924. ** the interior node. If the specified term is greater than or equal
  115925. ** to the term from the interior node, then all terms on the sub-tree
  115926. ** headed by node iChild are smaller than zTerm. No need to search
  115927. ** iChild.
  115928. **
  115929. ** If the interior node term is larger than the specified term, then
  115930. ** the tree headed by iChild may contain the specified term.
  115931. */
  115932. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  115933. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  115934. *piFirst = iChild;
  115935. piFirst = 0;
  115936. }
  115937. if( piLast && cmp<0 ){
  115938. *piLast = iChild;
  115939. piLast = 0;
  115940. }
  115941. iChild++;
  115942. };
  115943. if( piFirst ) *piFirst = iChild;
  115944. if( piLast ) *piLast = iChild;
  115945. finish_scan:
  115946. sqlite3_free(zBuffer);
  115947. return rc;
  115948. }
  115949. /*
  115950. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  115951. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  115952. ** contains a term. This function searches the sub-tree headed by the zNode
  115953. ** node for the range of leaf nodes that may contain the specified term
  115954. ** or terms for which the specified term is a prefix.
  115955. **
  115956. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  115957. ** left-most leaf node in the tree that may contain the specified term.
  115958. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  115959. ** right-most leaf node that may contain a term for which the specified
  115960. ** term is a prefix.
  115961. **
  115962. ** It is possible that the range of returned leaf nodes does not contain
  115963. ** the specified term or any terms for which it is a prefix. However, if the
  115964. ** segment does contain any such terms, they are stored within the identified
  115965. ** range. Because this function only inspects interior segment nodes (and
  115966. ** never loads leaf nodes into memory), it is not possible to be sure.
  115967. **
  115968. ** If an error occurs, an error code other than SQLITE_OK is returned.
  115969. */
  115970. static int fts3SelectLeaf(
  115971. Fts3Table *p, /* Virtual table handle */
  115972. const char *zTerm, /* Term to select leaves for */
  115973. int nTerm, /* Size of term zTerm in bytes */
  115974. const char *zNode, /* Buffer containing segment interior node */
  115975. int nNode, /* Size of buffer at zNode */
  115976. sqlite3_int64 *piLeaf, /* Selected leaf node */
  115977. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  115978. ){
  115979. int rc; /* Return code */
  115980. int iHeight; /* Height of this node in tree */
  115981. assert( piLeaf || piLeaf2 );
  115982. sqlite3Fts3GetVarint32(zNode, &iHeight);
  115983. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  115984. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  115985. if( rc==SQLITE_OK && iHeight>1 ){
  115986. char *zBlob = 0; /* Blob read from %_segments table */
  115987. int nBlob; /* Size of zBlob in bytes */
  115988. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  115989. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  115990. if( rc==SQLITE_OK ){
  115991. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  115992. }
  115993. sqlite3_free(zBlob);
  115994. piLeaf = 0;
  115995. zBlob = 0;
  115996. }
  115997. if( rc==SQLITE_OK ){
  115998. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  115999. }
  116000. if( rc==SQLITE_OK ){
  116001. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  116002. }
  116003. sqlite3_free(zBlob);
  116004. }
  116005. return rc;
  116006. }
  116007. /*
  116008. ** This function is used to create delta-encoded serialized lists of FTS3
  116009. ** varints. Each call to this function appends a single varint to a list.
  116010. */
  116011. static void fts3PutDeltaVarint(
  116012. char **pp, /* IN/OUT: Output pointer */
  116013. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  116014. sqlite3_int64 iVal /* Write this value to the list */
  116015. ){
  116016. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  116017. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  116018. *piPrev = iVal;
  116019. }
  116020. /*
  116021. ** When this function is called, *ppPoslist is assumed to point to the
  116022. ** start of a position-list. After it returns, *ppPoslist points to the
  116023. ** first byte after the position-list.
  116024. **
  116025. ** A position list is list of positions (delta encoded) and columns for
  116026. ** a single document record of a doclist. So, in other words, this
  116027. ** routine advances *ppPoslist so that it points to the next docid in
  116028. ** the doclist, or to the first byte past the end of the doclist.
  116029. **
  116030. ** If pp is not NULL, then the contents of the position list are copied
  116031. ** to *pp. *pp is set to point to the first byte past the last byte copied
  116032. ** before this function returns.
  116033. */
  116034. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  116035. char *pEnd = *ppPoslist;
  116036. char c = 0;
  116037. /* The end of a position list is marked by a zero encoded as an FTS3
  116038. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  116039. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  116040. ** of some other, multi-byte, value.
  116041. **
  116042. ** The following while-loop moves pEnd to point to the first byte that is not
  116043. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  116044. ** pEnd once more so that it points to the byte immediately following the
  116045. ** last byte in the position-list.
  116046. */
  116047. while( *pEnd | c ){
  116048. c = *pEnd++ & 0x80;
  116049. testcase( c!=0 && (*pEnd)==0 );
  116050. }
  116051. pEnd++; /* Advance past the POS_END terminator byte */
  116052. if( pp ){
  116053. int n = (int)(pEnd - *ppPoslist);
  116054. char *p = *pp;
  116055. memcpy(p, *ppPoslist, n);
  116056. p += n;
  116057. *pp = p;
  116058. }
  116059. *ppPoslist = pEnd;
  116060. }
  116061. /*
  116062. ** When this function is called, *ppPoslist is assumed to point to the
  116063. ** start of a column-list. After it returns, *ppPoslist points to the
  116064. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  116065. **
  116066. ** A column-list is list of delta-encoded positions for a single column
  116067. ** within a single document within a doclist.
  116068. **
  116069. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  116070. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  116071. ** the POS_COLUMN or POS_END that terminates the column-list.
  116072. **
  116073. ** If pp is not NULL, then the contents of the column-list are copied
  116074. ** to *pp. *pp is set to point to the first byte past the last byte copied
  116075. ** before this function returns. The POS_COLUMN or POS_END terminator
  116076. ** is not copied into *pp.
  116077. */
  116078. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  116079. char *pEnd = *ppPoslist;
  116080. char c = 0;
  116081. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  116082. ** not part of a multi-byte varint.
  116083. */
  116084. while( 0xFE & (*pEnd | c) ){
  116085. c = *pEnd++ & 0x80;
  116086. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  116087. }
  116088. if( pp ){
  116089. int n = (int)(pEnd - *ppPoslist);
  116090. char *p = *pp;
  116091. memcpy(p, *ppPoslist, n);
  116092. p += n;
  116093. *pp = p;
  116094. }
  116095. *ppPoslist = pEnd;
  116096. }
  116097. /*
  116098. ** Value used to signify the end of an position-list. This is safe because
  116099. ** it is not possible to have a document with 2^31 terms.
  116100. */
  116101. #define POSITION_LIST_END 0x7fffffff
  116102. /*
  116103. ** This function is used to help parse position-lists. When this function is
  116104. ** called, *pp may point to the start of the next varint in the position-list
  116105. ** being parsed, or it may point to 1 byte past the end of the position-list
  116106. ** (in which case **pp will be a terminator bytes POS_END (0) or
  116107. ** (1)).
  116108. **
  116109. ** If *pp points past the end of the current position-list, set *pi to
  116110. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  116111. ** increment the current value of *pi by the value read, and set *pp to
  116112. ** point to the next value before returning.
  116113. **
  116114. ** Before calling this routine *pi must be initialized to the value of
  116115. ** the previous position, or zero if we are reading the first position
  116116. ** in the position-list. Because positions are delta-encoded, the value
  116117. ** of the previous position is needed in order to compute the value of
  116118. ** the next position.
  116119. */
  116120. static void fts3ReadNextPos(
  116121. char **pp, /* IN/OUT: Pointer into position-list buffer */
  116122. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  116123. ){
  116124. if( (**pp)&0xFE ){
  116125. fts3GetDeltaVarint(pp, pi);
  116126. *pi -= 2;
  116127. }else{
  116128. *pi = POSITION_LIST_END;
  116129. }
  116130. }
  116131. /*
  116132. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  116133. ** the value of iCol encoded as a varint to *pp. This will start a new
  116134. ** column list.
  116135. **
  116136. ** Set *pp to point to the byte just after the last byte written before
  116137. ** returning (do not modify it if iCol==0). Return the total number of bytes
  116138. ** written (0 if iCol==0).
  116139. */
  116140. static int fts3PutColNumber(char **pp, int iCol){
  116141. int n = 0; /* Number of bytes written */
  116142. if( iCol ){
  116143. char *p = *pp; /* Output pointer */
  116144. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  116145. *p = 0x01;
  116146. *pp = &p[n];
  116147. }
  116148. return n;
  116149. }
  116150. /*
  116151. ** Compute the union of two position lists. The output written
  116152. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  116153. ** order and with any duplicates removed. All pointers are
  116154. ** updated appropriately. The caller is responsible for insuring
  116155. ** that there is enough space in *pp to hold the complete output.
  116156. */
  116157. static void fts3PoslistMerge(
  116158. char **pp, /* Output buffer */
  116159. char **pp1, /* Left input list */
  116160. char **pp2 /* Right input list */
  116161. ){
  116162. char *p = *pp;
  116163. char *p1 = *pp1;
  116164. char *p2 = *pp2;
  116165. while( *p1 || *p2 ){
  116166. int iCol1; /* The current column index in pp1 */
  116167. int iCol2; /* The current column index in pp2 */
  116168. if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
  116169. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  116170. else iCol1 = 0;
  116171. if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
  116172. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  116173. else iCol2 = 0;
  116174. if( iCol1==iCol2 ){
  116175. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  116176. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  116177. sqlite3_int64 iPrev = 0;
  116178. int n = fts3PutColNumber(&p, iCol1);
  116179. p1 += n;
  116180. p2 += n;
  116181. /* At this point, both p1 and p2 point to the start of column-lists
  116182. ** for the same column (the column with index iCol1 and iCol2).
  116183. ** A column-list is a list of non-negative delta-encoded varints, each
  116184. ** incremented by 2 before being stored. Each list is terminated by a
  116185. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  116186. ** and writes the results to buffer p. p is left pointing to the byte
  116187. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  116188. ** written to the output.
  116189. */
  116190. fts3GetDeltaVarint(&p1, &i1);
  116191. fts3GetDeltaVarint(&p2, &i2);
  116192. do {
  116193. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  116194. iPrev -= 2;
  116195. if( i1==i2 ){
  116196. fts3ReadNextPos(&p1, &i1);
  116197. fts3ReadNextPos(&p2, &i2);
  116198. }else if( i1<i2 ){
  116199. fts3ReadNextPos(&p1, &i1);
  116200. }else{
  116201. fts3ReadNextPos(&p2, &i2);
  116202. }
  116203. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  116204. }else if( iCol1<iCol2 ){
  116205. p1 += fts3PutColNumber(&p, iCol1);
  116206. fts3ColumnlistCopy(&p, &p1);
  116207. }else{
  116208. p2 += fts3PutColNumber(&p, iCol2);
  116209. fts3ColumnlistCopy(&p, &p2);
  116210. }
  116211. }
  116212. *p++ = POS_END;
  116213. *pp = p;
  116214. *pp1 = p1 + 1;
  116215. *pp2 = p2 + 1;
  116216. }
  116217. /*
  116218. ** This function is used to merge two position lists into one. When it is
  116219. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  116220. ** the part of a doclist that follows each document id. For example, if a row
  116221. ** contains:
  116222. **
  116223. ** 'a b c'|'x y z'|'a b b a'
  116224. **
  116225. ** Then the position list for this row for token 'b' would consist of:
  116226. **
  116227. ** 0x02 0x01 0x02 0x03 0x03 0x00
  116228. **
  116229. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  116230. ** byte following the 0x00 terminator of their respective position lists.
  116231. **
  116232. ** If isSaveLeft is 0, an entry is added to the output position list for
  116233. ** each position in *pp2 for which there exists one or more positions in
  116234. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  116235. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  116236. ** slots before it.
  116237. **
  116238. ** e.g. nToken==1 searches for adjacent positions.
  116239. */
  116240. static int fts3PoslistPhraseMerge(
  116241. char **pp, /* IN/OUT: Preallocated output buffer */
  116242. int nToken, /* Maximum difference in token positions */
  116243. int isSaveLeft, /* Save the left position */
  116244. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  116245. char **pp1, /* IN/OUT: Left input list */
  116246. char **pp2 /* IN/OUT: Right input list */
  116247. ){
  116248. char *p = *pp;
  116249. char *p1 = *pp1;
  116250. char *p2 = *pp2;
  116251. int iCol1 = 0;
  116252. int iCol2 = 0;
  116253. /* Never set both isSaveLeft and isExact for the same invocation. */
  116254. assert( isSaveLeft==0 || isExact==0 );
  116255. assert( p!=0 && *p1!=0 && *p2!=0 );
  116256. if( *p1==POS_COLUMN ){
  116257. p1++;
  116258. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  116259. }
  116260. if( *p2==POS_COLUMN ){
  116261. p2++;
  116262. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  116263. }
  116264. while( 1 ){
  116265. if( iCol1==iCol2 ){
  116266. char *pSave = p;
  116267. sqlite3_int64 iPrev = 0;
  116268. sqlite3_int64 iPos1 = 0;
  116269. sqlite3_int64 iPos2 = 0;
  116270. if( iCol1 ){
  116271. *p++ = POS_COLUMN;
  116272. p += sqlite3Fts3PutVarint(p, iCol1);
  116273. }
  116274. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  116275. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  116276. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  116277. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  116278. while( 1 ){
  116279. if( iPos2==iPos1+nToken
  116280. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  116281. ){
  116282. sqlite3_int64 iSave;
  116283. iSave = isSaveLeft ? iPos1 : iPos2;
  116284. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  116285. pSave = 0;
  116286. assert( p );
  116287. }
  116288. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  116289. if( (*p2&0xFE)==0 ) break;
  116290. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  116291. }else{
  116292. if( (*p1&0xFE)==0 ) break;
  116293. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  116294. }
  116295. }
  116296. if( pSave ){
  116297. assert( pp && p );
  116298. p = pSave;
  116299. }
  116300. fts3ColumnlistCopy(0, &p1);
  116301. fts3ColumnlistCopy(0, &p2);
  116302. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  116303. if( 0==*p1 || 0==*p2 ) break;
  116304. p1++;
  116305. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  116306. p2++;
  116307. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  116308. }
  116309. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  116310. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  116311. ** end of the position list, or the 0x01 that precedes the next
  116312. ** column-number in the position list.
  116313. */
  116314. else if( iCol1<iCol2 ){
  116315. fts3ColumnlistCopy(0, &p1);
  116316. if( 0==*p1 ) break;
  116317. p1++;
  116318. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  116319. }else{
  116320. fts3ColumnlistCopy(0, &p2);
  116321. if( 0==*p2 ) break;
  116322. p2++;
  116323. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  116324. }
  116325. }
  116326. fts3PoslistCopy(0, &p2);
  116327. fts3PoslistCopy(0, &p1);
  116328. *pp1 = p1;
  116329. *pp2 = p2;
  116330. if( *pp==p ){
  116331. return 0;
  116332. }
  116333. *p++ = 0x00;
  116334. *pp = p;
  116335. return 1;
  116336. }
  116337. /*
  116338. ** Merge two position-lists as required by the NEAR operator. The argument
  116339. ** position lists correspond to the left and right phrases of an expression
  116340. ** like:
  116341. **
  116342. ** "phrase 1" NEAR "phrase number 2"
  116343. **
  116344. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  116345. ** expression and *pp2 to the right. As usual, the indexes in the position
  116346. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  116347. ** in the example above).
  116348. **
  116349. ** The output position list - written to *pp - is a copy of *pp2 with those
  116350. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  116351. */
  116352. static int fts3PoslistNearMerge(
  116353. char **pp, /* Output buffer */
  116354. char *aTmp, /* Temporary buffer space */
  116355. int nRight, /* Maximum difference in token positions */
  116356. int nLeft, /* Maximum difference in token positions */
  116357. char **pp1, /* IN/OUT: Left input list */
  116358. char **pp2 /* IN/OUT: Right input list */
  116359. ){
  116360. char *p1 = *pp1;
  116361. char *p2 = *pp2;
  116362. char *pTmp1 = aTmp;
  116363. char *pTmp2;
  116364. char *aTmp2;
  116365. int res = 1;
  116366. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  116367. aTmp2 = pTmp2 = pTmp1;
  116368. *pp1 = p1;
  116369. *pp2 = p2;
  116370. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  116371. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  116372. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  116373. }else if( pTmp1!=aTmp ){
  116374. fts3PoslistCopy(pp, &aTmp);
  116375. }else if( pTmp2!=aTmp2 ){
  116376. fts3PoslistCopy(pp, &aTmp2);
  116377. }else{
  116378. res = 0;
  116379. }
  116380. return res;
  116381. }
  116382. /*
  116383. ** An instance of this function is used to merge together the (potentially
  116384. ** large number of) doclists for each term that matches a prefix query.
  116385. ** See function fts3TermSelectMerge() for details.
  116386. */
  116387. typedef struct TermSelect TermSelect;
  116388. struct TermSelect {
  116389. char *aaOutput[16]; /* Malloc'd output buffers */
  116390. int anOutput[16]; /* Size each output buffer in bytes */
  116391. };
  116392. /*
  116393. ** This function is used to read a single varint from a buffer. Parameter
  116394. ** pEnd points 1 byte past the end of the buffer. When this function is
  116395. ** called, if *pp points to pEnd or greater, then the end of the buffer
  116396. ** has been reached. In this case *pp is set to 0 and the function returns.
  116397. **
  116398. ** If *pp does not point to or past pEnd, then a single varint is read
  116399. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  116400. **
  116401. ** If bDescIdx is false, the value read is added to *pVal before returning.
  116402. ** If it is true, the value read is subtracted from *pVal before this
  116403. ** function returns.
  116404. */
  116405. static void fts3GetDeltaVarint3(
  116406. char **pp, /* IN/OUT: Point to read varint from */
  116407. char *pEnd, /* End of buffer */
  116408. int bDescIdx, /* True if docids are descending */
  116409. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  116410. ){
  116411. if( *pp>=pEnd ){
  116412. *pp = 0;
  116413. }else{
  116414. sqlite3_int64 iVal;
  116415. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  116416. if( bDescIdx ){
  116417. *pVal -= iVal;
  116418. }else{
  116419. *pVal += iVal;
  116420. }
  116421. }
  116422. }
  116423. /*
  116424. ** This function is used to write a single varint to a buffer. The varint
  116425. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  116426. ** end of the value written.
  116427. **
  116428. ** If *pbFirst is zero when this function is called, the value written to
  116429. ** the buffer is that of parameter iVal.
  116430. **
  116431. ** If *pbFirst is non-zero when this function is called, then the value
  116432. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  116433. ** (if bDescIdx is non-zero).
  116434. **
  116435. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  116436. ** to the value of parameter iVal.
  116437. */
  116438. static void fts3PutDeltaVarint3(
  116439. char **pp, /* IN/OUT: Output pointer */
  116440. int bDescIdx, /* True for descending docids */
  116441. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  116442. int *pbFirst, /* IN/OUT: True after first int written */
  116443. sqlite3_int64 iVal /* Write this value to the list */
  116444. ){
  116445. sqlite3_int64 iWrite;
  116446. if( bDescIdx==0 || *pbFirst==0 ){
  116447. iWrite = iVal - *piPrev;
  116448. }else{
  116449. iWrite = *piPrev - iVal;
  116450. }
  116451. assert( *pbFirst || *piPrev==0 );
  116452. assert( *pbFirst==0 || iWrite>0 );
  116453. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  116454. *piPrev = iVal;
  116455. *pbFirst = 1;
  116456. }
  116457. /*
  116458. ** This macro is used by various functions that merge doclists. The two
  116459. ** arguments are 64-bit docid values. If the value of the stack variable
  116460. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  116461. ** Otherwise, (i2-i1).
  116462. **
  116463. ** Using this makes it easier to write code that can merge doclists that are
  116464. ** sorted in either ascending or descending order.
  116465. */
  116466. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  116467. /*
  116468. ** This function does an "OR" merge of two doclists (output contains all
  116469. ** positions contained in either argument doclist). If the docids in the
  116470. ** input doclists are sorted in ascending order, parameter bDescDoclist
  116471. ** should be false. If they are sorted in ascending order, it should be
  116472. ** passed a non-zero value.
  116473. **
  116474. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  116475. ** containing the output doclist and SQLITE_OK is returned. In this case
  116476. ** *pnOut is set to the number of bytes in the output doclist.
  116477. **
  116478. ** If an error occurs, an SQLite error code is returned. The output values
  116479. ** are undefined in this case.
  116480. */
  116481. static int fts3DoclistOrMerge(
  116482. int bDescDoclist, /* True if arguments are desc */
  116483. char *a1, int n1, /* First doclist */
  116484. char *a2, int n2, /* Second doclist */
  116485. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  116486. ){
  116487. sqlite3_int64 i1 = 0;
  116488. sqlite3_int64 i2 = 0;
  116489. sqlite3_int64 iPrev = 0;
  116490. char *pEnd1 = &a1[n1];
  116491. char *pEnd2 = &a2[n2];
  116492. char *p1 = a1;
  116493. char *p2 = a2;
  116494. char *p;
  116495. char *aOut;
  116496. int bFirstOut = 0;
  116497. *paOut = 0;
  116498. *pnOut = 0;
  116499. /* Allocate space for the output. Both the input and output doclists
  116500. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  116501. ** then the first docid in each list is simply encoded as a varint. For
  116502. ** each subsequent docid, the varint stored is the difference between the
  116503. ** current and previous docid (a positive number - since the list is in
  116504. ** ascending order).
  116505. **
  116506. ** The first docid written to the output is therefore encoded using the
  116507. ** same number of bytes as it is in whichever of the input lists it is
  116508. ** read from. And each subsequent docid read from the same input list
  116509. ** consumes either the same or less bytes as it did in the input (since
  116510. ** the difference between it and the previous value in the output must
  116511. ** be a positive value less than or equal to the delta value read from
  116512. ** the input list). The same argument applies to all but the first docid
  116513. ** read from the 'other' list. And to the contents of all position lists
  116514. ** that will be copied and merged from the input to the output.
  116515. **
  116516. ** However, if the first docid copied to the output is a negative number,
  116517. ** then the encoding of the first docid from the 'other' input list may
  116518. ** be larger in the output than it was in the input (since the delta value
  116519. ** may be a larger positive integer than the actual docid).
  116520. **
  116521. ** The space required to store the output is therefore the sum of the
  116522. ** sizes of the two inputs, plus enough space for exactly one of the input
  116523. ** docids to grow.
  116524. **
  116525. ** A symetric argument may be made if the doclists are in descending
  116526. ** order.
  116527. */
  116528. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  116529. if( !aOut ) return SQLITE_NOMEM;
  116530. p = aOut;
  116531. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  116532. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  116533. while( p1 || p2 ){
  116534. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  116535. if( p2 && p1 && iDiff==0 ){
  116536. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  116537. fts3PoslistMerge(&p, &p1, &p2);
  116538. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  116539. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  116540. }else if( !p2 || (p1 && iDiff<0) ){
  116541. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  116542. fts3PoslistCopy(&p, &p1);
  116543. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  116544. }else{
  116545. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  116546. fts3PoslistCopy(&p, &p2);
  116547. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  116548. }
  116549. }
  116550. *paOut = aOut;
  116551. *pnOut = (int)(p-aOut);
  116552. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  116553. return SQLITE_OK;
  116554. }
  116555. /*
  116556. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  116557. ** the output contains a copy of each position from the right-hand input
  116558. ** doclist for which there is a position in the left-hand input doclist
  116559. ** exactly nDist tokens before it.
  116560. **
  116561. ** If the docids in the input doclists are sorted in ascending order,
  116562. ** parameter bDescDoclist should be false. If they are sorted in ascending
  116563. ** order, it should be passed a non-zero value.
  116564. **
  116565. ** The right-hand input doclist is overwritten by this function.
  116566. */
  116567. static void fts3DoclistPhraseMerge(
  116568. int bDescDoclist, /* True if arguments are desc */
  116569. int nDist, /* Distance from left to right (1=adjacent) */
  116570. char *aLeft, int nLeft, /* Left doclist */
  116571. char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
  116572. ){
  116573. sqlite3_int64 i1 = 0;
  116574. sqlite3_int64 i2 = 0;
  116575. sqlite3_int64 iPrev = 0;
  116576. char *pEnd1 = &aLeft[nLeft];
  116577. char *pEnd2 = &aRight[*pnRight];
  116578. char *p1 = aLeft;
  116579. char *p2 = aRight;
  116580. char *p;
  116581. int bFirstOut = 0;
  116582. char *aOut = aRight;
  116583. assert( nDist>0 );
  116584. p = aOut;
  116585. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  116586. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  116587. while( p1 && p2 ){
  116588. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  116589. if( iDiff==0 ){
  116590. char *pSave = p;
  116591. sqlite3_int64 iPrevSave = iPrev;
  116592. int bFirstOutSave = bFirstOut;
  116593. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  116594. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  116595. p = pSave;
  116596. iPrev = iPrevSave;
  116597. bFirstOut = bFirstOutSave;
  116598. }
  116599. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  116600. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  116601. }else if( iDiff<0 ){
  116602. fts3PoslistCopy(0, &p1);
  116603. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  116604. }else{
  116605. fts3PoslistCopy(0, &p2);
  116606. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  116607. }
  116608. }
  116609. *pnRight = (int)(p - aOut);
  116610. }
  116611. /*
  116612. ** Argument pList points to a position list nList bytes in size. This
  116613. ** function checks to see if the position list contains any entries for
  116614. ** a token in position 0 (of any column). If so, it writes argument iDelta
  116615. ** to the output buffer pOut, followed by a position list consisting only
  116616. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  116617. ** The value returned is the number of bytes written to pOut (if any).
  116618. */
  116619. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  116620. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  116621. char *pList, /* Position list (no 0x00 term) */
  116622. int nList, /* Size of pList in bytes */
  116623. char *pOut /* Write output here */
  116624. ){
  116625. int nOut = 0;
  116626. int bWritten = 0; /* True once iDelta has been written */
  116627. char *p = pList;
  116628. char *pEnd = &pList[nList];
  116629. if( *p!=0x01 ){
  116630. if( *p==0x02 ){
  116631. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  116632. pOut[nOut++] = 0x02;
  116633. bWritten = 1;
  116634. }
  116635. fts3ColumnlistCopy(0, &p);
  116636. }
  116637. while( p<pEnd && *p==0x01 ){
  116638. sqlite3_int64 iCol;
  116639. p++;
  116640. p += sqlite3Fts3GetVarint(p, &iCol);
  116641. if( *p==0x02 ){
  116642. if( bWritten==0 ){
  116643. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  116644. bWritten = 1;
  116645. }
  116646. pOut[nOut++] = 0x01;
  116647. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  116648. pOut[nOut++] = 0x02;
  116649. }
  116650. fts3ColumnlistCopy(0, &p);
  116651. }
  116652. if( bWritten ){
  116653. pOut[nOut++] = 0x00;
  116654. }
  116655. return nOut;
  116656. }
  116657. /*
  116658. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  116659. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  116660. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  116661. **
  116662. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  116663. ** the responsibility of the caller to free any doclists left in the
  116664. ** TermSelect.aaOutput[] array.
  116665. */
  116666. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  116667. char *aOut = 0;
  116668. int nOut = 0;
  116669. int i;
  116670. /* Loop through the doclists in the aaOutput[] array. Merge them all
  116671. ** into a single doclist.
  116672. */
  116673. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  116674. if( pTS->aaOutput[i] ){
  116675. if( !aOut ){
  116676. aOut = pTS->aaOutput[i];
  116677. nOut = pTS->anOutput[i];
  116678. pTS->aaOutput[i] = 0;
  116679. }else{
  116680. int nNew;
  116681. char *aNew;
  116682. int rc = fts3DoclistOrMerge(p->bDescIdx,
  116683. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  116684. );
  116685. if( rc!=SQLITE_OK ){
  116686. sqlite3_free(aOut);
  116687. return rc;
  116688. }
  116689. sqlite3_free(pTS->aaOutput[i]);
  116690. sqlite3_free(aOut);
  116691. pTS->aaOutput[i] = 0;
  116692. aOut = aNew;
  116693. nOut = nNew;
  116694. }
  116695. }
  116696. }
  116697. pTS->aaOutput[0] = aOut;
  116698. pTS->anOutput[0] = nOut;
  116699. return SQLITE_OK;
  116700. }
  116701. /*
  116702. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  116703. ** as the first argument. The merge is an "OR" merge (see function
  116704. ** fts3DoclistOrMerge() for details).
  116705. **
  116706. ** This function is called with the doclist for each term that matches
  116707. ** a queried prefix. It merges all these doclists into one, the doclist
  116708. ** for the specified prefix. Since there can be a very large number of
  116709. ** doclists to merge, the merging is done pair-wise using the TermSelect
  116710. ** object.
  116711. **
  116712. ** This function returns SQLITE_OK if the merge is successful, or an
  116713. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  116714. */
  116715. static int fts3TermSelectMerge(
  116716. Fts3Table *p, /* FTS table handle */
  116717. TermSelect *pTS, /* TermSelect object to merge into */
  116718. char *aDoclist, /* Pointer to doclist */
  116719. int nDoclist /* Size of aDoclist in bytes */
  116720. ){
  116721. if( pTS->aaOutput[0]==0 ){
  116722. /* If this is the first term selected, copy the doclist to the output
  116723. ** buffer using memcpy(). */
  116724. pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
  116725. pTS->anOutput[0] = nDoclist;
  116726. if( pTS->aaOutput[0] ){
  116727. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  116728. }else{
  116729. return SQLITE_NOMEM;
  116730. }
  116731. }else{
  116732. char *aMerge = aDoclist;
  116733. int nMerge = nDoclist;
  116734. int iOut;
  116735. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  116736. if( pTS->aaOutput[iOut]==0 ){
  116737. assert( iOut>0 );
  116738. pTS->aaOutput[iOut] = aMerge;
  116739. pTS->anOutput[iOut] = nMerge;
  116740. break;
  116741. }else{
  116742. char *aNew;
  116743. int nNew;
  116744. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  116745. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  116746. );
  116747. if( rc!=SQLITE_OK ){
  116748. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  116749. return rc;
  116750. }
  116751. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  116752. sqlite3_free(pTS->aaOutput[iOut]);
  116753. pTS->aaOutput[iOut] = 0;
  116754. aMerge = aNew;
  116755. nMerge = nNew;
  116756. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  116757. pTS->aaOutput[iOut] = aMerge;
  116758. pTS->anOutput[iOut] = nMerge;
  116759. }
  116760. }
  116761. }
  116762. }
  116763. return SQLITE_OK;
  116764. }
  116765. /*
  116766. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  116767. */
  116768. static int fts3SegReaderCursorAppend(
  116769. Fts3MultiSegReader *pCsr,
  116770. Fts3SegReader *pNew
  116771. ){
  116772. if( (pCsr->nSegment%16)==0 ){
  116773. Fts3SegReader **apNew;
  116774. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  116775. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  116776. if( !apNew ){
  116777. sqlite3Fts3SegReaderFree(pNew);
  116778. return SQLITE_NOMEM;
  116779. }
  116780. pCsr->apSegment = apNew;
  116781. }
  116782. pCsr->apSegment[pCsr->nSegment++] = pNew;
  116783. return SQLITE_OK;
  116784. }
  116785. /*
  116786. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  116787. ** 8th argument.
  116788. **
  116789. ** This function returns SQLITE_OK if successful, or an SQLite error code
  116790. ** otherwise.
  116791. */
  116792. static int fts3SegReaderCursor(
  116793. Fts3Table *p, /* FTS3 table handle */
  116794. int iLangid, /* Language id */
  116795. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  116796. int iLevel, /* Level of segments to scan */
  116797. const char *zTerm, /* Term to query for */
  116798. int nTerm, /* Size of zTerm in bytes */
  116799. int isPrefix, /* True for a prefix search */
  116800. int isScan, /* True to scan from zTerm to EOF */
  116801. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  116802. ){
  116803. int rc = SQLITE_OK; /* Error code */
  116804. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  116805. int rc2; /* Result of sqlite3_reset() */
  116806. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  116807. ** for the pending-terms. If this is a scan, then this call must be being
  116808. ** made by an fts4aux module, not an FTS table. In this case calling
  116809. ** Fts3SegReaderPending might segfault, as the data structures used by
  116810. ** fts4aux are not completely populated. So it's easiest to filter these
  116811. ** calls out here. */
  116812. if( iLevel<0 && p->aIndex ){
  116813. Fts3SegReader *pSeg = 0;
  116814. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
  116815. if( rc==SQLITE_OK && pSeg ){
  116816. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  116817. }
  116818. }
  116819. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  116820. if( rc==SQLITE_OK ){
  116821. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  116822. }
  116823. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  116824. Fts3SegReader *pSeg = 0;
  116825. /* Read the values returned by the SELECT into local variables. */
  116826. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  116827. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  116828. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  116829. int nRoot = sqlite3_column_bytes(pStmt, 4);
  116830. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  116831. /* If zTerm is not NULL, and this segment is not stored entirely on its
  116832. ** root node, the range of leaves scanned can be reduced. Do this. */
  116833. if( iStartBlock && zTerm ){
  116834. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  116835. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  116836. if( rc!=SQLITE_OK ) goto finished;
  116837. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  116838. }
  116839. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  116840. (isPrefix==0 && isScan==0),
  116841. iStartBlock, iLeavesEndBlock,
  116842. iEndBlock, zRoot, nRoot, &pSeg
  116843. );
  116844. if( rc!=SQLITE_OK ) goto finished;
  116845. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  116846. }
  116847. }
  116848. finished:
  116849. rc2 = sqlite3_reset(pStmt);
  116850. if( rc==SQLITE_DONE ) rc = rc2;
  116851. return rc;
  116852. }
  116853. /*
  116854. ** Set up a cursor object for iterating through a full-text index or a
  116855. ** single level therein.
  116856. */
  116857. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  116858. Fts3Table *p, /* FTS3 table handle */
  116859. int iLangid, /* Language-id to search */
  116860. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  116861. int iLevel, /* Level of segments to scan */
  116862. const char *zTerm, /* Term to query for */
  116863. int nTerm, /* Size of zTerm in bytes */
  116864. int isPrefix, /* True for a prefix search */
  116865. int isScan, /* True to scan from zTerm to EOF */
  116866. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  116867. ){
  116868. assert( iIndex>=0 && iIndex<p->nIndex );
  116869. assert( iLevel==FTS3_SEGCURSOR_ALL
  116870. || iLevel==FTS3_SEGCURSOR_PENDING
  116871. || iLevel>=0
  116872. );
  116873. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  116874. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  116875. assert( isPrefix==0 || isScan==0 );
  116876. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  116877. return fts3SegReaderCursor(
  116878. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  116879. );
  116880. }
  116881. /*
  116882. ** In addition to its current configuration, have the Fts3MultiSegReader
  116883. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  116884. **
  116885. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  116886. */
  116887. static int fts3SegReaderCursorAddZero(
  116888. Fts3Table *p, /* FTS virtual table handle */
  116889. int iLangid,
  116890. const char *zTerm, /* Term to scan doclist of */
  116891. int nTerm, /* Number of bytes in zTerm */
  116892. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  116893. ){
  116894. return fts3SegReaderCursor(p,
  116895. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  116896. );
  116897. }
  116898. /*
  116899. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  116900. ** if isPrefix is true, to scan the doclist for all terms for which
  116901. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  116902. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  116903. ** an SQLite error code.
  116904. **
  116905. ** It is the responsibility of the caller to free this object by eventually
  116906. ** passing it to fts3SegReaderCursorFree()
  116907. **
  116908. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  116909. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  116910. */
  116911. static int fts3TermSegReaderCursor(
  116912. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  116913. const char *zTerm, /* Term to query for */
  116914. int nTerm, /* Size of zTerm in bytes */
  116915. int isPrefix, /* True for a prefix search */
  116916. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  116917. ){
  116918. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  116919. int rc = SQLITE_NOMEM; /* Return code */
  116920. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  116921. if( pSegcsr ){
  116922. int i;
  116923. int bFound = 0; /* True once an index has been found */
  116924. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  116925. if( isPrefix ){
  116926. for(i=1; bFound==0 && i<p->nIndex; i++){
  116927. if( p->aIndex[i].nPrefix==nTerm ){
  116928. bFound = 1;
  116929. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  116930. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  116931. );
  116932. pSegcsr->bLookup = 1;
  116933. }
  116934. }
  116935. for(i=1; bFound==0 && i<p->nIndex; i++){
  116936. if( p->aIndex[i].nPrefix==nTerm+1 ){
  116937. bFound = 1;
  116938. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  116939. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  116940. );
  116941. if( rc==SQLITE_OK ){
  116942. rc = fts3SegReaderCursorAddZero(
  116943. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  116944. );
  116945. }
  116946. }
  116947. }
  116948. }
  116949. if( bFound==0 ){
  116950. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  116951. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  116952. );
  116953. pSegcsr->bLookup = !isPrefix;
  116954. }
  116955. }
  116956. *ppSegcsr = pSegcsr;
  116957. return rc;
  116958. }
  116959. /*
  116960. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  116961. */
  116962. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  116963. sqlite3Fts3SegReaderFinish(pSegcsr);
  116964. sqlite3_free(pSegcsr);
  116965. }
  116966. /*
  116967. ** This function retrieves the doclist for the specified term (or term
  116968. ** prefix) from the database.
  116969. */
  116970. static int fts3TermSelect(
  116971. Fts3Table *p, /* Virtual table handle */
  116972. Fts3PhraseToken *pTok, /* Token to query for */
  116973. int iColumn, /* Column to query (or -ve for all columns) */
  116974. int *pnOut, /* OUT: Size of buffer at *ppOut */
  116975. char **ppOut /* OUT: Malloced result buffer */
  116976. ){
  116977. int rc; /* Return code */
  116978. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  116979. TermSelect tsc; /* Object for pair-wise doclist merging */
  116980. Fts3SegFilter filter; /* Segment term filter configuration */
  116981. pSegcsr = pTok->pSegcsr;
  116982. memset(&tsc, 0, sizeof(TermSelect));
  116983. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  116984. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  116985. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  116986. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  116987. filter.iCol = iColumn;
  116988. filter.zTerm = pTok->z;
  116989. filter.nTerm = pTok->n;
  116990. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  116991. while( SQLITE_OK==rc
  116992. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  116993. ){
  116994. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  116995. }
  116996. if( rc==SQLITE_OK ){
  116997. rc = fts3TermSelectFinishMerge(p, &tsc);
  116998. }
  116999. if( rc==SQLITE_OK ){
  117000. *ppOut = tsc.aaOutput[0];
  117001. *pnOut = tsc.anOutput[0];
  117002. }else{
  117003. int i;
  117004. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  117005. sqlite3_free(tsc.aaOutput[i]);
  117006. }
  117007. }
  117008. fts3SegReaderCursorFree(pSegcsr);
  117009. pTok->pSegcsr = 0;
  117010. return rc;
  117011. }
  117012. /*
  117013. ** This function counts the total number of docids in the doclist stored
  117014. ** in buffer aList[], size nList bytes.
  117015. **
  117016. ** If the isPoslist argument is true, then it is assumed that the doclist
  117017. ** contains a position-list following each docid. Otherwise, it is assumed
  117018. ** that the doclist is simply a list of docids stored as delta encoded
  117019. ** varints.
  117020. */
  117021. static int fts3DoclistCountDocids(char *aList, int nList){
  117022. int nDoc = 0; /* Return value */
  117023. if( aList ){
  117024. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  117025. char *p = aList; /* Cursor */
  117026. while( p<aEnd ){
  117027. nDoc++;
  117028. while( (*p++)&0x80 ); /* Skip docid varint */
  117029. fts3PoslistCopy(0, &p); /* Skip over position list */
  117030. }
  117031. }
  117032. return nDoc;
  117033. }
  117034. /*
  117035. ** Advance the cursor to the next row in the %_content table that
  117036. ** matches the search criteria. For a MATCH search, this will be
  117037. ** the next row that matches. For a full-table scan, this will be
  117038. ** simply the next row in the %_content table. For a docid lookup,
  117039. ** this routine simply sets the EOF flag.
  117040. **
  117041. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  117042. ** even if we reach end-of-file. The fts3EofMethod() will be called
  117043. ** subsequently to determine whether or not an EOF was hit.
  117044. */
  117045. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  117046. int rc;
  117047. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  117048. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  117049. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  117050. pCsr->isEof = 1;
  117051. rc = sqlite3_reset(pCsr->pStmt);
  117052. }else{
  117053. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  117054. rc = SQLITE_OK;
  117055. }
  117056. }else{
  117057. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  117058. }
  117059. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  117060. return rc;
  117061. }
  117062. /*
  117063. ** The following are copied from sqliteInt.h.
  117064. **
  117065. ** Constants for the largest and smallest possible 64-bit signed integers.
  117066. ** These macros are designed to work correctly on both 32-bit and 64-bit
  117067. ** compilers.
  117068. */
  117069. #ifndef SQLITE_AMALGAMATION
  117070. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  117071. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  117072. #endif
  117073. /*
  117074. ** If the numeric type of argument pVal is "integer", then return it
  117075. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  117076. ** the second parameter, iDefault.
  117077. */
  117078. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  117079. if( pVal ){
  117080. int eType = sqlite3_value_numeric_type(pVal);
  117081. if( eType==SQLITE_INTEGER ){
  117082. return sqlite3_value_int64(pVal);
  117083. }
  117084. }
  117085. return iDefault;
  117086. }
  117087. /*
  117088. ** This is the xFilter interface for the virtual table. See
  117089. ** the virtual table xFilter method documentation for additional
  117090. ** information.
  117091. **
  117092. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  117093. ** the %_content table.
  117094. **
  117095. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  117096. ** in the %_content table.
  117097. **
  117098. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  117099. ** column on the left-hand side of the MATCH operator is column
  117100. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  117101. ** side of the MATCH operator.
  117102. */
  117103. static int fts3FilterMethod(
  117104. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  117105. int idxNum, /* Strategy index */
  117106. const char *idxStr, /* Unused */
  117107. int nVal, /* Number of elements in apVal */
  117108. sqlite3_value **apVal /* Arguments for the indexing scheme */
  117109. ){
  117110. int rc;
  117111. char *zSql; /* SQL statement used to access %_content */
  117112. int eSearch;
  117113. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  117114. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  117115. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  117116. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  117117. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  117118. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  117119. int iIdx;
  117120. UNUSED_PARAMETER(idxStr);
  117121. UNUSED_PARAMETER(nVal);
  117122. eSearch = (idxNum & 0x0000FFFF);
  117123. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  117124. assert( p->pSegments==0 );
  117125. /* Collect arguments into local variables */
  117126. iIdx = 0;
  117127. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  117128. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  117129. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  117130. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  117131. assert( iIdx==nVal );
  117132. /* In case the cursor has been used before, clear it now. */
  117133. sqlite3_finalize(pCsr->pStmt);
  117134. sqlite3_free(pCsr->aDoclist);
  117135. sqlite3Fts3ExprFree(pCsr->pExpr);
  117136. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  117137. /* Set the lower and upper bounds on docids to return */
  117138. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  117139. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  117140. if( idxStr ){
  117141. pCsr->bDesc = (idxStr[0]=='D');
  117142. }else{
  117143. pCsr->bDesc = p->bDescIdx;
  117144. }
  117145. pCsr->eSearch = (i16)eSearch;
  117146. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  117147. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  117148. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  117149. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  117150. return SQLITE_NOMEM;
  117151. }
  117152. pCsr->iLangid = 0;
  117153. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  117154. assert( p->base.zErrMsg==0 );
  117155. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  117156. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  117157. &p->base.zErrMsg
  117158. );
  117159. if( rc!=SQLITE_OK ){
  117160. return rc;
  117161. }
  117162. rc = fts3EvalStart(pCsr);
  117163. sqlite3Fts3SegmentsClose(p);
  117164. if( rc!=SQLITE_OK ) return rc;
  117165. pCsr->pNextId = pCsr->aDoclist;
  117166. pCsr->iPrevId = 0;
  117167. }
  117168. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  117169. ** statement loops through all rows of the %_content table. For a
  117170. ** full-text query or docid lookup, the statement retrieves a single
  117171. ** row by docid.
  117172. */
  117173. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  117174. zSql = sqlite3_mprintf(
  117175. "SELECT %s ORDER BY rowid %s",
  117176. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  117177. );
  117178. if( zSql ){
  117179. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  117180. sqlite3_free(zSql);
  117181. }else{
  117182. rc = SQLITE_NOMEM;
  117183. }
  117184. }else if( eSearch==FTS3_DOCID_SEARCH ){
  117185. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  117186. if( rc==SQLITE_OK ){
  117187. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  117188. }
  117189. }
  117190. if( rc!=SQLITE_OK ) return rc;
  117191. return fts3NextMethod(pCursor);
  117192. }
  117193. /*
  117194. ** This is the xEof method of the virtual table. SQLite calls this
  117195. ** routine to find out if it has reached the end of a result set.
  117196. */
  117197. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  117198. return ((Fts3Cursor *)pCursor)->isEof;
  117199. }
  117200. /*
  117201. ** This is the xRowid method. The SQLite core calls this routine to
  117202. ** retrieve the rowid for the current row of the result set. fts3
  117203. ** exposes %_content.docid as the rowid for the virtual table. The
  117204. ** rowid should be written to *pRowid.
  117205. */
  117206. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  117207. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  117208. *pRowid = pCsr->iPrevId;
  117209. return SQLITE_OK;
  117210. }
  117211. /*
  117212. ** This is the xColumn method, called by SQLite to request a value from
  117213. ** the row that the supplied cursor currently points to.
  117214. **
  117215. ** If:
  117216. **
  117217. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  117218. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  117219. ** (iCol == p->nColumn+1) -> Docid column
  117220. ** (iCol == p->nColumn+2) -> Langid column
  117221. */
  117222. static int fts3ColumnMethod(
  117223. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  117224. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  117225. int iCol /* Index of column to read value from */
  117226. ){
  117227. int rc = SQLITE_OK; /* Return Code */
  117228. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  117229. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  117230. /* The column value supplied by SQLite must be in range. */
  117231. assert( iCol>=0 && iCol<=p->nColumn+2 );
  117232. if( iCol==p->nColumn+1 ){
  117233. /* This call is a request for the "docid" column. Since "docid" is an
  117234. ** alias for "rowid", use the xRowid() method to obtain the value.
  117235. */
  117236. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  117237. }else if( iCol==p->nColumn ){
  117238. /* The extra column whose name is the same as the table.
  117239. ** Return a blob which is a pointer to the cursor. */
  117240. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  117241. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  117242. sqlite3_result_int64(pCtx, pCsr->iLangid);
  117243. }else{
  117244. /* The requested column is either a user column (one that contains
  117245. ** indexed data), or the language-id column. */
  117246. rc = fts3CursorSeek(0, pCsr);
  117247. if( rc==SQLITE_OK ){
  117248. if( iCol==p->nColumn+2 ){
  117249. int iLangid = 0;
  117250. if( p->zLanguageid ){
  117251. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  117252. }
  117253. sqlite3_result_int(pCtx, iLangid);
  117254. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  117255. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  117256. }
  117257. }
  117258. }
  117259. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  117260. return rc;
  117261. }
  117262. /*
  117263. ** This function is the implementation of the xUpdate callback used by
  117264. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  117265. ** inserted, updated or deleted.
  117266. */
  117267. static int fts3UpdateMethod(
  117268. sqlite3_vtab *pVtab, /* Virtual table handle */
  117269. int nArg, /* Size of argument array */
  117270. sqlite3_value **apVal, /* Array of arguments */
  117271. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  117272. ){
  117273. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  117274. }
  117275. /*
  117276. ** Implementation of xSync() method. Flush the contents of the pending-terms
  117277. ** hash-table to the database.
  117278. */
  117279. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  117280. /* Following an incremental-merge operation, assuming that the input
  117281. ** segments are not completely consumed (the usual case), they are updated
  117282. ** in place to remove the entries that have already been merged. This
  117283. ** involves updating the leaf block that contains the smallest unmerged
  117284. ** entry and each block (if any) between the leaf and the root node. So
  117285. ** if the height of the input segment b-trees is N, and input segments
  117286. ** are merged eight at a time, updating the input segments at the end
  117287. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  117288. ** small - often between 0 and 2. So the overhead of the incremental
  117289. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  117290. ** dwarfing the actual productive work accomplished, the incremental merge
  117291. ** is only attempted if it will write at least 64 leaf blocks. Hence
  117292. ** nMinMerge.
  117293. **
  117294. ** Of course, updating the input segments also involves deleting a bunch
  117295. ** of blocks from the segments table. But this is not considered overhead
  117296. ** as it would also be required by a crisis-merge that used the same input
  117297. ** segments.
  117298. */
  117299. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  117300. Fts3Table *p = (Fts3Table*)pVtab;
  117301. int rc = sqlite3Fts3PendingTermsFlush(p);
  117302. if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
  117303. int mxLevel = 0; /* Maximum relative level value in db */
  117304. int A; /* Incr-merge parameter A */
  117305. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  117306. assert( rc==SQLITE_OK || mxLevel==0 );
  117307. A = p->nLeafAdd * mxLevel;
  117308. A += (A/2);
  117309. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
  117310. }
  117311. sqlite3Fts3SegmentsClose(p);
  117312. return rc;
  117313. }
  117314. /*
  117315. ** Implementation of xBegin() method. This is a no-op.
  117316. */
  117317. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  117318. Fts3Table *p = (Fts3Table*)pVtab;
  117319. UNUSED_PARAMETER(pVtab);
  117320. assert( p->pSegments==0 );
  117321. assert( p->nPendingData==0 );
  117322. assert( p->inTransaction!=1 );
  117323. TESTONLY( p->inTransaction = 1 );
  117324. TESTONLY( p->mxSavepoint = -1; );
  117325. p->nLeafAdd = 0;
  117326. return SQLITE_OK;
  117327. }
  117328. /*
  117329. ** Implementation of xCommit() method. This is a no-op. The contents of
  117330. ** the pending-terms hash-table have already been flushed into the database
  117331. ** by fts3SyncMethod().
  117332. */
  117333. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  117334. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  117335. UNUSED_PARAMETER(pVtab);
  117336. assert( p->nPendingData==0 );
  117337. assert( p->inTransaction!=0 );
  117338. assert( p->pSegments==0 );
  117339. TESTONLY( p->inTransaction = 0 );
  117340. TESTONLY( p->mxSavepoint = -1; );
  117341. return SQLITE_OK;
  117342. }
  117343. /*
  117344. ** Implementation of xRollback(). Discard the contents of the pending-terms
  117345. ** hash-table. Any changes made to the database are reverted by SQLite.
  117346. */
  117347. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  117348. Fts3Table *p = (Fts3Table*)pVtab;
  117349. sqlite3Fts3PendingTermsClear(p);
  117350. assert( p->inTransaction!=0 );
  117351. TESTONLY( p->inTransaction = 0 );
  117352. TESTONLY( p->mxSavepoint = -1; );
  117353. return SQLITE_OK;
  117354. }
  117355. /*
  117356. ** When called, *ppPoslist must point to the byte immediately following the
  117357. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  117358. ** moves *ppPoslist so that it instead points to the first byte of the
  117359. ** same position list.
  117360. */
  117361. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  117362. char *p = &(*ppPoslist)[-2];
  117363. char c = 0;
  117364. while( p>pStart && (c=*p--)==0 );
  117365. while( p>pStart && (*p & 0x80) | c ){
  117366. c = *p--;
  117367. }
  117368. if( p>pStart ){ p = &p[2]; }
  117369. while( *p++&0x80 );
  117370. *ppPoslist = p;
  117371. }
  117372. /*
  117373. ** Helper function used by the implementation of the overloaded snippet(),
  117374. ** offsets() and optimize() SQL functions.
  117375. **
  117376. ** If the value passed as the third argument is a blob of size
  117377. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  117378. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  117379. ** message is written to context pContext and SQLITE_ERROR returned. The
  117380. ** string passed via zFunc is used as part of the error message.
  117381. */
  117382. static int fts3FunctionArg(
  117383. sqlite3_context *pContext, /* SQL function call context */
  117384. const char *zFunc, /* Function name */
  117385. sqlite3_value *pVal, /* argv[0] passed to function */
  117386. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  117387. ){
  117388. Fts3Cursor *pRet;
  117389. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  117390. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  117391. ){
  117392. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  117393. sqlite3_result_error(pContext, zErr, -1);
  117394. sqlite3_free(zErr);
  117395. return SQLITE_ERROR;
  117396. }
  117397. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  117398. *ppCsr = pRet;
  117399. return SQLITE_OK;
  117400. }
  117401. /*
  117402. ** Implementation of the snippet() function for FTS3
  117403. */
  117404. static void fts3SnippetFunc(
  117405. sqlite3_context *pContext, /* SQLite function call context */
  117406. int nVal, /* Size of apVal[] array */
  117407. sqlite3_value **apVal /* Array of arguments */
  117408. ){
  117409. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  117410. const char *zStart = "<b>";
  117411. const char *zEnd = "</b>";
  117412. const char *zEllipsis = "<b>...</b>";
  117413. int iCol = -1;
  117414. int nToken = 15; /* Default number of tokens in snippet */
  117415. /* There must be at least one argument passed to this function (otherwise
  117416. ** the non-overloaded version would have been called instead of this one).
  117417. */
  117418. assert( nVal>=1 );
  117419. if( nVal>6 ){
  117420. sqlite3_result_error(pContext,
  117421. "wrong number of arguments to function snippet()", -1);
  117422. return;
  117423. }
  117424. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  117425. switch( nVal ){
  117426. case 6: nToken = sqlite3_value_int(apVal[5]);
  117427. case 5: iCol = sqlite3_value_int(apVal[4]);
  117428. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  117429. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  117430. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  117431. }
  117432. if( !zEllipsis || !zEnd || !zStart ){
  117433. sqlite3_result_error_nomem(pContext);
  117434. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  117435. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  117436. }
  117437. }
  117438. /*
  117439. ** Implementation of the offsets() function for FTS3
  117440. */
  117441. static void fts3OffsetsFunc(
  117442. sqlite3_context *pContext, /* SQLite function call context */
  117443. int nVal, /* Size of argument array */
  117444. sqlite3_value **apVal /* Array of arguments */
  117445. ){
  117446. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  117447. UNUSED_PARAMETER(nVal);
  117448. assert( nVal==1 );
  117449. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  117450. assert( pCsr );
  117451. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  117452. sqlite3Fts3Offsets(pContext, pCsr);
  117453. }
  117454. }
  117455. /*
  117456. ** Implementation of the special optimize() function for FTS3. This
  117457. ** function merges all segments in the database to a single segment.
  117458. ** Example usage is:
  117459. **
  117460. ** SELECT optimize(t) FROM t LIMIT 1;
  117461. **
  117462. ** where 't' is the name of an FTS3 table.
  117463. */
  117464. static void fts3OptimizeFunc(
  117465. sqlite3_context *pContext, /* SQLite function call context */
  117466. int nVal, /* Size of argument array */
  117467. sqlite3_value **apVal /* Array of arguments */
  117468. ){
  117469. int rc; /* Return code */
  117470. Fts3Table *p; /* Virtual table handle */
  117471. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  117472. UNUSED_PARAMETER(nVal);
  117473. assert( nVal==1 );
  117474. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  117475. p = (Fts3Table *)pCursor->base.pVtab;
  117476. assert( p );
  117477. rc = sqlite3Fts3Optimize(p);
  117478. switch( rc ){
  117479. case SQLITE_OK:
  117480. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  117481. break;
  117482. case SQLITE_DONE:
  117483. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  117484. break;
  117485. default:
  117486. sqlite3_result_error_code(pContext, rc);
  117487. break;
  117488. }
  117489. }
  117490. /*
  117491. ** Implementation of the matchinfo() function for FTS3
  117492. */
  117493. static void fts3MatchinfoFunc(
  117494. sqlite3_context *pContext, /* SQLite function call context */
  117495. int nVal, /* Size of argument array */
  117496. sqlite3_value **apVal /* Array of arguments */
  117497. ){
  117498. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  117499. assert( nVal==1 || nVal==2 );
  117500. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  117501. const char *zArg = 0;
  117502. if( nVal>1 ){
  117503. zArg = (const char *)sqlite3_value_text(apVal[1]);
  117504. }
  117505. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  117506. }
  117507. }
  117508. /*
  117509. ** This routine implements the xFindFunction method for the FTS3
  117510. ** virtual table.
  117511. */
  117512. static int fts3FindFunctionMethod(
  117513. sqlite3_vtab *pVtab, /* Virtual table handle */
  117514. int nArg, /* Number of SQL function arguments */
  117515. const char *zName, /* Name of SQL function */
  117516. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  117517. void **ppArg /* Unused */
  117518. ){
  117519. struct Overloaded {
  117520. const char *zName;
  117521. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  117522. } aOverload[] = {
  117523. { "snippet", fts3SnippetFunc },
  117524. { "offsets", fts3OffsetsFunc },
  117525. { "optimize", fts3OptimizeFunc },
  117526. { "matchinfo", fts3MatchinfoFunc },
  117527. };
  117528. int i; /* Iterator variable */
  117529. UNUSED_PARAMETER(pVtab);
  117530. UNUSED_PARAMETER(nArg);
  117531. UNUSED_PARAMETER(ppArg);
  117532. for(i=0; i<SizeofArray(aOverload); i++){
  117533. if( strcmp(zName, aOverload[i].zName)==0 ){
  117534. *pxFunc = aOverload[i].xFunc;
  117535. return 1;
  117536. }
  117537. }
  117538. /* No function of the specified name was found. Return 0. */
  117539. return 0;
  117540. }
  117541. /*
  117542. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  117543. */
  117544. static int fts3RenameMethod(
  117545. sqlite3_vtab *pVtab, /* Virtual table handle */
  117546. const char *zName /* New name of table */
  117547. ){
  117548. Fts3Table *p = (Fts3Table *)pVtab;
  117549. sqlite3 *db = p->db; /* Database connection */
  117550. int rc; /* Return Code */
  117551. /* As it happens, the pending terms table is always empty here. This is
  117552. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  117553. ** always opens a savepoint transaction. And the xSavepoint() method
  117554. ** flushes the pending terms table. But leave the (no-op) call to
  117555. ** PendingTermsFlush() in in case that changes.
  117556. */
  117557. assert( p->nPendingData==0 );
  117558. rc = sqlite3Fts3PendingTermsFlush(p);
  117559. if( p->zContentTbl==0 ){
  117560. fts3DbExec(&rc, db,
  117561. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  117562. p->zDb, p->zName, zName
  117563. );
  117564. }
  117565. if( p->bHasDocsize ){
  117566. fts3DbExec(&rc, db,
  117567. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  117568. p->zDb, p->zName, zName
  117569. );
  117570. }
  117571. if( p->bHasStat ){
  117572. fts3DbExec(&rc, db,
  117573. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  117574. p->zDb, p->zName, zName
  117575. );
  117576. }
  117577. fts3DbExec(&rc, db,
  117578. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  117579. p->zDb, p->zName, zName
  117580. );
  117581. fts3DbExec(&rc, db,
  117582. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  117583. p->zDb, p->zName, zName
  117584. );
  117585. return rc;
  117586. }
  117587. /*
  117588. ** The xSavepoint() method.
  117589. **
  117590. ** Flush the contents of the pending-terms table to disk.
  117591. */
  117592. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  117593. int rc = SQLITE_OK;
  117594. UNUSED_PARAMETER(iSavepoint);
  117595. assert( ((Fts3Table *)pVtab)->inTransaction );
  117596. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  117597. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  117598. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  117599. rc = fts3SyncMethod(pVtab);
  117600. }
  117601. return rc;
  117602. }
  117603. /*
  117604. ** The xRelease() method.
  117605. **
  117606. ** This is a no-op.
  117607. */
  117608. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  117609. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  117610. UNUSED_PARAMETER(iSavepoint);
  117611. UNUSED_PARAMETER(pVtab);
  117612. assert( p->inTransaction );
  117613. assert( p->mxSavepoint >= iSavepoint );
  117614. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  117615. return SQLITE_OK;
  117616. }
  117617. /*
  117618. ** The xRollbackTo() method.
  117619. **
  117620. ** Discard the contents of the pending terms table.
  117621. */
  117622. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  117623. Fts3Table *p = (Fts3Table*)pVtab;
  117624. UNUSED_PARAMETER(iSavepoint);
  117625. assert( p->inTransaction );
  117626. assert( p->mxSavepoint >= iSavepoint );
  117627. TESTONLY( p->mxSavepoint = iSavepoint );
  117628. sqlite3Fts3PendingTermsClear(p);
  117629. return SQLITE_OK;
  117630. }
  117631. static const sqlite3_module fts3Module = {
  117632. /* iVersion */ 2,
  117633. /* xCreate */ fts3CreateMethod,
  117634. /* xConnect */ fts3ConnectMethod,
  117635. /* xBestIndex */ fts3BestIndexMethod,
  117636. /* xDisconnect */ fts3DisconnectMethod,
  117637. /* xDestroy */ fts3DestroyMethod,
  117638. /* xOpen */ fts3OpenMethod,
  117639. /* xClose */ fts3CloseMethod,
  117640. /* xFilter */ fts3FilterMethod,
  117641. /* xNext */ fts3NextMethod,
  117642. /* xEof */ fts3EofMethod,
  117643. /* xColumn */ fts3ColumnMethod,
  117644. /* xRowid */ fts3RowidMethod,
  117645. /* xUpdate */ fts3UpdateMethod,
  117646. /* xBegin */ fts3BeginMethod,
  117647. /* xSync */ fts3SyncMethod,
  117648. /* xCommit */ fts3CommitMethod,
  117649. /* xRollback */ fts3RollbackMethod,
  117650. /* xFindFunction */ fts3FindFunctionMethod,
  117651. /* xRename */ fts3RenameMethod,
  117652. /* xSavepoint */ fts3SavepointMethod,
  117653. /* xRelease */ fts3ReleaseMethod,
  117654. /* xRollbackTo */ fts3RollbackToMethod,
  117655. };
  117656. /*
  117657. ** This function is registered as the module destructor (called when an
  117658. ** FTS3 enabled database connection is closed). It frees the memory
  117659. ** allocated for the tokenizer hash table.
  117660. */
  117661. static void hashDestroy(void *p){
  117662. Fts3Hash *pHash = (Fts3Hash *)p;
  117663. sqlite3Fts3HashClear(pHash);
  117664. sqlite3_free(pHash);
  117665. }
  117666. /*
  117667. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  117668. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  117669. ** respectively. The following three forward declarations are for functions
  117670. ** declared in these files used to retrieve the respective implementations.
  117671. **
  117672. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  117673. ** to by the argument to point to the "simple" tokenizer implementation.
  117674. ** And so on.
  117675. */
  117676. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  117677. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  117678. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  117679. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  117680. #endif
  117681. #ifdef SQLITE_ENABLE_ICU
  117682. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  117683. #endif
  117684. /*
  117685. ** Initialize the fts3 extension. If this extension is built as part
  117686. ** of the sqlite library, then this function is called directly by
  117687. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  117688. ** function is called by the sqlite3_extension_init() entry point.
  117689. */
  117690. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  117691. int rc = SQLITE_OK;
  117692. Fts3Hash *pHash = 0;
  117693. const sqlite3_tokenizer_module *pSimple = 0;
  117694. const sqlite3_tokenizer_module *pPorter = 0;
  117695. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  117696. const sqlite3_tokenizer_module *pUnicode = 0;
  117697. #endif
  117698. #ifdef SQLITE_ENABLE_ICU
  117699. const sqlite3_tokenizer_module *pIcu = 0;
  117700. sqlite3Fts3IcuTokenizerModule(&pIcu);
  117701. #endif
  117702. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  117703. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  117704. #endif
  117705. #ifdef SQLITE_TEST
  117706. rc = sqlite3Fts3InitTerm(db);
  117707. if( rc!=SQLITE_OK ) return rc;
  117708. #endif
  117709. rc = sqlite3Fts3InitAux(db);
  117710. if( rc!=SQLITE_OK ) return rc;
  117711. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  117712. sqlite3Fts3PorterTokenizerModule(&pPorter);
  117713. /* Allocate and initialize the hash-table used to store tokenizers. */
  117714. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  117715. if( !pHash ){
  117716. rc = SQLITE_NOMEM;
  117717. }else{
  117718. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  117719. }
  117720. /* Load the built-in tokenizers into the hash table */
  117721. if( rc==SQLITE_OK ){
  117722. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  117723. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  117724. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  117725. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  117726. #endif
  117727. #ifdef SQLITE_ENABLE_ICU
  117728. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  117729. #endif
  117730. ){
  117731. rc = SQLITE_NOMEM;
  117732. }
  117733. }
  117734. #ifdef SQLITE_TEST
  117735. if( rc==SQLITE_OK ){
  117736. rc = sqlite3Fts3ExprInitTestInterface(db);
  117737. }
  117738. #endif
  117739. /* Create the virtual table wrapper around the hash-table and overload
  117740. ** the two scalar functions. If this is successful, register the
  117741. ** module with sqlite.
  117742. */
  117743. if( SQLITE_OK==rc
  117744. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  117745. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  117746. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  117747. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  117748. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  117749. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  117750. ){
  117751. rc = sqlite3_create_module_v2(
  117752. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  117753. );
  117754. if( rc==SQLITE_OK ){
  117755. rc = sqlite3_create_module_v2(
  117756. db, "fts4", &fts3Module, (void *)pHash, 0
  117757. );
  117758. }
  117759. if( rc==SQLITE_OK ){
  117760. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  117761. }
  117762. return rc;
  117763. }
  117764. /* An error has occurred. Delete the hash table and return the error code. */
  117765. assert( rc!=SQLITE_OK );
  117766. if( pHash ){
  117767. sqlite3Fts3HashClear(pHash);
  117768. sqlite3_free(pHash);
  117769. }
  117770. return rc;
  117771. }
  117772. /*
  117773. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  117774. ** by pExpr.
  117775. **
  117776. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  117777. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  117778. ** Fts3SegReader objects internally to provide an interface to seek or scan
  117779. ** within the union of all segments of a b-tree. Hence the name.
  117780. **
  117781. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  117782. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  117783. ** there exists prefix b-tree of the right length) then it may be traversed
  117784. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  117785. ** doclist and then traversed.
  117786. */
  117787. static void fts3EvalAllocateReaders(
  117788. Fts3Cursor *pCsr, /* FTS cursor handle */
  117789. Fts3Expr *pExpr, /* Allocate readers for this expression */
  117790. int *pnToken, /* OUT: Total number of tokens in phrase. */
  117791. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  117792. int *pRc /* IN/OUT: Error code */
  117793. ){
  117794. if( pExpr && SQLITE_OK==*pRc ){
  117795. if( pExpr->eType==FTSQUERY_PHRASE ){
  117796. int i;
  117797. int nToken = pExpr->pPhrase->nToken;
  117798. *pnToken += nToken;
  117799. for(i=0; i<nToken; i++){
  117800. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  117801. int rc = fts3TermSegReaderCursor(pCsr,
  117802. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  117803. );
  117804. if( rc!=SQLITE_OK ){
  117805. *pRc = rc;
  117806. return;
  117807. }
  117808. }
  117809. assert( pExpr->pPhrase->iDoclistToken==0 );
  117810. pExpr->pPhrase->iDoclistToken = -1;
  117811. }else{
  117812. *pnOr += (pExpr->eType==FTSQUERY_OR);
  117813. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  117814. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  117815. }
  117816. }
  117817. }
  117818. /*
  117819. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  117820. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  117821. **
  117822. ** This function assumes that pList points to a buffer allocated using
  117823. ** sqlite3_malloc(). This function takes responsibility for eventually
  117824. ** freeing the buffer.
  117825. */
  117826. static void fts3EvalPhraseMergeToken(
  117827. Fts3Table *pTab, /* FTS Table pointer */
  117828. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  117829. int iToken, /* Token pList/nList corresponds to */
  117830. char *pList, /* Pointer to doclist */
  117831. int nList /* Number of bytes in pList */
  117832. ){
  117833. assert( iToken!=p->iDoclistToken );
  117834. if( pList==0 ){
  117835. sqlite3_free(p->doclist.aAll);
  117836. p->doclist.aAll = 0;
  117837. p->doclist.nAll = 0;
  117838. }
  117839. else if( p->iDoclistToken<0 ){
  117840. p->doclist.aAll = pList;
  117841. p->doclist.nAll = nList;
  117842. }
  117843. else if( p->doclist.aAll==0 ){
  117844. sqlite3_free(pList);
  117845. }
  117846. else {
  117847. char *pLeft;
  117848. char *pRight;
  117849. int nLeft;
  117850. int nRight;
  117851. int nDiff;
  117852. if( p->iDoclistToken<iToken ){
  117853. pLeft = p->doclist.aAll;
  117854. nLeft = p->doclist.nAll;
  117855. pRight = pList;
  117856. nRight = nList;
  117857. nDiff = iToken - p->iDoclistToken;
  117858. }else{
  117859. pRight = p->doclist.aAll;
  117860. nRight = p->doclist.nAll;
  117861. pLeft = pList;
  117862. nLeft = nList;
  117863. nDiff = p->iDoclistToken - iToken;
  117864. }
  117865. fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
  117866. sqlite3_free(pLeft);
  117867. p->doclist.aAll = pRight;
  117868. p->doclist.nAll = nRight;
  117869. }
  117870. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  117871. }
  117872. /*
  117873. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  117874. ** does not take deferred tokens into account.
  117875. **
  117876. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  117877. */
  117878. static int fts3EvalPhraseLoad(
  117879. Fts3Cursor *pCsr, /* FTS Cursor handle */
  117880. Fts3Phrase *p /* Phrase object */
  117881. ){
  117882. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  117883. int iToken;
  117884. int rc = SQLITE_OK;
  117885. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  117886. Fts3PhraseToken *pToken = &p->aToken[iToken];
  117887. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  117888. if( pToken->pSegcsr ){
  117889. int nThis = 0;
  117890. char *pThis = 0;
  117891. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  117892. if( rc==SQLITE_OK ){
  117893. fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  117894. }
  117895. }
  117896. assert( pToken->pSegcsr==0 );
  117897. }
  117898. return rc;
  117899. }
  117900. /*
  117901. ** This function is called on each phrase after the position lists for
  117902. ** any deferred tokens have been loaded into memory. It updates the phrases
  117903. ** current position list to include only those positions that are really
  117904. ** instances of the phrase (after considering deferred tokens). If this
  117905. ** means that the phrase does not appear in the current row, doclist.pList
  117906. ** and doclist.nList are both zeroed.
  117907. **
  117908. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  117909. */
  117910. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  117911. int iToken; /* Used to iterate through phrase tokens */
  117912. char *aPoslist = 0; /* Position list for deferred tokens */
  117913. int nPoslist = 0; /* Number of bytes in aPoslist */
  117914. int iPrev = -1; /* Token number of previous deferred token */
  117915. assert( pPhrase->doclist.bFreeList==0 );
  117916. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  117917. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  117918. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  117919. if( pDeferred ){
  117920. char *pList;
  117921. int nList;
  117922. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  117923. if( rc!=SQLITE_OK ) return rc;
  117924. if( pList==0 ){
  117925. sqlite3_free(aPoslist);
  117926. pPhrase->doclist.pList = 0;
  117927. pPhrase->doclist.nList = 0;
  117928. return SQLITE_OK;
  117929. }else if( aPoslist==0 ){
  117930. aPoslist = pList;
  117931. nPoslist = nList;
  117932. }else{
  117933. char *aOut = pList;
  117934. char *p1 = aPoslist;
  117935. char *p2 = aOut;
  117936. assert( iPrev>=0 );
  117937. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  117938. sqlite3_free(aPoslist);
  117939. aPoslist = pList;
  117940. nPoslist = (int)(aOut - aPoslist);
  117941. if( nPoslist==0 ){
  117942. sqlite3_free(aPoslist);
  117943. pPhrase->doclist.pList = 0;
  117944. pPhrase->doclist.nList = 0;
  117945. return SQLITE_OK;
  117946. }
  117947. }
  117948. iPrev = iToken;
  117949. }
  117950. }
  117951. if( iPrev>=0 ){
  117952. int nMaxUndeferred = pPhrase->iDoclistToken;
  117953. if( nMaxUndeferred<0 ){
  117954. pPhrase->doclist.pList = aPoslist;
  117955. pPhrase->doclist.nList = nPoslist;
  117956. pPhrase->doclist.iDocid = pCsr->iPrevId;
  117957. pPhrase->doclist.bFreeList = 1;
  117958. }else{
  117959. int nDistance;
  117960. char *p1;
  117961. char *p2;
  117962. char *aOut;
  117963. if( nMaxUndeferred>iPrev ){
  117964. p1 = aPoslist;
  117965. p2 = pPhrase->doclist.pList;
  117966. nDistance = nMaxUndeferred - iPrev;
  117967. }else{
  117968. p1 = pPhrase->doclist.pList;
  117969. p2 = aPoslist;
  117970. nDistance = iPrev - nMaxUndeferred;
  117971. }
  117972. aOut = (char *)sqlite3_malloc(nPoslist+8);
  117973. if( !aOut ){
  117974. sqlite3_free(aPoslist);
  117975. return SQLITE_NOMEM;
  117976. }
  117977. pPhrase->doclist.pList = aOut;
  117978. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  117979. pPhrase->doclist.bFreeList = 1;
  117980. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  117981. }else{
  117982. sqlite3_free(aOut);
  117983. pPhrase->doclist.pList = 0;
  117984. pPhrase->doclist.nList = 0;
  117985. }
  117986. sqlite3_free(aPoslist);
  117987. }
  117988. }
  117989. return SQLITE_OK;
  117990. }
  117991. /*
  117992. ** Maximum number of tokens a phrase may have to be considered for the
  117993. ** incremental doclists strategy.
  117994. */
  117995. #define MAX_INCR_PHRASE_TOKENS 4
  117996. /*
  117997. ** This function is called for each Fts3Phrase in a full-text query
  117998. ** expression to initialize the mechanism for returning rows. Once this
  117999. ** function has been called successfully on an Fts3Phrase, it may be
  118000. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  118001. **
  118002. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  118003. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  118004. ** memory within this call.
  118005. **
  118006. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  118007. */
  118008. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  118009. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  118010. int rc = SQLITE_OK; /* Error code */
  118011. int i;
  118012. /* Determine if doclists may be loaded from disk incrementally. This is
  118013. ** possible if the bOptOk argument is true, the FTS doclists will be
  118014. ** scanned in forward order, and the phrase consists of
  118015. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  118016. ** tokens or prefix tokens that cannot use a prefix-index. */
  118017. int bHaveIncr = 0;
  118018. int bIncrOk = (bOptOk
  118019. && pCsr->bDesc==pTab->bDescIdx
  118020. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  118021. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  118022. #ifdef SQLITE_TEST
  118023. && pTab->bNoIncrDoclist==0
  118024. #endif
  118025. );
  118026. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  118027. Fts3PhraseToken *pToken = &p->aToken[i];
  118028. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  118029. bIncrOk = 0;
  118030. }
  118031. if( pToken->pSegcsr ) bHaveIncr = 1;
  118032. }
  118033. if( bIncrOk && bHaveIncr ){
  118034. /* Use the incremental approach. */
  118035. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  118036. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  118037. Fts3PhraseToken *pToken = &p->aToken[i];
  118038. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  118039. if( pSegcsr ){
  118040. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  118041. }
  118042. }
  118043. p->bIncr = 1;
  118044. }else{
  118045. /* Load the full doclist for the phrase into memory. */
  118046. rc = fts3EvalPhraseLoad(pCsr, p);
  118047. p->bIncr = 0;
  118048. }
  118049. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  118050. return rc;
  118051. }
  118052. /*
  118053. ** This function is used to iterate backwards (from the end to start)
  118054. ** through doclists. It is used by this module to iterate through phrase
  118055. ** doclists in reverse and by the fts3_write.c module to iterate through
  118056. ** pending-terms lists when writing to databases with "order=desc".
  118057. **
  118058. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  118059. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  118060. ** function iterates from the end of the doclist to the beginning.
  118061. */
  118062. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  118063. int bDescIdx, /* True if the doclist is desc */
  118064. char *aDoclist, /* Pointer to entire doclist */
  118065. int nDoclist, /* Length of aDoclist in bytes */
  118066. char **ppIter, /* IN/OUT: Iterator pointer */
  118067. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  118068. int *pnList, /* OUT: List length pointer */
  118069. u8 *pbEof /* OUT: End-of-file flag */
  118070. ){
  118071. char *p = *ppIter;
  118072. assert( nDoclist>0 );
  118073. assert( *pbEof==0 );
  118074. assert( p || *piDocid==0 );
  118075. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  118076. if( p==0 ){
  118077. sqlite3_int64 iDocid = 0;
  118078. char *pNext = 0;
  118079. char *pDocid = aDoclist;
  118080. char *pEnd = &aDoclist[nDoclist];
  118081. int iMul = 1;
  118082. while( pDocid<pEnd ){
  118083. sqlite3_int64 iDelta;
  118084. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  118085. iDocid += (iMul * iDelta);
  118086. pNext = pDocid;
  118087. fts3PoslistCopy(0, &pDocid);
  118088. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  118089. iMul = (bDescIdx ? -1 : 1);
  118090. }
  118091. *pnList = (int)(pEnd - pNext);
  118092. *ppIter = pNext;
  118093. *piDocid = iDocid;
  118094. }else{
  118095. int iMul = (bDescIdx ? -1 : 1);
  118096. sqlite3_int64 iDelta;
  118097. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  118098. *piDocid -= (iMul * iDelta);
  118099. if( p==aDoclist ){
  118100. *pbEof = 1;
  118101. }else{
  118102. char *pSave = p;
  118103. fts3ReversePoslist(aDoclist, &p);
  118104. *pnList = (int)(pSave - p);
  118105. }
  118106. *ppIter = p;
  118107. }
  118108. }
  118109. /*
  118110. ** Iterate forwards through a doclist.
  118111. */
  118112. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  118113. int bDescIdx, /* True if the doclist is desc */
  118114. char *aDoclist, /* Pointer to entire doclist */
  118115. int nDoclist, /* Length of aDoclist in bytes */
  118116. char **ppIter, /* IN/OUT: Iterator pointer */
  118117. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  118118. u8 *pbEof /* OUT: End-of-file flag */
  118119. ){
  118120. char *p = *ppIter;
  118121. assert( nDoclist>0 );
  118122. assert( *pbEof==0 );
  118123. assert( p || *piDocid==0 );
  118124. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  118125. if( p==0 ){
  118126. p = aDoclist;
  118127. p += sqlite3Fts3GetVarint(p, piDocid);
  118128. }else{
  118129. fts3PoslistCopy(0, &p);
  118130. if( p>=&aDoclist[nDoclist] ){
  118131. *pbEof = 1;
  118132. }else{
  118133. sqlite3_int64 iVar;
  118134. p += sqlite3Fts3GetVarint(p, &iVar);
  118135. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  118136. }
  118137. }
  118138. *ppIter = p;
  118139. }
  118140. /*
  118141. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  118142. ** to true if EOF is reached.
  118143. */
  118144. static void fts3EvalDlPhraseNext(
  118145. Fts3Table *pTab,
  118146. Fts3Doclist *pDL,
  118147. u8 *pbEof
  118148. ){
  118149. char *pIter; /* Used to iterate through aAll */
  118150. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  118151. if( pDL->pNextDocid ){
  118152. pIter = pDL->pNextDocid;
  118153. }else{
  118154. pIter = pDL->aAll;
  118155. }
  118156. if( pIter>=pEnd ){
  118157. /* We have already reached the end of this doclist. EOF. */
  118158. *pbEof = 1;
  118159. }else{
  118160. sqlite3_int64 iDelta;
  118161. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  118162. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  118163. pDL->iDocid += iDelta;
  118164. }else{
  118165. pDL->iDocid -= iDelta;
  118166. }
  118167. pDL->pList = pIter;
  118168. fts3PoslistCopy(0, &pIter);
  118169. pDL->nList = (int)(pIter - pDL->pList);
  118170. /* pIter now points just past the 0x00 that terminates the position-
  118171. ** list for document pDL->iDocid. However, if this position-list was
  118172. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  118173. ** point to the start of the next docid value. The following line deals
  118174. ** with this case by advancing pIter past the zero-padding added by
  118175. ** fts3EvalNearTrim(). */
  118176. while( pIter<pEnd && *pIter==0 ) pIter++;
  118177. pDL->pNextDocid = pIter;
  118178. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  118179. *pbEof = 0;
  118180. }
  118181. }
  118182. /*
  118183. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  118184. */
  118185. typedef struct TokenDoclist TokenDoclist;
  118186. struct TokenDoclist {
  118187. int bIgnore;
  118188. sqlite3_int64 iDocid;
  118189. char *pList;
  118190. int nList;
  118191. };
  118192. /*
  118193. ** Token pToken is an incrementally loaded token that is part of a
  118194. ** multi-token phrase. Advance it to the next matching document in the
  118195. ** database and populate output variable *p with the details of the new
  118196. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  118197. **
  118198. ** If an error occurs, return an SQLite error code. Otherwise, return
  118199. ** SQLITE_OK.
  118200. */
  118201. static int incrPhraseTokenNext(
  118202. Fts3Table *pTab, /* Virtual table handle */
  118203. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  118204. int iToken, /* Specific token to advance */
  118205. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  118206. u8 *pbEof /* OUT: True if iterator is at EOF */
  118207. ){
  118208. int rc = SQLITE_OK;
  118209. if( pPhrase->iDoclistToken==iToken ){
  118210. assert( p->bIgnore==0 );
  118211. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  118212. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  118213. p->pList = pPhrase->doclist.pList;
  118214. p->nList = pPhrase->doclist.nList;
  118215. p->iDocid = pPhrase->doclist.iDocid;
  118216. }else{
  118217. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  118218. assert( pToken->pDeferred==0 );
  118219. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  118220. if( pToken->pSegcsr ){
  118221. assert( p->bIgnore==0 );
  118222. rc = sqlite3Fts3MsrIncrNext(
  118223. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  118224. );
  118225. if( p->pList==0 ) *pbEof = 1;
  118226. }else{
  118227. p->bIgnore = 1;
  118228. }
  118229. }
  118230. return rc;
  118231. }
  118232. /*
  118233. ** The phrase iterator passed as the second argument:
  118234. **
  118235. ** * features at least one token that uses an incremental doclist, and
  118236. **
  118237. ** * does not contain any deferred tokens.
  118238. **
  118239. ** Advance it to the next matching documnent in the database and populate
  118240. ** the Fts3Doclist.pList and nList fields.
  118241. **
  118242. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  118243. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  118244. ** successfully advanced, *pbEof is set to 0.
  118245. **
  118246. ** If an error occurs, return an SQLite error code. Otherwise, return
  118247. ** SQLITE_OK.
  118248. */
  118249. static int fts3EvalIncrPhraseNext(
  118250. Fts3Cursor *pCsr, /* FTS Cursor handle */
  118251. Fts3Phrase *p, /* Phrase object to advance to next docid */
  118252. u8 *pbEof /* OUT: Set to 1 if EOF */
  118253. ){
  118254. int rc = SQLITE_OK;
  118255. Fts3Doclist *pDL = &p->doclist;
  118256. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  118257. u8 bEof = 0;
  118258. /* This is only called if it is guaranteed that the phrase has at least
  118259. ** one incremental token. In which case the bIncr flag is set. */
  118260. assert( p->bIncr==1 );
  118261. if( p->nToken==1 && p->bIncr ){
  118262. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  118263. &pDL->iDocid, &pDL->pList, &pDL->nList
  118264. );
  118265. if( pDL->pList==0 ) bEof = 1;
  118266. }else{
  118267. int bDescDoclist = pCsr->bDesc;
  118268. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  118269. memset(a, 0, sizeof(a));
  118270. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  118271. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  118272. while( bEof==0 ){
  118273. int bMaxSet = 0;
  118274. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  118275. int i; /* Used to iterate through tokens */
  118276. /* Advance the iterator for each token in the phrase once. */
  118277. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  118278. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  118279. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  118280. iMax = a[i].iDocid;
  118281. bMaxSet = 1;
  118282. }
  118283. }
  118284. assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 );
  118285. assert( rc!=SQLITE_OK || bMaxSet );
  118286. /* Keep advancing iterators until they all point to the same document */
  118287. for(i=0; i<p->nToken; i++){
  118288. while( rc==SQLITE_OK && bEof==0
  118289. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  118290. ){
  118291. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  118292. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  118293. iMax = a[i].iDocid;
  118294. i = 0;
  118295. }
  118296. }
  118297. }
  118298. /* Check if the current entries really are a phrase match */
  118299. if( bEof==0 ){
  118300. int nList = 0;
  118301. int nByte = a[p->nToken-1].nList;
  118302. char *aDoclist = sqlite3_malloc(nByte+1);
  118303. if( !aDoclist ) return SQLITE_NOMEM;
  118304. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  118305. for(i=0; i<(p->nToken-1); i++){
  118306. if( a[i].bIgnore==0 ){
  118307. char *pL = a[i].pList;
  118308. char *pR = aDoclist;
  118309. char *pOut = aDoclist;
  118310. int nDist = p->nToken-1-i;
  118311. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  118312. if( res==0 ) break;
  118313. nList = (int)(pOut - aDoclist);
  118314. }
  118315. }
  118316. if( i==(p->nToken-1) ){
  118317. pDL->iDocid = iMax;
  118318. pDL->pList = aDoclist;
  118319. pDL->nList = nList;
  118320. pDL->bFreeList = 1;
  118321. break;
  118322. }
  118323. sqlite3_free(aDoclist);
  118324. }
  118325. }
  118326. }
  118327. *pbEof = bEof;
  118328. return rc;
  118329. }
  118330. /*
  118331. ** Attempt to move the phrase iterator to point to the next matching docid.
  118332. ** If an error occurs, return an SQLite error code. Otherwise, return
  118333. ** SQLITE_OK.
  118334. **
  118335. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  118336. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  118337. ** successfully advanced, *pbEof is set to 0.
  118338. */
  118339. static int fts3EvalPhraseNext(
  118340. Fts3Cursor *pCsr, /* FTS Cursor handle */
  118341. Fts3Phrase *p, /* Phrase object to advance to next docid */
  118342. u8 *pbEof /* OUT: Set to 1 if EOF */
  118343. ){
  118344. int rc = SQLITE_OK;
  118345. Fts3Doclist *pDL = &p->doclist;
  118346. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  118347. if( p->bIncr ){
  118348. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  118349. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  118350. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  118351. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  118352. );
  118353. pDL->pList = pDL->pNextDocid;
  118354. }else{
  118355. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  118356. }
  118357. return rc;
  118358. }
  118359. /*
  118360. **
  118361. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  118362. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  118363. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  118364. ** expressions for which all descendent tokens are deferred.
  118365. **
  118366. ** If parameter bOptOk is zero, then it is guaranteed that the
  118367. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  118368. ** each phrase in the expression (subject to deferred token processing).
  118369. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  118370. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  118371. **
  118372. ** If an error occurs within this function, *pRc is set to an SQLite error
  118373. ** code before returning.
  118374. */
  118375. static void fts3EvalStartReaders(
  118376. Fts3Cursor *pCsr, /* FTS Cursor handle */
  118377. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  118378. int *pRc /* IN/OUT: Error code */
  118379. ){
  118380. if( pExpr && SQLITE_OK==*pRc ){
  118381. if( pExpr->eType==FTSQUERY_PHRASE ){
  118382. int i;
  118383. int nToken = pExpr->pPhrase->nToken;
  118384. for(i=0; i<nToken; i++){
  118385. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  118386. }
  118387. pExpr->bDeferred = (i==nToken);
  118388. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  118389. }else{
  118390. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  118391. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  118392. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  118393. }
  118394. }
  118395. }
  118396. /*
  118397. ** An array of the following structures is assembled as part of the process
  118398. ** of selecting tokens to defer before the query starts executing (as part
  118399. ** of the xFilter() method). There is one element in the array for each
  118400. ** token in the FTS expression.
  118401. **
  118402. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  118403. ** to phrases that are connected only by AND and NEAR operators (not OR or
  118404. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  118405. ** separately. The root of a tokens AND/NEAR cluster is stored in
  118406. ** Fts3TokenAndCost.pRoot.
  118407. */
  118408. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  118409. struct Fts3TokenAndCost {
  118410. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  118411. int iToken; /* Position of token in phrase */
  118412. Fts3PhraseToken *pToken; /* The token itself */
  118413. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  118414. int nOvfl; /* Number of overflow pages to load doclist */
  118415. int iCol; /* The column the token must match */
  118416. };
  118417. /*
  118418. ** This function is used to populate an allocated Fts3TokenAndCost array.
  118419. **
  118420. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  118421. ** Otherwise, if an error occurs during execution, *pRc is set to an
  118422. ** SQLite error code.
  118423. */
  118424. static void fts3EvalTokenCosts(
  118425. Fts3Cursor *pCsr, /* FTS Cursor handle */
  118426. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  118427. Fts3Expr *pExpr, /* Expression to consider */
  118428. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  118429. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  118430. int *pRc /* IN/OUT: Error code */
  118431. ){
  118432. if( *pRc==SQLITE_OK ){
  118433. if( pExpr->eType==FTSQUERY_PHRASE ){
  118434. Fts3Phrase *pPhrase = pExpr->pPhrase;
  118435. int i;
  118436. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  118437. Fts3TokenAndCost *pTC = (*ppTC)++;
  118438. pTC->pPhrase = pPhrase;
  118439. pTC->iToken = i;
  118440. pTC->pRoot = pRoot;
  118441. pTC->pToken = &pPhrase->aToken[i];
  118442. pTC->iCol = pPhrase->iColumn;
  118443. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  118444. }
  118445. }else if( pExpr->eType!=FTSQUERY_NOT ){
  118446. assert( pExpr->eType==FTSQUERY_OR
  118447. || pExpr->eType==FTSQUERY_AND
  118448. || pExpr->eType==FTSQUERY_NEAR
  118449. );
  118450. assert( pExpr->pLeft && pExpr->pRight );
  118451. if( pExpr->eType==FTSQUERY_OR ){
  118452. pRoot = pExpr->pLeft;
  118453. **ppOr = pRoot;
  118454. (*ppOr)++;
  118455. }
  118456. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  118457. if( pExpr->eType==FTSQUERY_OR ){
  118458. pRoot = pExpr->pRight;
  118459. **ppOr = pRoot;
  118460. (*ppOr)++;
  118461. }
  118462. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  118463. }
  118464. }
  118465. }
  118466. /*
  118467. ** Determine the average document (row) size in pages. If successful,
  118468. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  118469. ** an SQLite error code.
  118470. **
  118471. ** The average document size in pages is calculated by first calculating
  118472. ** determining the average size in bytes, B. If B is less than the amount
  118473. ** of data that will fit on a single leaf page of an intkey table in
  118474. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  118475. ** the number of overflow pages consumed by a record B bytes in size.
  118476. */
  118477. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  118478. if( pCsr->nRowAvg==0 ){
  118479. /* The average document size, which is required to calculate the cost
  118480. ** of each doclist, has not yet been determined. Read the required
  118481. ** data from the %_stat table to calculate it.
  118482. **
  118483. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  118484. ** varints, where nCol is the number of columns in the FTS3 table.
  118485. ** The first varint is the number of documents currently stored in
  118486. ** the table. The following nCol varints contain the total amount of
  118487. ** data stored in all rows of each column of the table, from left
  118488. ** to right.
  118489. */
  118490. int rc;
  118491. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  118492. sqlite3_stmt *pStmt;
  118493. sqlite3_int64 nDoc = 0;
  118494. sqlite3_int64 nByte = 0;
  118495. const char *pEnd;
  118496. const char *a;
  118497. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  118498. if( rc!=SQLITE_OK ) return rc;
  118499. a = sqlite3_column_blob(pStmt, 0);
  118500. assert( a );
  118501. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  118502. a += sqlite3Fts3GetVarint(a, &nDoc);
  118503. while( a<pEnd ){
  118504. a += sqlite3Fts3GetVarint(a, &nByte);
  118505. }
  118506. if( nDoc==0 || nByte==0 ){
  118507. sqlite3_reset(pStmt);
  118508. return FTS_CORRUPT_VTAB;
  118509. }
  118510. pCsr->nDoc = nDoc;
  118511. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  118512. assert( pCsr->nRowAvg>0 );
  118513. rc = sqlite3_reset(pStmt);
  118514. if( rc!=SQLITE_OK ) return rc;
  118515. }
  118516. *pnPage = pCsr->nRowAvg;
  118517. return SQLITE_OK;
  118518. }
  118519. /*
  118520. ** This function is called to select the tokens (if any) that will be
  118521. ** deferred. The array aTC[] has already been populated when this is
  118522. ** called.
  118523. **
  118524. ** This function is called once for each AND/NEAR cluster in the
  118525. ** expression. Each invocation determines which tokens to defer within
  118526. ** the cluster with root node pRoot. See comments above the definition
  118527. ** of struct Fts3TokenAndCost for more details.
  118528. **
  118529. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  118530. ** called on each token to defer. Otherwise, an SQLite error code is
  118531. ** returned.
  118532. */
  118533. static int fts3EvalSelectDeferred(
  118534. Fts3Cursor *pCsr, /* FTS Cursor handle */
  118535. Fts3Expr *pRoot, /* Consider tokens with this root node */
  118536. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  118537. int nTC /* Number of entries in aTC[] */
  118538. ){
  118539. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  118540. int nDocSize = 0; /* Number of pages per doc loaded */
  118541. int rc = SQLITE_OK; /* Return code */
  118542. int ii; /* Iterator variable for various purposes */
  118543. int nOvfl = 0; /* Total overflow pages used by doclists */
  118544. int nToken = 0; /* Total number of tokens in cluster */
  118545. int nMinEst = 0; /* The minimum count for any phrase so far. */
  118546. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  118547. /* Tokens are never deferred for FTS tables created using the content=xxx
  118548. ** option. The reason being that it is not guaranteed that the content
  118549. ** table actually contains the same data as the index. To prevent this from
  118550. ** causing any problems, the deferred token optimization is completely
  118551. ** disabled for content=xxx tables. */
  118552. if( pTab->zContentTbl ){
  118553. return SQLITE_OK;
  118554. }
  118555. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  118556. ** associated with the tokens spill onto overflow pages, or if there is
  118557. ** only 1 token, exit early. No tokens to defer in this case. */
  118558. for(ii=0; ii<nTC; ii++){
  118559. if( aTC[ii].pRoot==pRoot ){
  118560. nOvfl += aTC[ii].nOvfl;
  118561. nToken++;
  118562. }
  118563. }
  118564. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  118565. /* Obtain the average docsize (in pages). */
  118566. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  118567. assert( rc!=SQLITE_OK || nDocSize>0 );
  118568. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  118569. ** of the number of overflow pages that will be loaded by the pager layer
  118570. ** to retrieve the entire doclist for the token from the full-text index.
  118571. ** Load the doclists for tokens that are either:
  118572. **
  118573. ** a. The cheapest token in the entire query (i.e. the one visited by the
  118574. ** first iteration of this loop), or
  118575. **
  118576. ** b. Part of a multi-token phrase.
  118577. **
  118578. ** After each token doclist is loaded, merge it with the others from the
  118579. ** same phrase and count the number of documents that the merged doclist
  118580. ** contains. Set variable "nMinEst" to the smallest number of documents in
  118581. ** any phrase doclist for which 1 or more token doclists have been loaded.
  118582. ** Let nOther be the number of other phrases for which it is certain that
  118583. ** one or more tokens will not be deferred.
  118584. **
  118585. ** Then, for each token, defer it if loading the doclist would result in
  118586. ** loading N or more overflow pages into memory, where N is computed as:
  118587. **
  118588. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  118589. */
  118590. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  118591. int iTC; /* Used to iterate through aTC[] array. */
  118592. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  118593. /* Set pTC to point to the cheapest remaining token. */
  118594. for(iTC=0; iTC<nTC; iTC++){
  118595. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  118596. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  118597. ){
  118598. pTC = &aTC[iTC];
  118599. }
  118600. }
  118601. assert( pTC );
  118602. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  118603. /* The number of overflow pages to load for this (and therefore all
  118604. ** subsequent) tokens is greater than the estimated number of pages
  118605. ** that will be loaded if all subsequent tokens are deferred.
  118606. */
  118607. Fts3PhraseToken *pToken = pTC->pToken;
  118608. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  118609. fts3SegReaderCursorFree(pToken->pSegcsr);
  118610. pToken->pSegcsr = 0;
  118611. }else{
  118612. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  118613. ** for-loop. Except, limit the value to 2^24 to prevent it from
  118614. ** overflowing the 32-bit integer it is stored in. */
  118615. if( ii<12 ) nLoad4 = nLoad4*4;
  118616. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  118617. /* Either this is the cheapest token in the entire query, or it is
  118618. ** part of a multi-token phrase. Either way, the entire doclist will
  118619. ** (eventually) be loaded into memory. It may as well be now. */
  118620. Fts3PhraseToken *pToken = pTC->pToken;
  118621. int nList = 0;
  118622. char *pList = 0;
  118623. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  118624. assert( rc==SQLITE_OK || pList==0 );
  118625. if( rc==SQLITE_OK ){
  118626. int nCount;
  118627. fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
  118628. nCount = fts3DoclistCountDocids(
  118629. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  118630. );
  118631. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  118632. }
  118633. }
  118634. }
  118635. pTC->pToken = 0;
  118636. }
  118637. return rc;
  118638. }
  118639. /*
  118640. ** This function is called from within the xFilter method. It initializes
  118641. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  118642. ** the results of a query, the caller does:
  118643. **
  118644. ** fts3EvalStart(pCsr);
  118645. ** while( 1 ){
  118646. ** fts3EvalNext(pCsr);
  118647. ** if( pCsr->bEof ) break;
  118648. ** ... return row pCsr->iPrevId to the caller ...
  118649. ** }
  118650. */
  118651. static int fts3EvalStart(Fts3Cursor *pCsr){
  118652. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  118653. int rc = SQLITE_OK;
  118654. int nToken = 0;
  118655. int nOr = 0;
  118656. /* Allocate a MultiSegReader for each token in the expression. */
  118657. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  118658. /* Determine which, if any, tokens in the expression should be deferred. */
  118659. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  118660. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  118661. Fts3TokenAndCost *aTC;
  118662. Fts3Expr **apOr;
  118663. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  118664. sizeof(Fts3TokenAndCost) * nToken
  118665. + sizeof(Fts3Expr *) * nOr * 2
  118666. );
  118667. apOr = (Fts3Expr **)&aTC[nToken];
  118668. if( !aTC ){
  118669. rc = SQLITE_NOMEM;
  118670. }else{
  118671. int ii;
  118672. Fts3TokenAndCost *pTC = aTC;
  118673. Fts3Expr **ppOr = apOr;
  118674. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  118675. nToken = (int)(pTC-aTC);
  118676. nOr = (int)(ppOr-apOr);
  118677. if( rc==SQLITE_OK ){
  118678. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  118679. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  118680. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  118681. }
  118682. }
  118683. sqlite3_free(aTC);
  118684. }
  118685. }
  118686. #endif
  118687. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  118688. return rc;
  118689. }
  118690. /*
  118691. ** Invalidate the current position list for phrase pPhrase.
  118692. */
  118693. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  118694. if( pPhrase->doclist.bFreeList ){
  118695. sqlite3_free(pPhrase->doclist.pList);
  118696. }
  118697. pPhrase->doclist.pList = 0;
  118698. pPhrase->doclist.nList = 0;
  118699. pPhrase->doclist.bFreeList = 0;
  118700. }
  118701. /*
  118702. ** This function is called to edit the position list associated with
  118703. ** the phrase object passed as the fifth argument according to a NEAR
  118704. ** condition. For example:
  118705. **
  118706. ** abc NEAR/5 "def ghi"
  118707. **
  118708. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  118709. ** the example above). When this function is called, *paPoslist points to
  118710. ** the position list, and *pnToken is the number of phrase tokens in, the
  118711. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  118712. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  118713. ** the position list associated with phrase "abc".
  118714. **
  118715. ** All positions in the pPhrase position list that are not sufficiently
  118716. ** close to a position in the *paPoslist position list are removed. If this
  118717. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  118718. **
  118719. ** Before returning, *paPoslist is set to point to the position lsit
  118720. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  118721. ** pPhrase.
  118722. */
  118723. static int fts3EvalNearTrim(
  118724. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  118725. char *aTmp, /* Temporary space to use */
  118726. char **paPoslist, /* IN/OUT: Position list */
  118727. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  118728. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  118729. ){
  118730. int nParam1 = nNear + pPhrase->nToken;
  118731. int nParam2 = nNear + *pnToken;
  118732. int nNew;
  118733. char *p2;
  118734. char *pOut;
  118735. int res;
  118736. assert( pPhrase->doclist.pList );
  118737. p2 = pOut = pPhrase->doclist.pList;
  118738. res = fts3PoslistNearMerge(
  118739. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  118740. );
  118741. if( res ){
  118742. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  118743. assert( pPhrase->doclist.pList[nNew]=='\0' );
  118744. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  118745. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  118746. pPhrase->doclist.nList = nNew;
  118747. *paPoslist = pPhrase->doclist.pList;
  118748. *pnToken = pPhrase->nToken;
  118749. }
  118750. return res;
  118751. }
  118752. /*
  118753. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  118754. ** Otherwise, it advances the expression passed as the second argument to
  118755. ** point to the next matching row in the database. Expressions iterate through
  118756. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  118757. ** or descending if it is non-zero.
  118758. **
  118759. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  118760. ** successful, the following variables in pExpr are set:
  118761. **
  118762. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  118763. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  118764. **
  118765. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  118766. ** at EOF, then the following variables are populated with the position list
  118767. ** for the phrase for the visited row:
  118768. **
  118769. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  118770. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  118771. **
  118772. ** It says above that this function advances the expression to the next
  118773. ** matching row. This is usually true, but there are the following exceptions:
  118774. **
  118775. ** 1. Deferred tokens are not taken into account. If a phrase consists
  118776. ** entirely of deferred tokens, it is assumed to match every row in
  118777. ** the db. In this case the position-list is not populated at all.
  118778. **
  118779. ** Or, if a phrase contains one or more deferred tokens and one or
  118780. ** more non-deferred tokens, then the expression is advanced to the
  118781. ** next possible match, considering only non-deferred tokens. In other
  118782. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  118783. ** is advanced to the next row that contains an instance of "A * C",
  118784. ** where "*" may match any single token. The position list in this case
  118785. ** is populated as for "A * C" before returning.
  118786. **
  118787. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  118788. ** advanced to point to the next row that matches "x AND y".
  118789. **
  118790. ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
  118791. ** really a match, taking into account deferred tokens and NEAR operators.
  118792. */
  118793. static void fts3EvalNextRow(
  118794. Fts3Cursor *pCsr, /* FTS Cursor handle */
  118795. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  118796. int *pRc /* IN/OUT: Error code */
  118797. ){
  118798. if( *pRc==SQLITE_OK ){
  118799. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  118800. assert( pExpr->bEof==0 );
  118801. pExpr->bStart = 1;
  118802. switch( pExpr->eType ){
  118803. case FTSQUERY_NEAR:
  118804. case FTSQUERY_AND: {
  118805. Fts3Expr *pLeft = pExpr->pLeft;
  118806. Fts3Expr *pRight = pExpr->pRight;
  118807. assert( !pLeft->bDeferred || !pRight->bDeferred );
  118808. if( pLeft->bDeferred ){
  118809. /* LHS is entirely deferred. So we assume it matches every row.
  118810. ** Advance the RHS iterator to find the next row visited. */
  118811. fts3EvalNextRow(pCsr, pRight, pRc);
  118812. pExpr->iDocid = pRight->iDocid;
  118813. pExpr->bEof = pRight->bEof;
  118814. }else if( pRight->bDeferred ){
  118815. /* RHS is entirely deferred. So we assume it matches every row.
  118816. ** Advance the LHS iterator to find the next row visited. */
  118817. fts3EvalNextRow(pCsr, pLeft, pRc);
  118818. pExpr->iDocid = pLeft->iDocid;
  118819. pExpr->bEof = pLeft->bEof;
  118820. }else{
  118821. /* Neither the RHS or LHS are deferred. */
  118822. fts3EvalNextRow(pCsr, pLeft, pRc);
  118823. fts3EvalNextRow(pCsr, pRight, pRc);
  118824. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  118825. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  118826. if( iDiff==0 ) break;
  118827. if( iDiff<0 ){
  118828. fts3EvalNextRow(pCsr, pLeft, pRc);
  118829. }else{
  118830. fts3EvalNextRow(pCsr, pRight, pRc);
  118831. }
  118832. }
  118833. pExpr->iDocid = pLeft->iDocid;
  118834. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  118835. }
  118836. break;
  118837. }
  118838. case FTSQUERY_OR: {
  118839. Fts3Expr *pLeft = pExpr->pLeft;
  118840. Fts3Expr *pRight = pExpr->pRight;
  118841. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  118842. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  118843. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  118844. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  118845. fts3EvalNextRow(pCsr, pLeft, pRc);
  118846. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  118847. fts3EvalNextRow(pCsr, pRight, pRc);
  118848. }else{
  118849. fts3EvalNextRow(pCsr, pLeft, pRc);
  118850. fts3EvalNextRow(pCsr, pRight, pRc);
  118851. }
  118852. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  118853. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  118854. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  118855. pExpr->iDocid = pLeft->iDocid;
  118856. }else{
  118857. pExpr->iDocid = pRight->iDocid;
  118858. }
  118859. break;
  118860. }
  118861. case FTSQUERY_NOT: {
  118862. Fts3Expr *pLeft = pExpr->pLeft;
  118863. Fts3Expr *pRight = pExpr->pRight;
  118864. if( pRight->bStart==0 ){
  118865. fts3EvalNextRow(pCsr, pRight, pRc);
  118866. assert( *pRc!=SQLITE_OK || pRight->bStart );
  118867. }
  118868. fts3EvalNextRow(pCsr, pLeft, pRc);
  118869. if( pLeft->bEof==0 ){
  118870. while( !*pRc
  118871. && !pRight->bEof
  118872. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  118873. ){
  118874. fts3EvalNextRow(pCsr, pRight, pRc);
  118875. }
  118876. }
  118877. pExpr->iDocid = pLeft->iDocid;
  118878. pExpr->bEof = pLeft->bEof;
  118879. break;
  118880. }
  118881. default: {
  118882. Fts3Phrase *pPhrase = pExpr->pPhrase;
  118883. fts3EvalInvalidatePoslist(pPhrase);
  118884. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  118885. pExpr->iDocid = pPhrase->doclist.iDocid;
  118886. break;
  118887. }
  118888. }
  118889. }
  118890. }
  118891. /*
  118892. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  118893. ** cluster, then this function returns 1 immediately.
  118894. **
  118895. ** Otherwise, it checks if the current row really does match the NEAR
  118896. ** expression, using the data currently stored in the position lists
  118897. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  118898. **
  118899. ** If the current row is a match, the position list associated with each
  118900. ** phrase in the NEAR expression is edited in place to contain only those
  118901. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  118902. ** constraints. In this case it returns 1. If the NEAR expression does not
  118903. ** match the current row, 0 is returned. The position lists may or may not
  118904. ** be edited if 0 is returned.
  118905. */
  118906. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  118907. int res = 1;
  118908. /* The following block runs if pExpr is the root of a NEAR query.
  118909. ** For example, the query:
  118910. **
  118911. ** "w" NEAR "x" NEAR "y" NEAR "z"
  118912. **
  118913. ** which is represented in tree form as:
  118914. **
  118915. ** |
  118916. ** +--NEAR--+ <-- root of NEAR query
  118917. ** | |
  118918. ** +--NEAR--+ "z"
  118919. ** | |
  118920. ** +--NEAR--+ "y"
  118921. ** | |
  118922. ** "w" "x"
  118923. **
  118924. ** The right-hand child of a NEAR node is always a phrase. The
  118925. ** left-hand child may be either a phrase or a NEAR node. There are
  118926. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  118927. */
  118928. if( *pRc==SQLITE_OK
  118929. && pExpr->eType==FTSQUERY_NEAR
  118930. && pExpr->bEof==0
  118931. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  118932. ){
  118933. Fts3Expr *p;
  118934. int nTmp = 0; /* Bytes of temp space */
  118935. char *aTmp; /* Temp space for PoslistNearMerge() */
  118936. /* Allocate temporary working space. */
  118937. for(p=pExpr; p->pLeft; p=p->pLeft){
  118938. nTmp += p->pRight->pPhrase->doclist.nList;
  118939. }
  118940. nTmp += p->pPhrase->doclist.nList;
  118941. if( nTmp==0 ){
  118942. res = 0;
  118943. }else{
  118944. aTmp = sqlite3_malloc(nTmp*2);
  118945. if( !aTmp ){
  118946. *pRc = SQLITE_NOMEM;
  118947. res = 0;
  118948. }else{
  118949. char *aPoslist = p->pPhrase->doclist.pList;
  118950. int nToken = p->pPhrase->nToken;
  118951. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  118952. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  118953. int nNear = p->nNear;
  118954. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  118955. }
  118956. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  118957. nToken = pExpr->pRight->pPhrase->nToken;
  118958. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  118959. int nNear;
  118960. Fts3Phrase *pPhrase;
  118961. assert( p->pParent && p->pParent->pLeft==p );
  118962. nNear = p->pParent->nNear;
  118963. pPhrase = (
  118964. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  118965. );
  118966. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  118967. }
  118968. }
  118969. sqlite3_free(aTmp);
  118970. }
  118971. }
  118972. return res;
  118973. }
  118974. /*
  118975. ** This function is a helper function for fts3EvalTestDeferredAndNear().
  118976. ** Assuming no error occurs or has occurred, It returns non-zero if the
  118977. ** expression passed as the second argument matches the row that pCsr
  118978. ** currently points to, or zero if it does not.
  118979. **
  118980. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  118981. ** If an error occurs during execution of this function, *pRc is set to
  118982. ** the appropriate SQLite error code. In this case the returned value is
  118983. ** undefined.
  118984. */
  118985. static int fts3EvalTestExpr(
  118986. Fts3Cursor *pCsr, /* FTS cursor handle */
  118987. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  118988. int *pRc /* IN/OUT: Error code */
  118989. ){
  118990. int bHit = 1; /* Return value */
  118991. if( *pRc==SQLITE_OK ){
  118992. switch( pExpr->eType ){
  118993. case FTSQUERY_NEAR:
  118994. case FTSQUERY_AND:
  118995. bHit = (
  118996. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  118997. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  118998. && fts3EvalNearTest(pExpr, pRc)
  118999. );
  119000. /* If the NEAR expression does not match any rows, zero the doclist for
  119001. ** all phrases involved in the NEAR. This is because the snippet(),
  119002. ** offsets() and matchinfo() functions are not supposed to recognize
  119003. ** any instances of phrases that are part of unmatched NEAR queries.
  119004. ** For example if this expression:
  119005. **
  119006. ** ... MATCH 'a OR (b NEAR c)'
  119007. **
  119008. ** is matched against a row containing:
  119009. **
  119010. ** 'a b d e'
  119011. **
  119012. ** then any snippet() should ony highlight the "a" term, not the "b"
  119013. ** (as "b" is part of a non-matching NEAR clause).
  119014. */
  119015. if( bHit==0
  119016. && pExpr->eType==FTSQUERY_NEAR
  119017. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  119018. ){
  119019. Fts3Expr *p;
  119020. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  119021. if( p->pRight->iDocid==pCsr->iPrevId ){
  119022. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  119023. }
  119024. }
  119025. if( p->iDocid==pCsr->iPrevId ){
  119026. fts3EvalInvalidatePoslist(p->pPhrase);
  119027. }
  119028. }
  119029. break;
  119030. case FTSQUERY_OR: {
  119031. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  119032. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  119033. bHit = bHit1 || bHit2;
  119034. break;
  119035. }
  119036. case FTSQUERY_NOT:
  119037. bHit = (
  119038. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  119039. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  119040. );
  119041. break;
  119042. default: {
  119043. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  119044. if( pCsr->pDeferred
  119045. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  119046. ){
  119047. Fts3Phrase *pPhrase = pExpr->pPhrase;
  119048. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  119049. if( pExpr->bDeferred ){
  119050. fts3EvalInvalidatePoslist(pPhrase);
  119051. }
  119052. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  119053. bHit = (pPhrase->doclist.pList!=0);
  119054. pExpr->iDocid = pCsr->iPrevId;
  119055. }else
  119056. #endif
  119057. {
  119058. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  119059. }
  119060. break;
  119061. }
  119062. }
  119063. }
  119064. return bHit;
  119065. }
  119066. /*
  119067. ** This function is called as the second part of each xNext operation when
  119068. ** iterating through the results of a full-text query. At this point the
  119069. ** cursor points to a row that matches the query expression, with the
  119070. ** following caveats:
  119071. **
  119072. ** * Up until this point, "NEAR" operators in the expression have been
  119073. ** treated as "AND".
  119074. **
  119075. ** * Deferred tokens have not yet been considered.
  119076. **
  119077. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  119078. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  119079. ** operators and deferred tokens the current row is still a match for the
  119080. ** expression. It returns 1 if both of the following are true:
  119081. **
  119082. ** 1. *pRc is SQLITE_OK when this function returns, and
  119083. **
  119084. ** 2. After scanning the current FTS table row for the deferred tokens,
  119085. ** it is determined that the row does *not* match the query.
  119086. **
  119087. ** Or, if no error occurs and it seems the current row does match the FTS
  119088. ** query, return 0.
  119089. */
  119090. static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
  119091. int rc = *pRc;
  119092. int bMiss = 0;
  119093. if( rc==SQLITE_OK ){
  119094. /* If there are one or more deferred tokens, load the current row into
  119095. ** memory and scan it to determine the position list for each deferred
  119096. ** token. Then, see if this row is really a match, considering deferred
  119097. ** tokens and NEAR operators (neither of which were taken into account
  119098. ** earlier, by fts3EvalNextRow()).
  119099. */
  119100. if( pCsr->pDeferred ){
  119101. rc = fts3CursorSeek(0, pCsr);
  119102. if( rc==SQLITE_OK ){
  119103. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  119104. }
  119105. }
  119106. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  119107. /* Free the position-lists accumulated for each deferred token above. */
  119108. sqlite3Fts3FreeDeferredDoclists(pCsr);
  119109. *pRc = rc;
  119110. }
  119111. return (rc==SQLITE_OK && bMiss);
  119112. }
  119113. /*
  119114. ** Advance to the next document that matches the FTS expression in
  119115. ** Fts3Cursor.pExpr.
  119116. */
  119117. static int fts3EvalNext(Fts3Cursor *pCsr){
  119118. int rc = SQLITE_OK; /* Return Code */
  119119. Fts3Expr *pExpr = pCsr->pExpr;
  119120. assert( pCsr->isEof==0 );
  119121. if( pExpr==0 ){
  119122. pCsr->isEof = 1;
  119123. }else{
  119124. do {
  119125. if( pCsr->isRequireSeek==0 ){
  119126. sqlite3_reset(pCsr->pStmt);
  119127. }
  119128. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  119129. fts3EvalNextRow(pCsr, pExpr, &rc);
  119130. pCsr->isEof = pExpr->bEof;
  119131. pCsr->isRequireSeek = 1;
  119132. pCsr->isMatchinfoNeeded = 1;
  119133. pCsr->iPrevId = pExpr->iDocid;
  119134. }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
  119135. }
  119136. /* Check if the cursor is past the end of the docid range specified
  119137. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  119138. if( rc==SQLITE_OK && (
  119139. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  119140. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  119141. )){
  119142. pCsr->isEof = 1;
  119143. }
  119144. return rc;
  119145. }
  119146. /*
  119147. ** Restart interation for expression pExpr so that the next call to
  119148. ** fts3EvalNext() visits the first row. Do not allow incremental
  119149. ** loading or merging of phrase doclists for this iteration.
  119150. **
  119151. ** If *pRc is other than SQLITE_OK when this function is called, it is
  119152. ** a no-op. If an error occurs within this function, *pRc is set to an
  119153. ** SQLite error code before returning.
  119154. */
  119155. static void fts3EvalRestart(
  119156. Fts3Cursor *pCsr,
  119157. Fts3Expr *pExpr,
  119158. int *pRc
  119159. ){
  119160. if( pExpr && *pRc==SQLITE_OK ){
  119161. Fts3Phrase *pPhrase = pExpr->pPhrase;
  119162. if( pPhrase ){
  119163. fts3EvalInvalidatePoslist(pPhrase);
  119164. if( pPhrase->bIncr ){
  119165. int i;
  119166. for(i=0; i<pPhrase->nToken; i++){
  119167. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  119168. assert( pToken->pDeferred==0 );
  119169. if( pToken->pSegcsr ){
  119170. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  119171. }
  119172. }
  119173. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  119174. }
  119175. pPhrase->doclist.pNextDocid = 0;
  119176. pPhrase->doclist.iDocid = 0;
  119177. }
  119178. pExpr->iDocid = 0;
  119179. pExpr->bEof = 0;
  119180. pExpr->bStart = 0;
  119181. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  119182. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  119183. }
  119184. }
  119185. /*
  119186. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  119187. ** expression rooted at pExpr, the cursor iterates through all rows matched
  119188. ** by pExpr, calling this function for each row. This function increments
  119189. ** the values in Fts3Expr.aMI[] according to the position-list currently
  119190. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  119191. ** expression nodes.
  119192. */
  119193. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  119194. if( pExpr ){
  119195. Fts3Phrase *pPhrase = pExpr->pPhrase;
  119196. if( pPhrase && pPhrase->doclist.pList ){
  119197. int iCol = 0;
  119198. char *p = pPhrase->doclist.pList;
  119199. assert( *p );
  119200. while( 1 ){
  119201. u8 c = 0;
  119202. int iCnt = 0;
  119203. while( 0xFE & (*p | c) ){
  119204. if( (c&0x80)==0 ) iCnt++;
  119205. c = *p++ & 0x80;
  119206. }
  119207. /* aMI[iCol*3 + 1] = Number of occurrences
  119208. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  119209. */
  119210. pExpr->aMI[iCol*3 + 1] += iCnt;
  119211. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  119212. if( *p==0x00 ) break;
  119213. p++;
  119214. p += sqlite3Fts3GetVarint32(p, &iCol);
  119215. }
  119216. }
  119217. fts3EvalUpdateCounts(pExpr->pLeft);
  119218. fts3EvalUpdateCounts(pExpr->pRight);
  119219. }
  119220. }
  119221. /*
  119222. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  119223. **
  119224. ** If it is not already allocated and populated, this function allocates and
  119225. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  119226. ** of a NEAR expression, then it also allocates and populates the same array
  119227. ** for all other phrases that are part of the NEAR expression.
  119228. **
  119229. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  119230. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  119231. */
  119232. static int fts3EvalGatherStats(
  119233. Fts3Cursor *pCsr, /* Cursor object */
  119234. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  119235. ){
  119236. int rc = SQLITE_OK; /* Return code */
  119237. assert( pExpr->eType==FTSQUERY_PHRASE );
  119238. if( pExpr->aMI==0 ){
  119239. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119240. Fts3Expr *pRoot; /* Root of NEAR expression */
  119241. Fts3Expr *p; /* Iterator used for several purposes */
  119242. sqlite3_int64 iPrevId = pCsr->iPrevId;
  119243. sqlite3_int64 iDocid;
  119244. u8 bEof;
  119245. /* Find the root of the NEAR expression */
  119246. pRoot = pExpr;
  119247. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  119248. pRoot = pRoot->pParent;
  119249. }
  119250. iDocid = pRoot->iDocid;
  119251. bEof = pRoot->bEof;
  119252. assert( pRoot->bStart );
  119253. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  119254. for(p=pRoot; p; p=p->pLeft){
  119255. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  119256. assert( pE->aMI==0 );
  119257. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  119258. if( !pE->aMI ) return SQLITE_NOMEM;
  119259. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  119260. }
  119261. fts3EvalRestart(pCsr, pRoot, &rc);
  119262. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  119263. do {
  119264. /* Ensure the %_content statement is reset. */
  119265. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  119266. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  119267. /* Advance to the next document */
  119268. fts3EvalNextRow(pCsr, pRoot, &rc);
  119269. pCsr->isEof = pRoot->bEof;
  119270. pCsr->isRequireSeek = 1;
  119271. pCsr->isMatchinfoNeeded = 1;
  119272. pCsr->iPrevId = pRoot->iDocid;
  119273. }while( pCsr->isEof==0
  119274. && pRoot->eType==FTSQUERY_NEAR
  119275. && fts3EvalTestDeferredAndNear(pCsr, &rc)
  119276. );
  119277. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  119278. fts3EvalUpdateCounts(pRoot);
  119279. }
  119280. }
  119281. pCsr->isEof = 0;
  119282. pCsr->iPrevId = iPrevId;
  119283. if( bEof ){
  119284. pRoot->bEof = bEof;
  119285. }else{
  119286. /* Caution: pRoot may iterate through docids in ascending or descending
  119287. ** order. For this reason, even though it seems more defensive, the
  119288. ** do loop can not be written:
  119289. **
  119290. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  119291. */
  119292. fts3EvalRestart(pCsr, pRoot, &rc);
  119293. do {
  119294. fts3EvalNextRow(pCsr, pRoot, &rc);
  119295. assert( pRoot->bEof==0 );
  119296. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  119297. fts3EvalTestDeferredAndNear(pCsr, &rc);
  119298. }
  119299. }
  119300. return rc;
  119301. }
  119302. /*
  119303. ** This function is used by the matchinfo() module to query a phrase
  119304. ** expression node for the following information:
  119305. **
  119306. ** 1. The total number of occurrences of the phrase in each column of
  119307. ** the FTS table (considering all rows), and
  119308. **
  119309. ** 2. For each column, the number of rows in the table for which the
  119310. ** column contains at least one instance of the phrase.
  119311. **
  119312. ** If no error occurs, SQLITE_OK is returned and the values for each column
  119313. ** written into the array aiOut as follows:
  119314. **
  119315. ** aiOut[iCol*3 + 1] = Number of occurrences
  119316. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  119317. **
  119318. ** Caveats:
  119319. **
  119320. ** * If a phrase consists entirely of deferred tokens, then all output
  119321. ** values are set to the number of documents in the table. In other
  119322. ** words we assume that very common tokens occur exactly once in each
  119323. ** column of each row of the table.
  119324. **
  119325. ** * If a phrase contains some deferred tokens (and some non-deferred
  119326. ** tokens), count the potential occurrence identified by considering
  119327. ** the non-deferred tokens instead of actual phrase occurrences.
  119328. **
  119329. ** * If the phrase is part of a NEAR expression, then only phrase instances
  119330. ** that meet the NEAR constraint are included in the counts.
  119331. */
  119332. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  119333. Fts3Cursor *pCsr, /* FTS cursor handle */
  119334. Fts3Expr *pExpr, /* Phrase expression */
  119335. u32 *aiOut /* Array to write results into (see above) */
  119336. ){
  119337. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119338. int rc = SQLITE_OK;
  119339. int iCol;
  119340. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  119341. assert( pCsr->nDoc>0 );
  119342. for(iCol=0; iCol<pTab->nColumn; iCol++){
  119343. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  119344. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  119345. }
  119346. }else{
  119347. rc = fts3EvalGatherStats(pCsr, pExpr);
  119348. if( rc==SQLITE_OK ){
  119349. assert( pExpr->aMI );
  119350. for(iCol=0; iCol<pTab->nColumn; iCol++){
  119351. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  119352. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  119353. }
  119354. }
  119355. }
  119356. return rc;
  119357. }
  119358. /*
  119359. ** The expression pExpr passed as the second argument to this function
  119360. ** must be of type FTSQUERY_PHRASE.
  119361. **
  119362. ** The returned value is either NULL or a pointer to a buffer containing
  119363. ** a position-list indicating the occurrences of the phrase in column iCol
  119364. ** of the current row.
  119365. **
  119366. ** More specifically, the returned buffer contains 1 varint for each
  119367. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  119368. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  119369. ** if the requested column contains "a b X c d X X" and the position-list
  119370. ** for 'X' is requested, the buffer returned may contain:
  119371. **
  119372. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  119373. **
  119374. ** This function works regardless of whether or not the phrase is deferred,
  119375. ** incremental, or neither.
  119376. */
  119377. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  119378. Fts3Cursor *pCsr, /* FTS3 cursor object */
  119379. Fts3Expr *pExpr, /* Phrase to return doclist for */
  119380. int iCol, /* Column to return position list for */
  119381. char **ppOut /* OUT: Pointer to position list */
  119382. ){
  119383. Fts3Phrase *pPhrase = pExpr->pPhrase;
  119384. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119385. char *pIter;
  119386. int iThis;
  119387. sqlite3_int64 iDocid;
  119388. /* If this phrase is applies specifically to some column other than
  119389. ** column iCol, return a NULL pointer. */
  119390. *ppOut = 0;
  119391. assert( iCol>=0 && iCol<pTab->nColumn );
  119392. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  119393. return SQLITE_OK;
  119394. }
  119395. iDocid = pExpr->iDocid;
  119396. pIter = pPhrase->doclist.pList;
  119397. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  119398. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  119399. int iMul; /* +1 if csr dir matches index dir, else -1 */
  119400. int bOr = 0;
  119401. u8 bEof = 0;
  119402. u8 bTreeEof = 0;
  119403. Fts3Expr *p; /* Used to iterate from pExpr to root */
  119404. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  119405. /* Check if this phrase descends from an OR expression node. If not,
  119406. ** return NULL. Otherwise, the entry that corresponds to docid
  119407. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  119408. ** tree that the node is part of has been marked as EOF, but the node
  119409. ** itself is not EOF, then it may point to an earlier entry. */
  119410. pNear = pExpr;
  119411. for(p=pExpr->pParent; p; p=p->pParent){
  119412. if( p->eType==FTSQUERY_OR ) bOr = 1;
  119413. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  119414. if( p->bEof ) bTreeEof = 1;
  119415. }
  119416. if( bOr==0 ) return SQLITE_OK;
  119417. /* This is the descendent of an OR node. In this case we cannot use
  119418. ** an incremental phrase. Load the entire doclist for the phrase
  119419. ** into memory in this case. */
  119420. if( pPhrase->bIncr ){
  119421. int rc = SQLITE_OK;
  119422. int bEofSave = pExpr->bEof;
  119423. fts3EvalRestart(pCsr, pExpr, &rc);
  119424. while( rc==SQLITE_OK && !pExpr->bEof ){
  119425. fts3EvalNextRow(pCsr, pExpr, &rc);
  119426. if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
  119427. }
  119428. pIter = pPhrase->doclist.pList;
  119429. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  119430. if( rc!=SQLITE_OK ) return rc;
  119431. }
  119432. iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
  119433. while( bTreeEof==1
  119434. && pNear->bEof==0
  119435. && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
  119436. ){
  119437. int rc = SQLITE_OK;
  119438. fts3EvalNextRow(pCsr, pExpr, &rc);
  119439. if( rc!=SQLITE_OK ) return rc;
  119440. iDocid = pExpr->iDocid;
  119441. pIter = pPhrase->doclist.pList;
  119442. }
  119443. bEof = (pPhrase->doclist.nAll==0);
  119444. assert( bDescDoclist==0 || bDescDoclist==1 );
  119445. assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
  119446. if( bEof==0 ){
  119447. if( pCsr->bDesc==bDescDoclist ){
  119448. int dummy;
  119449. if( pNear->bEof ){
  119450. /* This expression is already at EOF. So position it to point to the
  119451. ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
  119452. ** iDocid is already set for this entry, so all that is required is
  119453. ** to set pIter to point to the first byte of the last position-list
  119454. ** in the doclist.
  119455. **
  119456. ** It would also be correct to set pIter and iDocid to zero. In
  119457. ** this case, the first call to sqltie3Fts4DoclistPrev() below
  119458. ** would also move the iterator to point to the last entry in the
  119459. ** doclist. However, this is expensive, as to do so it has to
  119460. ** iterate through the entire doclist from start to finish (since
  119461. ** it does not know the docid for the last entry). */
  119462. pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
  119463. fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
  119464. }
  119465. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  119466. sqlite3Fts3DoclistPrev(
  119467. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  119468. &pIter, &iDocid, &dummy, &bEof
  119469. );
  119470. }
  119471. }else{
  119472. if( pNear->bEof ){
  119473. pIter = 0;
  119474. iDocid = 0;
  119475. }
  119476. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  119477. sqlite3Fts3DoclistNext(
  119478. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  119479. &pIter, &iDocid, &bEof
  119480. );
  119481. }
  119482. }
  119483. }
  119484. if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
  119485. }
  119486. if( pIter==0 ) return SQLITE_OK;
  119487. if( *pIter==0x01 ){
  119488. pIter++;
  119489. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  119490. }else{
  119491. iThis = 0;
  119492. }
  119493. while( iThis<iCol ){
  119494. fts3ColumnlistCopy(0, &pIter);
  119495. if( *pIter==0x00 ) return 0;
  119496. pIter++;
  119497. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  119498. }
  119499. *ppOut = ((iCol==iThis)?pIter:0);
  119500. return SQLITE_OK;
  119501. }
  119502. /*
  119503. ** Free all components of the Fts3Phrase structure that were allocated by
  119504. ** the eval module. Specifically, this means to free:
  119505. **
  119506. ** * the contents of pPhrase->doclist, and
  119507. ** * any Fts3MultiSegReader objects held by phrase tokens.
  119508. */
  119509. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  119510. if( pPhrase ){
  119511. int i;
  119512. sqlite3_free(pPhrase->doclist.aAll);
  119513. fts3EvalInvalidatePoslist(pPhrase);
  119514. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  119515. for(i=0; i<pPhrase->nToken; i++){
  119516. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  119517. pPhrase->aToken[i].pSegcsr = 0;
  119518. }
  119519. }
  119520. }
  119521. /*
  119522. ** Return SQLITE_CORRUPT_VTAB.
  119523. */
  119524. #ifdef SQLITE_DEBUG
  119525. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  119526. return SQLITE_CORRUPT_VTAB;
  119527. }
  119528. #endif
  119529. #if !SQLITE_CORE
  119530. /*
  119531. ** Initialize API pointer table, if required.
  119532. */
  119533. #ifdef _WIN32
  119534. __declspec(dllexport)
  119535. #endif
  119536. SQLITE_API int sqlite3_fts3_init(
  119537. sqlite3 *db,
  119538. char **pzErrMsg,
  119539. const sqlite3_api_routines *pApi
  119540. ){
  119541. SQLITE_EXTENSION_INIT2(pApi)
  119542. return sqlite3Fts3Init(db);
  119543. }
  119544. #endif
  119545. #endif
  119546. /************** End of fts3.c ************************************************/
  119547. /************** Begin file fts3_aux.c ****************************************/
  119548. /*
  119549. ** 2011 Jan 27
  119550. **
  119551. ** The author disclaims copyright to this source code. In place of
  119552. ** a legal notice, here is a blessing:
  119553. **
  119554. ** May you do good and not evil.
  119555. ** May you find forgiveness for yourself and forgive others.
  119556. ** May you share freely, never taking more than you give.
  119557. **
  119558. ******************************************************************************
  119559. **
  119560. */
  119561. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  119562. /* #include <string.h> */
  119563. /* #include <assert.h> */
  119564. typedef struct Fts3auxTable Fts3auxTable;
  119565. typedef struct Fts3auxCursor Fts3auxCursor;
  119566. struct Fts3auxTable {
  119567. sqlite3_vtab base; /* Base class used by SQLite core */
  119568. Fts3Table *pFts3Tab;
  119569. };
  119570. struct Fts3auxCursor {
  119571. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  119572. Fts3MultiSegReader csr; /* Must be right after "base" */
  119573. Fts3SegFilter filter;
  119574. char *zStop;
  119575. int nStop; /* Byte-length of string zStop */
  119576. int iLangid; /* Language id to query */
  119577. int isEof; /* True if cursor is at EOF */
  119578. sqlite3_int64 iRowid; /* Current rowid */
  119579. int iCol; /* Current value of 'col' column */
  119580. int nStat; /* Size of aStat[] array */
  119581. struct Fts3auxColstats {
  119582. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  119583. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  119584. } *aStat;
  119585. };
  119586. /*
  119587. ** Schema of the terms table.
  119588. */
  119589. #define FTS3_AUX_SCHEMA \
  119590. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  119591. /*
  119592. ** This function does all the work for both the xConnect and xCreate methods.
  119593. ** These tables have no persistent representation of their own, so xConnect
  119594. ** and xCreate are identical operations.
  119595. */
  119596. static int fts3auxConnectMethod(
  119597. sqlite3 *db, /* Database connection */
  119598. void *pUnused, /* Unused */
  119599. int argc, /* Number of elements in argv array */
  119600. const char * const *argv, /* xCreate/xConnect argument array */
  119601. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  119602. char **pzErr /* OUT: sqlite3_malloc'd error message */
  119603. ){
  119604. char const *zDb; /* Name of database (e.g. "main") */
  119605. char const *zFts3; /* Name of fts3 table */
  119606. int nDb; /* Result of strlen(zDb) */
  119607. int nFts3; /* Result of strlen(zFts3) */
  119608. int nByte; /* Bytes of space to allocate here */
  119609. int rc; /* value returned by declare_vtab() */
  119610. Fts3auxTable *p; /* Virtual table object to return */
  119611. UNUSED_PARAMETER(pUnused);
  119612. /* The user should invoke this in one of two forms:
  119613. **
  119614. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  119615. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  119616. */
  119617. if( argc!=4 && argc!=5 ) goto bad_args;
  119618. zDb = argv[1];
  119619. nDb = (int)strlen(zDb);
  119620. if( argc==5 ){
  119621. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  119622. zDb = argv[3];
  119623. nDb = (int)strlen(zDb);
  119624. zFts3 = argv[4];
  119625. }else{
  119626. goto bad_args;
  119627. }
  119628. }else{
  119629. zFts3 = argv[3];
  119630. }
  119631. nFts3 = (int)strlen(zFts3);
  119632. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  119633. if( rc!=SQLITE_OK ) return rc;
  119634. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  119635. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  119636. if( !p ) return SQLITE_NOMEM;
  119637. memset(p, 0, nByte);
  119638. p->pFts3Tab = (Fts3Table *)&p[1];
  119639. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  119640. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  119641. p->pFts3Tab->db = db;
  119642. p->pFts3Tab->nIndex = 1;
  119643. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  119644. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  119645. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  119646. *ppVtab = (sqlite3_vtab *)p;
  119647. return SQLITE_OK;
  119648. bad_args:
  119649. *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
  119650. return SQLITE_ERROR;
  119651. }
  119652. /*
  119653. ** This function does the work for both the xDisconnect and xDestroy methods.
  119654. ** These tables have no persistent representation of their own, so xDisconnect
  119655. ** and xDestroy are identical operations.
  119656. */
  119657. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  119658. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  119659. Fts3Table *pFts3 = p->pFts3Tab;
  119660. int i;
  119661. /* Free any prepared statements held */
  119662. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  119663. sqlite3_finalize(pFts3->aStmt[i]);
  119664. }
  119665. sqlite3_free(pFts3->zSegmentsTbl);
  119666. sqlite3_free(p);
  119667. return SQLITE_OK;
  119668. }
  119669. #define FTS4AUX_EQ_CONSTRAINT 1
  119670. #define FTS4AUX_GE_CONSTRAINT 2
  119671. #define FTS4AUX_LE_CONSTRAINT 4
  119672. /*
  119673. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  119674. */
  119675. static int fts3auxBestIndexMethod(
  119676. sqlite3_vtab *pVTab,
  119677. sqlite3_index_info *pInfo
  119678. ){
  119679. int i;
  119680. int iEq = -1;
  119681. int iGe = -1;
  119682. int iLe = -1;
  119683. int iLangid = -1;
  119684. int iNext = 1; /* Next free argvIndex value */
  119685. UNUSED_PARAMETER(pVTab);
  119686. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  119687. if( pInfo->nOrderBy==1
  119688. && pInfo->aOrderBy[0].iColumn==0
  119689. && pInfo->aOrderBy[0].desc==0
  119690. ){
  119691. pInfo->orderByConsumed = 1;
  119692. }
  119693. /* Search for equality and range constraints on the "term" column.
  119694. ** And equality constraints on the hidden "languageid" column. */
  119695. for(i=0; i<pInfo->nConstraint; i++){
  119696. if( pInfo->aConstraint[i].usable ){
  119697. int op = pInfo->aConstraint[i].op;
  119698. int iCol = pInfo->aConstraint[i].iColumn;
  119699. if( iCol==0 ){
  119700. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  119701. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  119702. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  119703. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  119704. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  119705. }
  119706. if( iCol==4 ){
  119707. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  119708. }
  119709. }
  119710. }
  119711. if( iEq>=0 ){
  119712. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  119713. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  119714. pInfo->estimatedCost = 5;
  119715. }else{
  119716. pInfo->idxNum = 0;
  119717. pInfo->estimatedCost = 20000;
  119718. if( iGe>=0 ){
  119719. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  119720. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  119721. pInfo->estimatedCost /= 2;
  119722. }
  119723. if( iLe>=0 ){
  119724. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  119725. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  119726. pInfo->estimatedCost /= 2;
  119727. }
  119728. }
  119729. if( iLangid>=0 ){
  119730. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  119731. pInfo->estimatedCost--;
  119732. }
  119733. return SQLITE_OK;
  119734. }
  119735. /*
  119736. ** xOpen - Open a cursor.
  119737. */
  119738. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  119739. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  119740. UNUSED_PARAMETER(pVTab);
  119741. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  119742. if( !pCsr ) return SQLITE_NOMEM;
  119743. memset(pCsr, 0, sizeof(Fts3auxCursor));
  119744. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  119745. return SQLITE_OK;
  119746. }
  119747. /*
  119748. ** xClose - Close a cursor.
  119749. */
  119750. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  119751. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  119752. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  119753. sqlite3Fts3SegmentsClose(pFts3);
  119754. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  119755. sqlite3_free((void *)pCsr->filter.zTerm);
  119756. sqlite3_free(pCsr->zStop);
  119757. sqlite3_free(pCsr->aStat);
  119758. sqlite3_free(pCsr);
  119759. return SQLITE_OK;
  119760. }
  119761. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  119762. if( nSize>pCsr->nStat ){
  119763. struct Fts3auxColstats *aNew;
  119764. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  119765. sizeof(struct Fts3auxColstats) * nSize
  119766. );
  119767. if( aNew==0 ) return SQLITE_NOMEM;
  119768. memset(&aNew[pCsr->nStat], 0,
  119769. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  119770. );
  119771. pCsr->aStat = aNew;
  119772. pCsr->nStat = nSize;
  119773. }
  119774. return SQLITE_OK;
  119775. }
  119776. /*
  119777. ** xNext - Advance the cursor to the next row, if any.
  119778. */
  119779. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  119780. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  119781. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  119782. int rc;
  119783. /* Increment our pretend rowid value. */
  119784. pCsr->iRowid++;
  119785. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  119786. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  119787. }
  119788. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  119789. if( rc==SQLITE_ROW ){
  119790. int i = 0;
  119791. int nDoclist = pCsr->csr.nDoclist;
  119792. char *aDoclist = pCsr->csr.aDoclist;
  119793. int iCol;
  119794. int eState = 0;
  119795. if( pCsr->zStop ){
  119796. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  119797. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  119798. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  119799. pCsr->isEof = 1;
  119800. return SQLITE_OK;
  119801. }
  119802. }
  119803. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  119804. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  119805. iCol = 0;
  119806. while( i<nDoclist ){
  119807. sqlite3_int64 v = 0;
  119808. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  119809. switch( eState ){
  119810. /* State 0. In this state the integer just read was a docid. */
  119811. case 0:
  119812. pCsr->aStat[0].nDoc++;
  119813. eState = 1;
  119814. iCol = 0;
  119815. break;
  119816. /* State 1. In this state we are expecting either a 1, indicating
  119817. ** that the following integer will be a column number, or the
  119818. ** start of a position list for column 0.
  119819. **
  119820. ** The only difference between state 1 and state 2 is that if the
  119821. ** integer encountered in state 1 is not 0 or 1, then we need to
  119822. ** increment the column 0 "nDoc" count for this term.
  119823. */
  119824. case 1:
  119825. assert( iCol==0 );
  119826. if( v>1 ){
  119827. pCsr->aStat[1].nDoc++;
  119828. }
  119829. eState = 2;
  119830. /* fall through */
  119831. case 2:
  119832. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  119833. eState = 0;
  119834. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  119835. eState = 3;
  119836. }else{ /* 2 or greater. A position. */
  119837. pCsr->aStat[iCol+1].nOcc++;
  119838. pCsr->aStat[0].nOcc++;
  119839. }
  119840. break;
  119841. /* State 3. The integer just read is a column number. */
  119842. default: assert( eState==3 );
  119843. iCol = (int)v;
  119844. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  119845. pCsr->aStat[iCol+1].nDoc++;
  119846. eState = 2;
  119847. break;
  119848. }
  119849. }
  119850. pCsr->iCol = 0;
  119851. rc = SQLITE_OK;
  119852. }else{
  119853. pCsr->isEof = 1;
  119854. }
  119855. return rc;
  119856. }
  119857. /*
  119858. ** xFilter - Initialize a cursor to point at the start of its data.
  119859. */
  119860. static int fts3auxFilterMethod(
  119861. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  119862. int idxNum, /* Strategy index */
  119863. const char *idxStr, /* Unused */
  119864. int nVal, /* Number of elements in apVal */
  119865. sqlite3_value **apVal /* Arguments for the indexing scheme */
  119866. ){
  119867. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  119868. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  119869. int rc;
  119870. int isScan = 0;
  119871. int iLangVal = 0; /* Language id to query */
  119872. int iEq = -1; /* Index of term=? value in apVal */
  119873. int iGe = -1; /* Index of term>=? value in apVal */
  119874. int iLe = -1; /* Index of term<=? value in apVal */
  119875. int iLangid = -1; /* Index of languageid=? value in apVal */
  119876. int iNext = 0;
  119877. UNUSED_PARAMETER(nVal);
  119878. UNUSED_PARAMETER(idxStr);
  119879. assert( idxStr==0 );
  119880. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  119881. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  119882. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  119883. );
  119884. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  119885. iEq = iNext++;
  119886. }else{
  119887. isScan = 1;
  119888. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  119889. iGe = iNext++;
  119890. }
  119891. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  119892. iLe = iNext++;
  119893. }
  119894. }
  119895. if( iNext<nVal ){
  119896. iLangid = iNext++;
  119897. }
  119898. /* In case this cursor is being reused, close and zero it. */
  119899. testcase(pCsr->filter.zTerm);
  119900. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  119901. sqlite3_free((void *)pCsr->filter.zTerm);
  119902. sqlite3_free(pCsr->aStat);
  119903. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  119904. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  119905. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  119906. if( iEq>=0 || iGe>=0 ){
  119907. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  119908. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  119909. if( zStr ){
  119910. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  119911. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  119912. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  119913. }
  119914. }
  119915. if( iLe>=0 ){
  119916. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  119917. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  119918. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  119919. }
  119920. if( iLangid>=0 ){
  119921. iLangVal = sqlite3_value_int(apVal[iLangid]);
  119922. /* If the user specified a negative value for the languageid, use zero
  119923. ** instead. This works, as the "languageid=?" constraint will also
  119924. ** be tested by the VDBE layer. The test will always be false (since
  119925. ** this module will not return a row with a negative languageid), and
  119926. ** so the overall query will return zero rows. */
  119927. if( iLangVal<0 ) iLangVal = 0;
  119928. }
  119929. pCsr->iLangid = iLangVal;
  119930. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  119931. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  119932. );
  119933. if( rc==SQLITE_OK ){
  119934. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  119935. }
  119936. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  119937. return rc;
  119938. }
  119939. /*
  119940. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  119941. */
  119942. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  119943. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  119944. return pCsr->isEof;
  119945. }
  119946. /*
  119947. ** xColumn - Return a column value.
  119948. */
  119949. static int fts3auxColumnMethod(
  119950. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  119951. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  119952. int iCol /* Index of column to read value from */
  119953. ){
  119954. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  119955. assert( p->isEof==0 );
  119956. switch( iCol ){
  119957. case 0: /* term */
  119958. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  119959. break;
  119960. case 1: /* col */
  119961. if( p->iCol ){
  119962. sqlite3_result_int(pCtx, p->iCol-1);
  119963. }else{
  119964. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  119965. }
  119966. break;
  119967. case 2: /* documents */
  119968. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  119969. break;
  119970. case 3: /* occurrences */
  119971. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  119972. break;
  119973. default: /* languageid */
  119974. assert( iCol==4 );
  119975. sqlite3_result_int(pCtx, p->iLangid);
  119976. break;
  119977. }
  119978. return SQLITE_OK;
  119979. }
  119980. /*
  119981. ** xRowid - Return the current rowid for the cursor.
  119982. */
  119983. static int fts3auxRowidMethod(
  119984. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  119985. sqlite_int64 *pRowid /* OUT: Rowid value */
  119986. ){
  119987. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  119988. *pRowid = pCsr->iRowid;
  119989. return SQLITE_OK;
  119990. }
  119991. /*
  119992. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  119993. ** if successful or an error code if sqlite3_create_module() fails.
  119994. */
  119995. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  119996. static const sqlite3_module fts3aux_module = {
  119997. 0, /* iVersion */
  119998. fts3auxConnectMethod, /* xCreate */
  119999. fts3auxConnectMethod, /* xConnect */
  120000. fts3auxBestIndexMethod, /* xBestIndex */
  120001. fts3auxDisconnectMethod, /* xDisconnect */
  120002. fts3auxDisconnectMethod, /* xDestroy */
  120003. fts3auxOpenMethod, /* xOpen */
  120004. fts3auxCloseMethod, /* xClose */
  120005. fts3auxFilterMethod, /* xFilter */
  120006. fts3auxNextMethod, /* xNext */
  120007. fts3auxEofMethod, /* xEof */
  120008. fts3auxColumnMethod, /* xColumn */
  120009. fts3auxRowidMethod, /* xRowid */
  120010. 0, /* xUpdate */
  120011. 0, /* xBegin */
  120012. 0, /* xSync */
  120013. 0, /* xCommit */
  120014. 0, /* xRollback */
  120015. 0, /* xFindFunction */
  120016. 0, /* xRename */
  120017. 0, /* xSavepoint */
  120018. 0, /* xRelease */
  120019. 0 /* xRollbackTo */
  120020. };
  120021. int rc; /* Return code */
  120022. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  120023. return rc;
  120024. }
  120025. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  120026. /************** End of fts3_aux.c ********************************************/
  120027. /************** Begin file fts3_expr.c ***************************************/
  120028. /*
  120029. ** 2008 Nov 28
  120030. **
  120031. ** The author disclaims copyright to this source code. In place of
  120032. ** a legal notice, here is a blessing:
  120033. **
  120034. ** May you do good and not evil.
  120035. ** May you find forgiveness for yourself and forgive others.
  120036. ** May you share freely, never taking more than you give.
  120037. **
  120038. ******************************************************************************
  120039. **
  120040. ** This module contains code that implements a parser for fts3 query strings
  120041. ** (the right-hand argument to the MATCH operator). Because the supported
  120042. ** syntax is relatively simple, the whole tokenizer/parser system is
  120043. ** hand-coded.
  120044. */
  120045. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  120046. /*
  120047. ** By default, this module parses the legacy syntax that has been
  120048. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  120049. ** is defined, then it uses the new syntax. The differences between
  120050. ** the new and the old syntaxes are:
  120051. **
  120052. ** a) The new syntax supports parenthesis. The old does not.
  120053. **
  120054. ** b) The new syntax supports the AND and NOT operators. The old does not.
  120055. **
  120056. ** c) The old syntax supports the "-" token qualifier. This is not
  120057. ** supported by the new syntax (it is replaced by the NOT operator).
  120058. **
  120059. ** d) When using the old syntax, the OR operator has a greater precedence
  120060. ** than an implicit AND. When using the new, both implicity and explicit
  120061. ** AND operators have a higher precedence than OR.
  120062. **
  120063. ** If compiled with SQLITE_TEST defined, then this module exports the
  120064. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  120065. ** to zero causes the module to use the old syntax. If it is set to
  120066. ** non-zero the new syntax is activated. This is so both syntaxes can
  120067. ** be tested using a single build of testfixture.
  120068. **
  120069. ** The following describes the syntax supported by the fts3 MATCH
  120070. ** operator in a similar format to that used by the lemon parser
  120071. ** generator. This module does not use actually lemon, it uses a
  120072. ** custom parser.
  120073. **
  120074. ** query ::= andexpr (OR andexpr)*.
  120075. **
  120076. ** andexpr ::= notexpr (AND? notexpr)*.
  120077. **
  120078. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  120079. ** notexpr ::= LP query RP.
  120080. **
  120081. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  120082. **
  120083. ** distance_opt ::= .
  120084. ** distance_opt ::= / INTEGER.
  120085. **
  120086. ** phrase ::= TOKEN.
  120087. ** phrase ::= COLUMN:TOKEN.
  120088. ** phrase ::= "TOKEN TOKEN TOKEN...".
  120089. */
  120090. #ifdef SQLITE_TEST
  120091. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  120092. #else
  120093. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  120094. # define sqlite3_fts3_enable_parentheses 1
  120095. # else
  120096. # define sqlite3_fts3_enable_parentheses 0
  120097. # endif
  120098. #endif
  120099. /*
  120100. ** Default span for NEAR operators.
  120101. */
  120102. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  120103. /* #include <string.h> */
  120104. /* #include <assert.h> */
  120105. /*
  120106. ** isNot:
  120107. ** This variable is used by function getNextNode(). When getNextNode() is
  120108. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  120109. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  120110. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  120111. ** zero.
  120112. */
  120113. typedef struct ParseContext ParseContext;
  120114. struct ParseContext {
  120115. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  120116. int iLangid; /* Language id used with tokenizer */
  120117. const char **azCol; /* Array of column names for fts3 table */
  120118. int bFts4; /* True to allow FTS4-only syntax */
  120119. int nCol; /* Number of entries in azCol[] */
  120120. int iDefaultCol; /* Default column to query */
  120121. int isNot; /* True if getNextNode() sees a unary - */
  120122. sqlite3_context *pCtx; /* Write error message here */
  120123. int nNest; /* Number of nested brackets */
  120124. };
  120125. /*
  120126. ** This function is equivalent to the standard isspace() function.
  120127. **
  120128. ** The standard isspace() can be awkward to use safely, because although it
  120129. ** is defined to accept an argument of type int, its behavior when passed
  120130. ** an integer that falls outside of the range of the unsigned char type
  120131. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  120132. ** is defined to accept an argument of type char, and always returns 0 for
  120133. ** any values that fall outside of the range of the unsigned char type (i.e.
  120134. ** negative values).
  120135. */
  120136. static int fts3isspace(char c){
  120137. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  120138. }
  120139. /*
  120140. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  120141. ** zero the memory before returning a pointer to it. If unsuccessful,
  120142. ** return NULL.
  120143. */
  120144. static void *fts3MallocZero(int nByte){
  120145. void *pRet = sqlite3_malloc(nByte);
  120146. if( pRet ) memset(pRet, 0, nByte);
  120147. return pRet;
  120148. }
  120149. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  120150. sqlite3_tokenizer *pTokenizer,
  120151. int iLangid,
  120152. const char *z,
  120153. int n,
  120154. sqlite3_tokenizer_cursor **ppCsr
  120155. ){
  120156. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  120157. sqlite3_tokenizer_cursor *pCsr = 0;
  120158. int rc;
  120159. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  120160. assert( rc==SQLITE_OK || pCsr==0 );
  120161. if( rc==SQLITE_OK ){
  120162. pCsr->pTokenizer = pTokenizer;
  120163. if( pModule->iVersion>=1 ){
  120164. rc = pModule->xLanguageid(pCsr, iLangid);
  120165. if( rc!=SQLITE_OK ){
  120166. pModule->xClose(pCsr);
  120167. pCsr = 0;
  120168. }
  120169. }
  120170. }
  120171. *ppCsr = pCsr;
  120172. return rc;
  120173. }
  120174. /*
  120175. ** Extract the next token from buffer z (length n) using the tokenizer
  120176. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  120177. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  120178. ** single token and set *ppExpr to point to it. If the end of the buffer is
  120179. ** reached before a token is found, set *ppExpr to zero. It is the
  120180. ** responsibility of the caller to eventually deallocate the allocated
  120181. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  120182. **
  120183. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  120184. ** fails.
  120185. */
  120186. static int getNextToken(
  120187. ParseContext *pParse, /* fts3 query parse context */
  120188. int iCol, /* Value for Fts3Phrase.iColumn */
  120189. const char *z, int n, /* Input string */
  120190. Fts3Expr **ppExpr, /* OUT: expression */
  120191. int *pnConsumed /* OUT: Number of bytes consumed */
  120192. ){
  120193. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  120194. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  120195. int rc;
  120196. sqlite3_tokenizer_cursor *pCursor;
  120197. Fts3Expr *pRet = 0;
  120198. int nConsumed = 0;
  120199. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
  120200. if( rc==SQLITE_OK ){
  120201. const char *zToken;
  120202. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  120203. int nByte; /* total space to allocate */
  120204. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  120205. if( rc==SQLITE_OK ){
  120206. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  120207. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  120208. if( !pRet ){
  120209. rc = SQLITE_NOMEM;
  120210. }else{
  120211. pRet->eType = FTSQUERY_PHRASE;
  120212. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  120213. pRet->pPhrase->nToken = 1;
  120214. pRet->pPhrase->iColumn = iCol;
  120215. pRet->pPhrase->aToken[0].n = nToken;
  120216. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  120217. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  120218. if( iEnd<n && z[iEnd]=='*' ){
  120219. pRet->pPhrase->aToken[0].isPrefix = 1;
  120220. iEnd++;
  120221. }
  120222. while( 1 ){
  120223. if( !sqlite3_fts3_enable_parentheses
  120224. && iStart>0 && z[iStart-1]=='-'
  120225. ){
  120226. pParse->isNot = 1;
  120227. iStart--;
  120228. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  120229. pRet->pPhrase->aToken[0].bFirst = 1;
  120230. iStart--;
  120231. }else{
  120232. break;
  120233. }
  120234. }
  120235. }
  120236. nConsumed = iEnd;
  120237. }
  120238. pModule->xClose(pCursor);
  120239. }
  120240. *pnConsumed = nConsumed;
  120241. *ppExpr = pRet;
  120242. return rc;
  120243. }
  120244. /*
  120245. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  120246. ** then free the old allocation.
  120247. */
  120248. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  120249. void *pRet = sqlite3_realloc(pOrig, nNew);
  120250. if( !pRet ){
  120251. sqlite3_free(pOrig);
  120252. }
  120253. return pRet;
  120254. }
  120255. /*
  120256. ** Buffer zInput, length nInput, contains the contents of a quoted string
  120257. ** that appeared as part of an fts3 query expression. Neither quote character
  120258. ** is included in the buffer. This function attempts to tokenize the entire
  120259. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  120260. ** containing the results.
  120261. **
  120262. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  120263. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  120264. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  120265. ** to 0.
  120266. */
  120267. static int getNextString(
  120268. ParseContext *pParse, /* fts3 query parse context */
  120269. const char *zInput, int nInput, /* Input string */
  120270. Fts3Expr **ppExpr /* OUT: expression */
  120271. ){
  120272. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  120273. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  120274. int rc;
  120275. Fts3Expr *p = 0;
  120276. sqlite3_tokenizer_cursor *pCursor = 0;
  120277. char *zTemp = 0;
  120278. int nTemp = 0;
  120279. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  120280. int nToken = 0;
  120281. /* The final Fts3Expr data structure, including the Fts3Phrase,
  120282. ** Fts3PhraseToken structures token buffers are all stored as a single
  120283. ** allocation so that the expression can be freed with a single call to
  120284. ** sqlite3_free(). Setting this up requires a two pass approach.
  120285. **
  120286. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  120287. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  120288. ** to assemble data in two dynamic buffers:
  120289. **
  120290. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  120291. ** structure, followed by the array of Fts3PhraseToken
  120292. ** structures. This pass only populates the Fts3PhraseToken array.
  120293. **
  120294. ** Buffer zTemp: Contains copies of all tokens.
  120295. **
  120296. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  120297. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  120298. ** structures.
  120299. */
  120300. rc = sqlite3Fts3OpenTokenizer(
  120301. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  120302. if( rc==SQLITE_OK ){
  120303. int ii;
  120304. for(ii=0; rc==SQLITE_OK; ii++){
  120305. const char *zByte;
  120306. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  120307. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  120308. if( rc==SQLITE_OK ){
  120309. Fts3PhraseToken *pToken;
  120310. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  120311. if( !p ) goto no_mem;
  120312. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  120313. if( !zTemp ) goto no_mem;
  120314. assert( nToken==ii );
  120315. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  120316. memset(pToken, 0, sizeof(Fts3PhraseToken));
  120317. memcpy(&zTemp[nTemp], zByte, nByte);
  120318. nTemp += nByte;
  120319. pToken->n = nByte;
  120320. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  120321. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  120322. nToken = ii+1;
  120323. }
  120324. }
  120325. pModule->xClose(pCursor);
  120326. pCursor = 0;
  120327. }
  120328. if( rc==SQLITE_DONE ){
  120329. int jj;
  120330. char *zBuf = 0;
  120331. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  120332. if( !p ) goto no_mem;
  120333. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  120334. p->eType = FTSQUERY_PHRASE;
  120335. p->pPhrase = (Fts3Phrase *)&p[1];
  120336. p->pPhrase->iColumn = pParse->iDefaultCol;
  120337. p->pPhrase->nToken = nToken;
  120338. zBuf = (char *)&p->pPhrase->aToken[nToken];
  120339. if( zTemp ){
  120340. memcpy(zBuf, zTemp, nTemp);
  120341. sqlite3_free(zTemp);
  120342. }else{
  120343. assert( nTemp==0 );
  120344. }
  120345. for(jj=0; jj<p->pPhrase->nToken; jj++){
  120346. p->pPhrase->aToken[jj].z = zBuf;
  120347. zBuf += p->pPhrase->aToken[jj].n;
  120348. }
  120349. rc = SQLITE_OK;
  120350. }
  120351. *ppExpr = p;
  120352. return rc;
  120353. no_mem:
  120354. if( pCursor ){
  120355. pModule->xClose(pCursor);
  120356. }
  120357. sqlite3_free(zTemp);
  120358. sqlite3_free(p);
  120359. *ppExpr = 0;
  120360. return SQLITE_NOMEM;
  120361. }
  120362. /*
  120363. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  120364. ** call fts3ExprParse(). So this forward declaration is required.
  120365. */
  120366. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  120367. /*
  120368. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  120369. ** structure, or set to 0 if the end of the input buffer is reached.
  120370. **
  120371. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  120372. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  120373. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  120374. */
  120375. static int getNextNode(
  120376. ParseContext *pParse, /* fts3 query parse context */
  120377. const char *z, int n, /* Input string */
  120378. Fts3Expr **ppExpr, /* OUT: expression */
  120379. int *pnConsumed /* OUT: Number of bytes consumed */
  120380. ){
  120381. static const struct Fts3Keyword {
  120382. char *z; /* Keyword text */
  120383. unsigned char n; /* Length of the keyword */
  120384. unsigned char parenOnly; /* Only valid in paren mode */
  120385. unsigned char eType; /* Keyword code */
  120386. } aKeyword[] = {
  120387. { "OR" , 2, 0, FTSQUERY_OR },
  120388. { "AND", 3, 1, FTSQUERY_AND },
  120389. { "NOT", 3, 1, FTSQUERY_NOT },
  120390. { "NEAR", 4, 0, FTSQUERY_NEAR }
  120391. };
  120392. int ii;
  120393. int iCol;
  120394. int iColLen;
  120395. int rc;
  120396. Fts3Expr *pRet = 0;
  120397. const char *zInput = z;
  120398. int nInput = n;
  120399. pParse->isNot = 0;
  120400. /* Skip over any whitespace before checking for a keyword, an open or
  120401. ** close bracket, or a quoted string.
  120402. */
  120403. while( nInput>0 && fts3isspace(*zInput) ){
  120404. nInput--;
  120405. zInput++;
  120406. }
  120407. if( nInput==0 ){
  120408. return SQLITE_DONE;
  120409. }
  120410. /* See if we are dealing with a keyword. */
  120411. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  120412. const struct Fts3Keyword *pKey = &aKeyword[ii];
  120413. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  120414. continue;
  120415. }
  120416. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  120417. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  120418. int nKey = pKey->n;
  120419. char cNext;
  120420. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  120421. if( pKey->eType==FTSQUERY_NEAR ){
  120422. assert( nKey==4 );
  120423. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  120424. nNear = 0;
  120425. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  120426. nNear = nNear * 10 + (zInput[nKey] - '0');
  120427. }
  120428. }
  120429. }
  120430. /* At this point this is probably a keyword. But for that to be true,
  120431. ** the next byte must contain either whitespace, an open or close
  120432. ** parenthesis, a quote character, or EOF.
  120433. */
  120434. cNext = zInput[nKey];
  120435. if( fts3isspace(cNext)
  120436. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  120437. ){
  120438. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  120439. if( !pRet ){
  120440. return SQLITE_NOMEM;
  120441. }
  120442. pRet->eType = pKey->eType;
  120443. pRet->nNear = nNear;
  120444. *ppExpr = pRet;
  120445. *pnConsumed = (int)((zInput - z) + nKey);
  120446. return SQLITE_OK;
  120447. }
  120448. /* Turns out that wasn't a keyword after all. This happens if the
  120449. ** user has supplied a token such as "ORacle". Continue.
  120450. */
  120451. }
  120452. }
  120453. /* Check for an open bracket. */
  120454. if( sqlite3_fts3_enable_parentheses ){
  120455. if( *zInput=='(' ){
  120456. int nConsumed;
  120457. pParse->nNest++;
  120458. rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
  120459. if( rc==SQLITE_OK && !*ppExpr ){
  120460. rc = SQLITE_DONE;
  120461. }
  120462. *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
  120463. return rc;
  120464. }
  120465. /* Check for a close bracket. */
  120466. if( *zInput==')' ){
  120467. pParse->nNest--;
  120468. *pnConsumed = (int)((zInput - z) + 1);
  120469. return SQLITE_DONE;
  120470. }
  120471. }
  120472. /* See if we are dealing with a quoted phrase. If this is the case, then
  120473. ** search for the closing quote and pass the whole string to getNextString()
  120474. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  120475. ** a quote character embedded in a string.
  120476. */
  120477. if( *zInput=='"' ){
  120478. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  120479. *pnConsumed = (int)((zInput - z) + ii + 1);
  120480. if( ii==nInput ){
  120481. return SQLITE_ERROR;
  120482. }
  120483. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  120484. }
  120485. /* If control flows to this point, this must be a regular token, or
  120486. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  120487. ** interface. Before doing so, figure out if there is an explicit
  120488. ** column specifier for the token.
  120489. **
  120490. ** TODO: Strangely, it is not possible to associate a column specifier
  120491. ** with a quoted phrase, only with a single token. Not sure if this was
  120492. ** an implementation artifact or an intentional decision when fts3 was
  120493. ** first implemented. Whichever it was, this module duplicates the
  120494. ** limitation.
  120495. */
  120496. iCol = pParse->iDefaultCol;
  120497. iColLen = 0;
  120498. for(ii=0; ii<pParse->nCol; ii++){
  120499. const char *zStr = pParse->azCol[ii];
  120500. int nStr = (int)strlen(zStr);
  120501. if( nInput>nStr && zInput[nStr]==':'
  120502. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  120503. ){
  120504. iCol = ii;
  120505. iColLen = (int)((zInput - z) + nStr + 1);
  120506. break;
  120507. }
  120508. }
  120509. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  120510. *pnConsumed += iColLen;
  120511. return rc;
  120512. }
  120513. /*
  120514. ** The argument is an Fts3Expr structure for a binary operator (any type
  120515. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  120516. ** precedence of the operator. Lower values have a higher precedence (i.e.
  120517. ** group more tightly). For example, in the C language, the == operator
  120518. ** groups more tightly than ||, and would therefore have a higher precedence.
  120519. **
  120520. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  120521. ** is defined), the order of the operators in precedence from highest to
  120522. ** lowest is:
  120523. **
  120524. ** NEAR
  120525. ** NOT
  120526. ** AND (including implicit ANDs)
  120527. ** OR
  120528. **
  120529. ** Note that when using the old query syntax, the OR operator has a higher
  120530. ** precedence than the AND operator.
  120531. */
  120532. static int opPrecedence(Fts3Expr *p){
  120533. assert( p->eType!=FTSQUERY_PHRASE );
  120534. if( sqlite3_fts3_enable_parentheses ){
  120535. return p->eType;
  120536. }else if( p->eType==FTSQUERY_NEAR ){
  120537. return 1;
  120538. }else if( p->eType==FTSQUERY_OR ){
  120539. return 2;
  120540. }
  120541. assert( p->eType==FTSQUERY_AND );
  120542. return 3;
  120543. }
  120544. /*
  120545. ** Argument ppHead contains a pointer to the current head of a query
  120546. ** expression tree being parsed. pPrev is the expression node most recently
  120547. ** inserted into the tree. This function adds pNew, which is always a binary
  120548. ** operator node, into the expression tree based on the relative precedence
  120549. ** of pNew and the existing nodes of the tree. This may result in the head
  120550. ** of the tree changing, in which case *ppHead is set to the new root node.
  120551. */
  120552. static void insertBinaryOperator(
  120553. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  120554. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  120555. Fts3Expr *pNew /* New binary node to insert into expression tree */
  120556. ){
  120557. Fts3Expr *pSplit = pPrev;
  120558. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  120559. pSplit = pSplit->pParent;
  120560. }
  120561. if( pSplit->pParent ){
  120562. assert( pSplit->pParent->pRight==pSplit );
  120563. pSplit->pParent->pRight = pNew;
  120564. pNew->pParent = pSplit->pParent;
  120565. }else{
  120566. *ppHead = pNew;
  120567. }
  120568. pNew->pLeft = pSplit;
  120569. pSplit->pParent = pNew;
  120570. }
  120571. /*
  120572. ** Parse the fts3 query expression found in buffer z, length n. This function
  120573. ** returns either when the end of the buffer is reached or an unmatched
  120574. ** closing bracket - ')' - is encountered.
  120575. **
  120576. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  120577. ** parsed form of the expression and *pnConsumed is set to the number of
  120578. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  120579. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  120580. */
  120581. static int fts3ExprParse(
  120582. ParseContext *pParse, /* fts3 query parse context */
  120583. const char *z, int n, /* Text of MATCH query */
  120584. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  120585. int *pnConsumed /* OUT: Number of bytes consumed */
  120586. ){
  120587. Fts3Expr *pRet = 0;
  120588. Fts3Expr *pPrev = 0;
  120589. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  120590. int nIn = n;
  120591. const char *zIn = z;
  120592. int rc = SQLITE_OK;
  120593. int isRequirePhrase = 1;
  120594. while( rc==SQLITE_OK ){
  120595. Fts3Expr *p = 0;
  120596. int nByte = 0;
  120597. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  120598. if( rc==SQLITE_OK ){
  120599. int isPhrase;
  120600. if( !sqlite3_fts3_enable_parentheses
  120601. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  120602. ){
  120603. /* Create an implicit NOT operator. */
  120604. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  120605. if( !pNot ){
  120606. sqlite3Fts3ExprFree(p);
  120607. rc = SQLITE_NOMEM;
  120608. goto exprparse_out;
  120609. }
  120610. pNot->eType = FTSQUERY_NOT;
  120611. pNot->pRight = p;
  120612. p->pParent = pNot;
  120613. if( pNotBranch ){
  120614. pNot->pLeft = pNotBranch;
  120615. pNotBranch->pParent = pNot;
  120616. }
  120617. pNotBranch = pNot;
  120618. p = pPrev;
  120619. }else{
  120620. int eType = p->eType;
  120621. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  120622. /* The isRequirePhrase variable is set to true if a phrase or
  120623. ** an expression contained in parenthesis is required. If a
  120624. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  120625. ** isRequirePhrase is set, this is a syntax error.
  120626. */
  120627. if( !isPhrase && isRequirePhrase ){
  120628. sqlite3Fts3ExprFree(p);
  120629. rc = SQLITE_ERROR;
  120630. goto exprparse_out;
  120631. }
  120632. if( isPhrase && !isRequirePhrase ){
  120633. /* Insert an implicit AND operator. */
  120634. Fts3Expr *pAnd;
  120635. assert( pRet && pPrev );
  120636. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  120637. if( !pAnd ){
  120638. sqlite3Fts3ExprFree(p);
  120639. rc = SQLITE_NOMEM;
  120640. goto exprparse_out;
  120641. }
  120642. pAnd->eType = FTSQUERY_AND;
  120643. insertBinaryOperator(&pRet, pPrev, pAnd);
  120644. pPrev = pAnd;
  120645. }
  120646. /* This test catches attempts to make either operand of a NEAR
  120647. ** operator something other than a phrase. For example, either of
  120648. ** the following:
  120649. **
  120650. ** (bracketed expression) NEAR phrase
  120651. ** phrase NEAR (bracketed expression)
  120652. **
  120653. ** Return an error in either case.
  120654. */
  120655. if( pPrev && (
  120656. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  120657. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  120658. )){
  120659. sqlite3Fts3ExprFree(p);
  120660. rc = SQLITE_ERROR;
  120661. goto exprparse_out;
  120662. }
  120663. if( isPhrase ){
  120664. if( pRet ){
  120665. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  120666. pPrev->pRight = p;
  120667. p->pParent = pPrev;
  120668. }else{
  120669. pRet = p;
  120670. }
  120671. }else{
  120672. insertBinaryOperator(&pRet, pPrev, p);
  120673. }
  120674. isRequirePhrase = !isPhrase;
  120675. }
  120676. assert( nByte>0 );
  120677. }
  120678. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  120679. nIn -= nByte;
  120680. zIn += nByte;
  120681. pPrev = p;
  120682. }
  120683. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  120684. rc = SQLITE_ERROR;
  120685. }
  120686. if( rc==SQLITE_DONE ){
  120687. rc = SQLITE_OK;
  120688. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  120689. if( !pRet ){
  120690. rc = SQLITE_ERROR;
  120691. }else{
  120692. Fts3Expr *pIter = pNotBranch;
  120693. while( pIter->pLeft ){
  120694. pIter = pIter->pLeft;
  120695. }
  120696. pIter->pLeft = pRet;
  120697. pRet->pParent = pIter;
  120698. pRet = pNotBranch;
  120699. }
  120700. }
  120701. }
  120702. *pnConsumed = n - nIn;
  120703. exprparse_out:
  120704. if( rc!=SQLITE_OK ){
  120705. sqlite3Fts3ExprFree(pRet);
  120706. sqlite3Fts3ExprFree(pNotBranch);
  120707. pRet = 0;
  120708. }
  120709. *ppExpr = pRet;
  120710. return rc;
  120711. }
  120712. /*
  120713. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  120714. ** as the only argument is more than nMaxDepth.
  120715. */
  120716. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  120717. int rc = SQLITE_OK;
  120718. if( p ){
  120719. if( nMaxDepth<0 ){
  120720. rc = SQLITE_TOOBIG;
  120721. }else{
  120722. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  120723. if( rc==SQLITE_OK ){
  120724. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  120725. }
  120726. }
  120727. }
  120728. return rc;
  120729. }
  120730. /*
  120731. ** This function attempts to transform the expression tree at (*pp) to
  120732. ** an equivalent but more balanced form. The tree is modified in place.
  120733. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  120734. ** new root expression node.
  120735. **
  120736. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  120737. **
  120738. ** Otherwise, if an error occurs, an SQLite error code is returned and
  120739. ** expression (*pp) freed.
  120740. */
  120741. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  120742. int rc = SQLITE_OK; /* Return code */
  120743. Fts3Expr *pRoot = *pp; /* Initial root node */
  120744. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  120745. int eType = pRoot->eType; /* Type of node in this tree */
  120746. if( nMaxDepth==0 ){
  120747. rc = SQLITE_ERROR;
  120748. }
  120749. if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  120750. Fts3Expr **apLeaf;
  120751. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  120752. if( 0==apLeaf ){
  120753. rc = SQLITE_NOMEM;
  120754. }else{
  120755. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  120756. }
  120757. if( rc==SQLITE_OK ){
  120758. int i;
  120759. Fts3Expr *p;
  120760. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  120761. for(p=pRoot; p->eType==eType; p=p->pLeft){
  120762. assert( p->pParent==0 || p->pParent->pLeft==p );
  120763. assert( p->pLeft && p->pRight );
  120764. }
  120765. /* This loop runs once for each leaf in the tree of eType nodes. */
  120766. while( 1 ){
  120767. int iLvl;
  120768. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  120769. assert( pParent==0 || pParent->pLeft==p );
  120770. p->pParent = 0;
  120771. if( pParent ){
  120772. pParent->pLeft = 0;
  120773. }else{
  120774. pRoot = 0;
  120775. }
  120776. rc = fts3ExprBalance(&p, nMaxDepth-1);
  120777. if( rc!=SQLITE_OK ) break;
  120778. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  120779. if( apLeaf[iLvl]==0 ){
  120780. apLeaf[iLvl] = p;
  120781. p = 0;
  120782. }else{
  120783. assert( pFree );
  120784. pFree->pLeft = apLeaf[iLvl];
  120785. pFree->pRight = p;
  120786. pFree->pLeft->pParent = pFree;
  120787. pFree->pRight->pParent = pFree;
  120788. p = pFree;
  120789. pFree = pFree->pParent;
  120790. p->pParent = 0;
  120791. apLeaf[iLvl] = 0;
  120792. }
  120793. }
  120794. if( p ){
  120795. sqlite3Fts3ExprFree(p);
  120796. rc = SQLITE_TOOBIG;
  120797. break;
  120798. }
  120799. /* If that was the last leaf node, break out of the loop */
  120800. if( pParent==0 ) break;
  120801. /* Set $p to point to the next leaf in the tree of eType nodes */
  120802. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  120803. /* Remove pParent from the original tree. */
  120804. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  120805. pParent->pRight->pParent = pParent->pParent;
  120806. if( pParent->pParent ){
  120807. pParent->pParent->pLeft = pParent->pRight;
  120808. }else{
  120809. assert( pParent==pRoot );
  120810. pRoot = pParent->pRight;
  120811. }
  120812. /* Link pParent into the free node list. It will be used as an
  120813. ** internal node of the new tree. */
  120814. pParent->pParent = pFree;
  120815. pFree = pParent;
  120816. }
  120817. if( rc==SQLITE_OK ){
  120818. p = 0;
  120819. for(i=0; i<nMaxDepth; i++){
  120820. if( apLeaf[i] ){
  120821. if( p==0 ){
  120822. p = apLeaf[i];
  120823. p->pParent = 0;
  120824. }else{
  120825. assert( pFree!=0 );
  120826. pFree->pRight = p;
  120827. pFree->pLeft = apLeaf[i];
  120828. pFree->pLeft->pParent = pFree;
  120829. pFree->pRight->pParent = pFree;
  120830. p = pFree;
  120831. pFree = pFree->pParent;
  120832. p->pParent = 0;
  120833. }
  120834. }
  120835. }
  120836. pRoot = p;
  120837. }else{
  120838. /* An error occurred. Delete the contents of the apLeaf[] array
  120839. ** and pFree list. Everything else is cleaned up by the call to
  120840. ** sqlite3Fts3ExprFree(pRoot) below. */
  120841. Fts3Expr *pDel;
  120842. for(i=0; i<nMaxDepth; i++){
  120843. sqlite3Fts3ExprFree(apLeaf[i]);
  120844. }
  120845. while( (pDel=pFree)!=0 ){
  120846. pFree = pDel->pParent;
  120847. sqlite3_free(pDel);
  120848. }
  120849. }
  120850. assert( pFree==0 );
  120851. sqlite3_free( apLeaf );
  120852. }
  120853. }
  120854. if( rc!=SQLITE_OK ){
  120855. sqlite3Fts3ExprFree(pRoot);
  120856. pRoot = 0;
  120857. }
  120858. *pp = pRoot;
  120859. return rc;
  120860. }
  120861. /*
  120862. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  120863. ** differences:
  120864. **
  120865. ** 1. It does not do expression rebalancing.
  120866. ** 2. It does not check that the expression does not exceed the
  120867. ** maximum allowable depth.
  120868. ** 3. Even if it fails, *ppExpr may still be set to point to an
  120869. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  120870. ** in this case.
  120871. */
  120872. static int fts3ExprParseUnbalanced(
  120873. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  120874. int iLangid, /* Language id for tokenizer */
  120875. char **azCol, /* Array of column names for fts3 table */
  120876. int bFts4, /* True to allow FTS4-only syntax */
  120877. int nCol, /* Number of entries in azCol[] */
  120878. int iDefaultCol, /* Default column to query */
  120879. const char *z, int n, /* Text of MATCH query */
  120880. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  120881. ){
  120882. int nParsed;
  120883. int rc;
  120884. ParseContext sParse;
  120885. memset(&sParse, 0, sizeof(ParseContext));
  120886. sParse.pTokenizer = pTokenizer;
  120887. sParse.iLangid = iLangid;
  120888. sParse.azCol = (const char **)azCol;
  120889. sParse.nCol = nCol;
  120890. sParse.iDefaultCol = iDefaultCol;
  120891. sParse.bFts4 = bFts4;
  120892. if( z==0 ){
  120893. *ppExpr = 0;
  120894. return SQLITE_OK;
  120895. }
  120896. if( n<0 ){
  120897. n = (int)strlen(z);
  120898. }
  120899. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  120900. assert( rc==SQLITE_OK || *ppExpr==0 );
  120901. /* Check for mismatched parenthesis */
  120902. if( rc==SQLITE_OK && sParse.nNest ){
  120903. rc = SQLITE_ERROR;
  120904. }
  120905. return rc;
  120906. }
  120907. /*
  120908. ** Parameters z and n contain a pointer to and length of a buffer containing
  120909. ** an fts3 query expression, respectively. This function attempts to parse the
  120910. ** query expression and create a tree of Fts3Expr structures representing the
  120911. ** parsed expression. If successful, *ppExpr is set to point to the head
  120912. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  120913. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  120914. ** error) is returned and *ppExpr is set to 0.
  120915. **
  120916. ** If parameter n is a negative number, then z is assumed to point to a
  120917. ** nul-terminated string and the length is determined using strlen().
  120918. **
  120919. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  120920. ** use to normalize query tokens while parsing the expression. The azCol[]
  120921. ** array, which is assumed to contain nCol entries, should contain the names
  120922. ** of each column in the target fts3 table, in order from left to right.
  120923. ** Column names must be nul-terminated strings.
  120924. **
  120925. ** The iDefaultCol parameter should be passed the index of the table column
  120926. ** that appears on the left-hand-side of the MATCH operator (the default
  120927. ** column to match against for tokens for which a column name is not explicitly
  120928. ** specified as part of the query string), or -1 if tokens may by default
  120929. ** match any table column.
  120930. */
  120931. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  120932. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  120933. int iLangid, /* Language id for tokenizer */
  120934. char **azCol, /* Array of column names for fts3 table */
  120935. int bFts4, /* True to allow FTS4-only syntax */
  120936. int nCol, /* Number of entries in azCol[] */
  120937. int iDefaultCol, /* Default column to query */
  120938. const char *z, int n, /* Text of MATCH query */
  120939. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  120940. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  120941. ){
  120942. int rc = fts3ExprParseUnbalanced(
  120943. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  120944. );
  120945. /* Rebalance the expression. And check that its depth does not exceed
  120946. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  120947. if( rc==SQLITE_OK && *ppExpr ){
  120948. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  120949. if( rc==SQLITE_OK ){
  120950. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  120951. }
  120952. }
  120953. if( rc!=SQLITE_OK ){
  120954. sqlite3Fts3ExprFree(*ppExpr);
  120955. *ppExpr = 0;
  120956. if( rc==SQLITE_TOOBIG ){
  120957. *pzErr = sqlite3_mprintf(
  120958. "FTS expression tree is too large (maximum depth %d)",
  120959. SQLITE_FTS3_MAX_EXPR_DEPTH
  120960. );
  120961. rc = SQLITE_ERROR;
  120962. }else if( rc==SQLITE_ERROR ){
  120963. *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
  120964. }
  120965. }
  120966. return rc;
  120967. }
  120968. /*
  120969. ** Free a single node of an expression tree.
  120970. */
  120971. static void fts3FreeExprNode(Fts3Expr *p){
  120972. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  120973. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  120974. sqlite3_free(p->aMI);
  120975. sqlite3_free(p);
  120976. }
  120977. /*
  120978. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  120979. **
  120980. ** This function would be simpler if it recursively called itself. But
  120981. ** that would mean passing a sufficiently large expression to ExprParse()
  120982. ** could cause a stack overflow.
  120983. */
  120984. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  120985. Fts3Expr *p;
  120986. assert( pDel==0 || pDel->pParent==0 );
  120987. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  120988. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  120989. }
  120990. while( p ){
  120991. Fts3Expr *pParent = p->pParent;
  120992. fts3FreeExprNode(p);
  120993. if( pParent && p==pParent->pLeft && pParent->pRight ){
  120994. p = pParent->pRight;
  120995. while( p && (p->pLeft || p->pRight) ){
  120996. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  120997. p = (p->pLeft ? p->pLeft : p->pRight);
  120998. }
  120999. }else{
  121000. p = pParent;
  121001. }
  121002. }
  121003. }
  121004. /****************************************************************************
  121005. *****************************************************************************
  121006. ** Everything after this point is just test code.
  121007. */
  121008. #ifdef SQLITE_TEST
  121009. /* #include <stdio.h> */
  121010. /*
  121011. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  121012. */
  121013. static int queryTestTokenizer(
  121014. sqlite3 *db,
  121015. const char *zName,
  121016. const sqlite3_tokenizer_module **pp
  121017. ){
  121018. int rc;
  121019. sqlite3_stmt *pStmt;
  121020. const char zSql[] = "SELECT fts3_tokenizer(?)";
  121021. *pp = 0;
  121022. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  121023. if( rc!=SQLITE_OK ){
  121024. return rc;
  121025. }
  121026. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  121027. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  121028. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  121029. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  121030. }
  121031. }
  121032. return sqlite3_finalize(pStmt);
  121033. }
  121034. /*
  121035. ** Return a pointer to a buffer containing a text representation of the
  121036. ** expression passed as the first argument. The buffer is obtained from
  121037. ** sqlite3_malloc(). It is the responsibility of the caller to use
  121038. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  121039. ** NULL is returned.
  121040. **
  121041. ** If the second argument is not NULL, then its contents are prepended to
  121042. ** the returned expression text and then freed using sqlite3_free().
  121043. */
  121044. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  121045. if( pExpr==0 ){
  121046. return sqlite3_mprintf("");
  121047. }
  121048. switch( pExpr->eType ){
  121049. case FTSQUERY_PHRASE: {
  121050. Fts3Phrase *pPhrase = pExpr->pPhrase;
  121051. int i;
  121052. zBuf = sqlite3_mprintf(
  121053. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  121054. for(i=0; zBuf && i<pPhrase->nToken; i++){
  121055. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  121056. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  121057. (pPhrase->aToken[i].isPrefix?"+":"")
  121058. );
  121059. }
  121060. return zBuf;
  121061. }
  121062. case FTSQUERY_NEAR:
  121063. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  121064. break;
  121065. case FTSQUERY_NOT:
  121066. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  121067. break;
  121068. case FTSQUERY_AND:
  121069. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  121070. break;
  121071. case FTSQUERY_OR:
  121072. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  121073. break;
  121074. }
  121075. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  121076. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  121077. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  121078. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  121079. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  121080. return zBuf;
  121081. }
  121082. /*
  121083. ** This is the implementation of a scalar SQL function used to test the
  121084. ** expression parser. It should be called as follows:
  121085. **
  121086. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  121087. **
  121088. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  121089. ** to parse the query expression (see README.tokenizers). The second argument
  121090. ** is the query expression to parse. Each subsequent argument is the name
  121091. ** of a column of the fts3 table that the query expression may refer to.
  121092. ** For example:
  121093. **
  121094. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  121095. */
  121096. static void fts3ExprTest(
  121097. sqlite3_context *context,
  121098. int argc,
  121099. sqlite3_value **argv
  121100. ){
  121101. sqlite3_tokenizer_module const *pModule = 0;
  121102. sqlite3_tokenizer *pTokenizer = 0;
  121103. int rc;
  121104. char **azCol = 0;
  121105. const char *zExpr;
  121106. int nExpr;
  121107. int nCol;
  121108. int ii;
  121109. Fts3Expr *pExpr;
  121110. char *zBuf = 0;
  121111. sqlite3 *db = sqlite3_context_db_handle(context);
  121112. if( argc<3 ){
  121113. sqlite3_result_error(context,
  121114. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  121115. );
  121116. return;
  121117. }
  121118. rc = queryTestTokenizer(db,
  121119. (const char *)sqlite3_value_text(argv[0]), &pModule);
  121120. if( rc==SQLITE_NOMEM ){
  121121. sqlite3_result_error_nomem(context);
  121122. goto exprtest_out;
  121123. }else if( !pModule ){
  121124. sqlite3_result_error(context, "No such tokenizer module", -1);
  121125. goto exprtest_out;
  121126. }
  121127. rc = pModule->xCreate(0, 0, &pTokenizer);
  121128. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  121129. if( rc==SQLITE_NOMEM ){
  121130. sqlite3_result_error_nomem(context);
  121131. goto exprtest_out;
  121132. }
  121133. pTokenizer->pModule = pModule;
  121134. zExpr = (const char *)sqlite3_value_text(argv[1]);
  121135. nExpr = sqlite3_value_bytes(argv[1]);
  121136. nCol = argc-2;
  121137. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  121138. if( !azCol ){
  121139. sqlite3_result_error_nomem(context);
  121140. goto exprtest_out;
  121141. }
  121142. for(ii=0; ii<nCol; ii++){
  121143. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  121144. }
  121145. if( sqlite3_user_data(context) ){
  121146. char *zDummy = 0;
  121147. rc = sqlite3Fts3ExprParse(
  121148. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  121149. );
  121150. assert( rc==SQLITE_OK || pExpr==0 );
  121151. sqlite3_free(zDummy);
  121152. }else{
  121153. rc = fts3ExprParseUnbalanced(
  121154. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  121155. );
  121156. }
  121157. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  121158. sqlite3Fts3ExprFree(pExpr);
  121159. sqlite3_result_error(context, "Error parsing expression", -1);
  121160. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  121161. sqlite3_result_error_nomem(context);
  121162. }else{
  121163. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  121164. sqlite3_free(zBuf);
  121165. }
  121166. sqlite3Fts3ExprFree(pExpr);
  121167. exprtest_out:
  121168. if( pModule && pTokenizer ){
  121169. rc = pModule->xDestroy(pTokenizer);
  121170. }
  121171. sqlite3_free(azCol);
  121172. }
  121173. /*
  121174. ** Register the query expression parser test function fts3_exprtest()
  121175. ** with database connection db.
  121176. */
  121177. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  121178. int rc = sqlite3_create_function(
  121179. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  121180. );
  121181. if( rc==SQLITE_OK ){
  121182. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  121183. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  121184. );
  121185. }
  121186. return rc;
  121187. }
  121188. #endif
  121189. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  121190. /************** End of fts3_expr.c *******************************************/
  121191. /************** Begin file fts3_hash.c ***************************************/
  121192. /*
  121193. ** 2001 September 22
  121194. **
  121195. ** The author disclaims copyright to this source code. In place of
  121196. ** a legal notice, here is a blessing:
  121197. **
  121198. ** May you do good and not evil.
  121199. ** May you find forgiveness for yourself and forgive others.
  121200. ** May you share freely, never taking more than you give.
  121201. **
  121202. *************************************************************************
  121203. ** This is the implementation of generic hash-tables used in SQLite.
  121204. ** We've modified it slightly to serve as a standalone hash table
  121205. ** implementation for the full-text indexing module.
  121206. */
  121207. /*
  121208. ** The code in this file is only compiled if:
  121209. **
  121210. ** * The FTS3 module is being built as an extension
  121211. ** (in which case SQLITE_CORE is not defined), or
  121212. **
  121213. ** * The FTS3 module is being built into the core of
  121214. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  121215. */
  121216. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  121217. /* #include <assert.h> */
  121218. /* #include <stdlib.h> */
  121219. /* #include <string.h> */
  121220. /*
  121221. ** Malloc and Free functions
  121222. */
  121223. static void *fts3HashMalloc(int n){
  121224. void *p = sqlite3_malloc(n);
  121225. if( p ){
  121226. memset(p, 0, n);
  121227. }
  121228. return p;
  121229. }
  121230. static void fts3HashFree(void *p){
  121231. sqlite3_free(p);
  121232. }
  121233. /* Turn bulk memory into a hash table object by initializing the
  121234. ** fields of the Hash structure.
  121235. **
  121236. ** "pNew" is a pointer to the hash table that is to be initialized.
  121237. ** keyClass is one of the constants
  121238. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  121239. ** determines what kind of key the hash table will use. "copyKey" is
  121240. ** true if the hash table should make its own private copy of keys and
  121241. ** false if it should just use the supplied pointer.
  121242. */
  121243. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  121244. assert( pNew!=0 );
  121245. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  121246. pNew->keyClass = keyClass;
  121247. pNew->copyKey = copyKey;
  121248. pNew->first = 0;
  121249. pNew->count = 0;
  121250. pNew->htsize = 0;
  121251. pNew->ht = 0;
  121252. }
  121253. /* Remove all entries from a hash table. Reclaim all memory.
  121254. ** Call this routine to delete a hash table or to reset a hash table
  121255. ** to the empty state.
  121256. */
  121257. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  121258. Fts3HashElem *elem; /* For looping over all elements of the table */
  121259. assert( pH!=0 );
  121260. elem = pH->first;
  121261. pH->first = 0;
  121262. fts3HashFree(pH->ht);
  121263. pH->ht = 0;
  121264. pH->htsize = 0;
  121265. while( elem ){
  121266. Fts3HashElem *next_elem = elem->next;
  121267. if( pH->copyKey && elem->pKey ){
  121268. fts3HashFree(elem->pKey);
  121269. }
  121270. fts3HashFree(elem);
  121271. elem = next_elem;
  121272. }
  121273. pH->count = 0;
  121274. }
  121275. /*
  121276. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  121277. */
  121278. static int fts3StrHash(const void *pKey, int nKey){
  121279. const char *z = (const char *)pKey;
  121280. int h = 0;
  121281. if( nKey<=0 ) nKey = (int) strlen(z);
  121282. while( nKey > 0 ){
  121283. h = (h<<3) ^ h ^ *z++;
  121284. nKey--;
  121285. }
  121286. return h & 0x7fffffff;
  121287. }
  121288. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  121289. if( n1!=n2 ) return 1;
  121290. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  121291. }
  121292. /*
  121293. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  121294. */
  121295. static int fts3BinHash(const void *pKey, int nKey){
  121296. int h = 0;
  121297. const char *z = (const char *)pKey;
  121298. while( nKey-- > 0 ){
  121299. h = (h<<3) ^ h ^ *(z++);
  121300. }
  121301. return h & 0x7fffffff;
  121302. }
  121303. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  121304. if( n1!=n2 ) return 1;
  121305. return memcmp(pKey1,pKey2,n1);
  121306. }
  121307. /*
  121308. ** Return a pointer to the appropriate hash function given the key class.
  121309. **
  121310. ** The C syntax in this function definition may be unfamilar to some
  121311. ** programmers, so we provide the following additional explanation:
  121312. **
  121313. ** The name of the function is "ftsHashFunction". The function takes a
  121314. ** single parameter "keyClass". The return value of ftsHashFunction()
  121315. ** is a pointer to another function. Specifically, the return value
  121316. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  121317. ** with types "const void*" and "int" and returns an "int".
  121318. */
  121319. static int (*ftsHashFunction(int keyClass))(const void*,int){
  121320. if( keyClass==FTS3_HASH_STRING ){
  121321. return &fts3StrHash;
  121322. }else{
  121323. assert( keyClass==FTS3_HASH_BINARY );
  121324. return &fts3BinHash;
  121325. }
  121326. }
  121327. /*
  121328. ** Return a pointer to the appropriate hash function given the key class.
  121329. **
  121330. ** For help in interpreted the obscure C code in the function definition,
  121331. ** see the header comment on the previous function.
  121332. */
  121333. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  121334. if( keyClass==FTS3_HASH_STRING ){
  121335. return &fts3StrCompare;
  121336. }else{
  121337. assert( keyClass==FTS3_HASH_BINARY );
  121338. return &fts3BinCompare;
  121339. }
  121340. }
  121341. /* Link an element into the hash table
  121342. */
  121343. static void fts3HashInsertElement(
  121344. Fts3Hash *pH, /* The complete hash table */
  121345. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  121346. Fts3HashElem *pNew /* The element to be inserted */
  121347. ){
  121348. Fts3HashElem *pHead; /* First element already in pEntry */
  121349. pHead = pEntry->chain;
  121350. if( pHead ){
  121351. pNew->next = pHead;
  121352. pNew->prev = pHead->prev;
  121353. if( pHead->prev ){ pHead->prev->next = pNew; }
  121354. else { pH->first = pNew; }
  121355. pHead->prev = pNew;
  121356. }else{
  121357. pNew->next = pH->first;
  121358. if( pH->first ){ pH->first->prev = pNew; }
  121359. pNew->prev = 0;
  121360. pH->first = pNew;
  121361. }
  121362. pEntry->count++;
  121363. pEntry->chain = pNew;
  121364. }
  121365. /* Resize the hash table so that it cantains "new_size" buckets.
  121366. ** "new_size" must be a power of 2. The hash table might fail
  121367. ** to resize if sqliteMalloc() fails.
  121368. **
  121369. ** Return non-zero if a memory allocation error occurs.
  121370. */
  121371. static int fts3Rehash(Fts3Hash *pH, int new_size){
  121372. struct _fts3ht *new_ht; /* The new hash table */
  121373. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  121374. int (*xHash)(const void*,int); /* The hash function */
  121375. assert( (new_size & (new_size-1))==0 );
  121376. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  121377. if( new_ht==0 ) return 1;
  121378. fts3HashFree(pH->ht);
  121379. pH->ht = new_ht;
  121380. pH->htsize = new_size;
  121381. xHash = ftsHashFunction(pH->keyClass);
  121382. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  121383. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  121384. next_elem = elem->next;
  121385. fts3HashInsertElement(pH, &new_ht[h], elem);
  121386. }
  121387. return 0;
  121388. }
  121389. /* This function (for internal use only) locates an element in an
  121390. ** hash table that matches the given key. The hash for this key has
  121391. ** already been computed and is passed as the 4th parameter.
  121392. */
  121393. static Fts3HashElem *fts3FindElementByHash(
  121394. const Fts3Hash *pH, /* The pH to be searched */
  121395. const void *pKey, /* The key we are searching for */
  121396. int nKey,
  121397. int h /* The hash for this key. */
  121398. ){
  121399. Fts3HashElem *elem; /* Used to loop thru the element list */
  121400. int count; /* Number of elements left to test */
  121401. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  121402. if( pH->ht ){
  121403. struct _fts3ht *pEntry = &pH->ht[h];
  121404. elem = pEntry->chain;
  121405. count = pEntry->count;
  121406. xCompare = ftsCompareFunction(pH->keyClass);
  121407. while( count-- && elem ){
  121408. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  121409. return elem;
  121410. }
  121411. elem = elem->next;
  121412. }
  121413. }
  121414. return 0;
  121415. }
  121416. /* Remove a single entry from the hash table given a pointer to that
  121417. ** element and a hash on the element's key.
  121418. */
  121419. static void fts3RemoveElementByHash(
  121420. Fts3Hash *pH, /* The pH containing "elem" */
  121421. Fts3HashElem* elem, /* The element to be removed from the pH */
  121422. int h /* Hash value for the element */
  121423. ){
  121424. struct _fts3ht *pEntry;
  121425. if( elem->prev ){
  121426. elem->prev->next = elem->next;
  121427. }else{
  121428. pH->first = elem->next;
  121429. }
  121430. if( elem->next ){
  121431. elem->next->prev = elem->prev;
  121432. }
  121433. pEntry = &pH->ht[h];
  121434. if( pEntry->chain==elem ){
  121435. pEntry->chain = elem->next;
  121436. }
  121437. pEntry->count--;
  121438. if( pEntry->count<=0 ){
  121439. pEntry->chain = 0;
  121440. }
  121441. if( pH->copyKey && elem->pKey ){
  121442. fts3HashFree(elem->pKey);
  121443. }
  121444. fts3HashFree( elem );
  121445. pH->count--;
  121446. if( pH->count<=0 ){
  121447. assert( pH->first==0 );
  121448. assert( pH->count==0 );
  121449. fts3HashClear(pH);
  121450. }
  121451. }
  121452. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  121453. const Fts3Hash *pH,
  121454. const void *pKey,
  121455. int nKey
  121456. ){
  121457. int h; /* A hash on key */
  121458. int (*xHash)(const void*,int); /* The hash function */
  121459. if( pH==0 || pH->ht==0 ) return 0;
  121460. xHash = ftsHashFunction(pH->keyClass);
  121461. assert( xHash!=0 );
  121462. h = (*xHash)(pKey,nKey);
  121463. assert( (pH->htsize & (pH->htsize-1))==0 );
  121464. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  121465. }
  121466. /*
  121467. ** Attempt to locate an element of the hash table pH with a key
  121468. ** that matches pKey,nKey. Return the data for this element if it is
  121469. ** found, or NULL if there is no match.
  121470. */
  121471. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  121472. Fts3HashElem *pElem; /* The element that matches key (if any) */
  121473. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  121474. return pElem ? pElem->data : 0;
  121475. }
  121476. /* Insert an element into the hash table pH. The key is pKey,nKey
  121477. ** and the data is "data".
  121478. **
  121479. ** If no element exists with a matching key, then a new
  121480. ** element is created. A copy of the key is made if the copyKey
  121481. ** flag is set. NULL is returned.
  121482. **
  121483. ** If another element already exists with the same key, then the
  121484. ** new data replaces the old data and the old data is returned.
  121485. ** The key is not copied in this instance. If a malloc fails, then
  121486. ** the new data is returned and the hash table is unchanged.
  121487. **
  121488. ** If the "data" parameter to this function is NULL, then the
  121489. ** element corresponding to "key" is removed from the hash table.
  121490. */
  121491. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  121492. Fts3Hash *pH, /* The hash table to insert into */
  121493. const void *pKey, /* The key */
  121494. int nKey, /* Number of bytes in the key */
  121495. void *data /* The data */
  121496. ){
  121497. int hraw; /* Raw hash value of the key */
  121498. int h; /* the hash of the key modulo hash table size */
  121499. Fts3HashElem *elem; /* Used to loop thru the element list */
  121500. Fts3HashElem *new_elem; /* New element added to the pH */
  121501. int (*xHash)(const void*,int); /* The hash function */
  121502. assert( pH!=0 );
  121503. xHash = ftsHashFunction(pH->keyClass);
  121504. assert( xHash!=0 );
  121505. hraw = (*xHash)(pKey, nKey);
  121506. assert( (pH->htsize & (pH->htsize-1))==0 );
  121507. h = hraw & (pH->htsize-1);
  121508. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  121509. if( elem ){
  121510. void *old_data = elem->data;
  121511. if( data==0 ){
  121512. fts3RemoveElementByHash(pH,elem,h);
  121513. }else{
  121514. elem->data = data;
  121515. }
  121516. return old_data;
  121517. }
  121518. if( data==0 ) return 0;
  121519. if( (pH->htsize==0 && fts3Rehash(pH,8))
  121520. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  121521. ){
  121522. pH->count = 0;
  121523. return data;
  121524. }
  121525. assert( pH->htsize>0 );
  121526. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  121527. if( new_elem==0 ) return data;
  121528. if( pH->copyKey && pKey!=0 ){
  121529. new_elem->pKey = fts3HashMalloc( nKey );
  121530. if( new_elem->pKey==0 ){
  121531. fts3HashFree(new_elem);
  121532. return data;
  121533. }
  121534. memcpy((void*)new_elem->pKey, pKey, nKey);
  121535. }else{
  121536. new_elem->pKey = (void*)pKey;
  121537. }
  121538. new_elem->nKey = nKey;
  121539. pH->count++;
  121540. assert( pH->htsize>0 );
  121541. assert( (pH->htsize & (pH->htsize-1))==0 );
  121542. h = hraw & (pH->htsize-1);
  121543. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  121544. new_elem->data = data;
  121545. return 0;
  121546. }
  121547. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  121548. /************** End of fts3_hash.c *******************************************/
  121549. /************** Begin file fts3_porter.c *************************************/
  121550. /*
  121551. ** 2006 September 30
  121552. **
  121553. ** The author disclaims copyright to this source code. In place of
  121554. ** a legal notice, here is a blessing:
  121555. **
  121556. ** May you do good and not evil.
  121557. ** May you find forgiveness for yourself and forgive others.
  121558. ** May you share freely, never taking more than you give.
  121559. **
  121560. *************************************************************************
  121561. ** Implementation of the full-text-search tokenizer that implements
  121562. ** a Porter stemmer.
  121563. */
  121564. /*
  121565. ** The code in this file is only compiled if:
  121566. **
  121567. ** * The FTS3 module is being built as an extension
  121568. ** (in which case SQLITE_CORE is not defined), or
  121569. **
  121570. ** * The FTS3 module is being built into the core of
  121571. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  121572. */
  121573. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  121574. /* #include <assert.h> */
  121575. /* #include <stdlib.h> */
  121576. /* #include <stdio.h> */
  121577. /* #include <string.h> */
  121578. /*
  121579. ** Class derived from sqlite3_tokenizer
  121580. */
  121581. typedef struct porter_tokenizer {
  121582. sqlite3_tokenizer base; /* Base class */
  121583. } porter_tokenizer;
  121584. /*
  121585. ** Class derived from sqlite3_tokenizer_cursor
  121586. */
  121587. typedef struct porter_tokenizer_cursor {
  121588. sqlite3_tokenizer_cursor base;
  121589. const char *zInput; /* input we are tokenizing */
  121590. int nInput; /* size of the input */
  121591. int iOffset; /* current position in zInput */
  121592. int iToken; /* index of next token to be returned */
  121593. char *zToken; /* storage for current token */
  121594. int nAllocated; /* space allocated to zToken buffer */
  121595. } porter_tokenizer_cursor;
  121596. /*
  121597. ** Create a new tokenizer instance.
  121598. */
  121599. static int porterCreate(
  121600. int argc, const char * const *argv,
  121601. sqlite3_tokenizer **ppTokenizer
  121602. ){
  121603. porter_tokenizer *t;
  121604. UNUSED_PARAMETER(argc);
  121605. UNUSED_PARAMETER(argv);
  121606. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  121607. if( t==NULL ) return SQLITE_NOMEM;
  121608. memset(t, 0, sizeof(*t));
  121609. *ppTokenizer = &t->base;
  121610. return SQLITE_OK;
  121611. }
  121612. /*
  121613. ** Destroy a tokenizer
  121614. */
  121615. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  121616. sqlite3_free(pTokenizer);
  121617. return SQLITE_OK;
  121618. }
  121619. /*
  121620. ** Prepare to begin tokenizing a particular string. The input
  121621. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  121622. ** used to incrementally tokenize this string is returned in
  121623. ** *ppCursor.
  121624. */
  121625. static int porterOpen(
  121626. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  121627. const char *zInput, int nInput, /* String to be tokenized */
  121628. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  121629. ){
  121630. porter_tokenizer_cursor *c;
  121631. UNUSED_PARAMETER(pTokenizer);
  121632. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  121633. if( c==NULL ) return SQLITE_NOMEM;
  121634. c->zInput = zInput;
  121635. if( zInput==0 ){
  121636. c->nInput = 0;
  121637. }else if( nInput<0 ){
  121638. c->nInput = (int)strlen(zInput);
  121639. }else{
  121640. c->nInput = nInput;
  121641. }
  121642. c->iOffset = 0; /* start tokenizing at the beginning */
  121643. c->iToken = 0;
  121644. c->zToken = NULL; /* no space allocated, yet. */
  121645. c->nAllocated = 0;
  121646. *ppCursor = &c->base;
  121647. return SQLITE_OK;
  121648. }
  121649. /*
  121650. ** Close a tokenization cursor previously opened by a call to
  121651. ** porterOpen() above.
  121652. */
  121653. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  121654. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  121655. sqlite3_free(c->zToken);
  121656. sqlite3_free(c);
  121657. return SQLITE_OK;
  121658. }
  121659. /*
  121660. ** Vowel or consonant
  121661. */
  121662. static const char cType[] = {
  121663. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  121664. 1, 1, 1, 2, 1
  121665. };
  121666. /*
  121667. ** isConsonant() and isVowel() determine if their first character in
  121668. ** the string they point to is a consonant or a vowel, according
  121669. ** to Porter ruls.
  121670. **
  121671. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  121672. ** 'Y' is a consonant unless it follows another consonant,
  121673. ** in which case it is a vowel.
  121674. **
  121675. ** In these routine, the letters are in reverse order. So the 'y' rule
  121676. ** is that 'y' is a consonant unless it is followed by another
  121677. ** consonent.
  121678. */
  121679. static int isVowel(const char*);
  121680. static int isConsonant(const char *z){
  121681. int j;
  121682. char x = *z;
  121683. if( x==0 ) return 0;
  121684. assert( x>='a' && x<='z' );
  121685. j = cType[x-'a'];
  121686. if( j<2 ) return j;
  121687. return z[1]==0 || isVowel(z + 1);
  121688. }
  121689. static int isVowel(const char *z){
  121690. int j;
  121691. char x = *z;
  121692. if( x==0 ) return 0;
  121693. assert( x>='a' && x<='z' );
  121694. j = cType[x-'a'];
  121695. if( j<2 ) return 1-j;
  121696. return isConsonant(z + 1);
  121697. }
  121698. /*
  121699. ** Let any sequence of one or more vowels be represented by V and let
  121700. ** C be sequence of one or more consonants. Then every word can be
  121701. ** represented as:
  121702. **
  121703. ** [C] (VC){m} [V]
  121704. **
  121705. ** In prose: A word is an optional consonant followed by zero or
  121706. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  121707. ** number of vowel consonant pairs. This routine computes the value
  121708. ** of m for the first i bytes of a word.
  121709. **
  121710. ** Return true if the m-value for z is 1 or more. In other words,
  121711. ** return true if z contains at least one vowel that is followed
  121712. ** by a consonant.
  121713. **
  121714. ** In this routine z[] is in reverse order. So we are really looking
  121715. ** for an instance of of a consonant followed by a vowel.
  121716. */
  121717. static int m_gt_0(const char *z){
  121718. while( isVowel(z) ){ z++; }
  121719. if( *z==0 ) return 0;
  121720. while( isConsonant(z) ){ z++; }
  121721. return *z!=0;
  121722. }
  121723. /* Like mgt0 above except we are looking for a value of m which is
  121724. ** exactly 1
  121725. */
  121726. static int m_eq_1(const char *z){
  121727. while( isVowel(z) ){ z++; }
  121728. if( *z==0 ) return 0;
  121729. while( isConsonant(z) ){ z++; }
  121730. if( *z==0 ) return 0;
  121731. while( isVowel(z) ){ z++; }
  121732. if( *z==0 ) return 1;
  121733. while( isConsonant(z) ){ z++; }
  121734. return *z==0;
  121735. }
  121736. /* Like mgt0 above except we are looking for a value of m>1 instead
  121737. ** or m>0
  121738. */
  121739. static int m_gt_1(const char *z){
  121740. while( isVowel(z) ){ z++; }
  121741. if( *z==0 ) return 0;
  121742. while( isConsonant(z) ){ z++; }
  121743. if( *z==0 ) return 0;
  121744. while( isVowel(z) ){ z++; }
  121745. if( *z==0 ) return 0;
  121746. while( isConsonant(z) ){ z++; }
  121747. return *z!=0;
  121748. }
  121749. /*
  121750. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  121751. */
  121752. static int hasVowel(const char *z){
  121753. while( isConsonant(z) ){ z++; }
  121754. return *z!=0;
  121755. }
  121756. /*
  121757. ** Return TRUE if the word ends in a double consonant.
  121758. **
  121759. ** The text is reversed here. So we are really looking at
  121760. ** the first two characters of z[].
  121761. */
  121762. static int doubleConsonant(const char *z){
  121763. return isConsonant(z) && z[0]==z[1];
  121764. }
  121765. /*
  121766. ** Return TRUE if the word ends with three letters which
  121767. ** are consonant-vowel-consonent and where the final consonant
  121768. ** is not 'w', 'x', or 'y'.
  121769. **
  121770. ** The word is reversed here. So we are really checking the
  121771. ** first three letters and the first one cannot be in [wxy].
  121772. */
  121773. static int star_oh(const char *z){
  121774. return
  121775. isConsonant(z) &&
  121776. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  121777. isVowel(z+1) &&
  121778. isConsonant(z+2);
  121779. }
  121780. /*
  121781. ** If the word ends with zFrom and xCond() is true for the stem
  121782. ** of the word that preceeds the zFrom ending, then change the
  121783. ** ending to zTo.
  121784. **
  121785. ** The input word *pz and zFrom are both in reverse order. zTo
  121786. ** is in normal order.
  121787. **
  121788. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  121789. ** match. Not that TRUE is returned even if xCond() fails and
  121790. ** no substitution occurs.
  121791. */
  121792. static int stem(
  121793. char **pz, /* The word being stemmed (Reversed) */
  121794. const char *zFrom, /* If the ending matches this... (Reversed) */
  121795. const char *zTo, /* ... change the ending to this (not reversed) */
  121796. int (*xCond)(const char*) /* Condition that must be true */
  121797. ){
  121798. char *z = *pz;
  121799. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  121800. if( *zFrom!=0 ) return 0;
  121801. if( xCond && !xCond(z) ) return 1;
  121802. while( *zTo ){
  121803. *(--z) = *(zTo++);
  121804. }
  121805. *pz = z;
  121806. return 1;
  121807. }
  121808. /*
  121809. ** This is the fallback stemmer used when the porter stemmer is
  121810. ** inappropriate. The input word is copied into the output with
  121811. ** US-ASCII case folding. If the input word is too long (more
  121812. ** than 20 bytes if it contains no digits or more than 6 bytes if
  121813. ** it contains digits) then word is truncated to 20 or 6 bytes
  121814. ** by taking 10 or 3 bytes from the beginning and end.
  121815. */
  121816. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  121817. int i, mx, j;
  121818. int hasDigit = 0;
  121819. for(i=0; i<nIn; i++){
  121820. char c = zIn[i];
  121821. if( c>='A' && c<='Z' ){
  121822. zOut[i] = c - 'A' + 'a';
  121823. }else{
  121824. if( c>='0' && c<='9' ) hasDigit = 1;
  121825. zOut[i] = c;
  121826. }
  121827. }
  121828. mx = hasDigit ? 3 : 10;
  121829. if( nIn>mx*2 ){
  121830. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  121831. zOut[j] = zOut[i];
  121832. }
  121833. i = j;
  121834. }
  121835. zOut[i] = 0;
  121836. *pnOut = i;
  121837. }
  121838. /*
  121839. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  121840. ** zOut is at least big enough to hold nIn bytes. Write the actual
  121841. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  121842. **
  121843. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  121844. ** are converted to lower case. Upper-case UTF characters are
  121845. ** unchanged.
  121846. **
  121847. ** Words that are longer than about 20 bytes are stemmed by retaining
  121848. ** a few bytes from the beginning and the end of the word. If the
  121849. ** word contains digits, 3 bytes are taken from the beginning and
  121850. ** 3 bytes from the end. For long words without digits, 10 bytes
  121851. ** are taken from each end. US-ASCII case folding still applies.
  121852. **
  121853. ** If the input word contains not digits but does characters not
  121854. ** in [a-zA-Z] then no stemming is attempted and this routine just
  121855. ** copies the input into the input into the output with US-ASCII
  121856. ** case folding.
  121857. **
  121858. ** Stemming never increases the length of the word. So there is
  121859. ** no chance of overflowing the zOut buffer.
  121860. */
  121861. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  121862. int i, j;
  121863. char zReverse[28];
  121864. char *z, *z2;
  121865. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  121866. /* The word is too big or too small for the porter stemmer.
  121867. ** Fallback to the copy stemmer */
  121868. copy_stemmer(zIn, nIn, zOut, pnOut);
  121869. return;
  121870. }
  121871. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  121872. char c = zIn[i];
  121873. if( c>='A' && c<='Z' ){
  121874. zReverse[j] = c + 'a' - 'A';
  121875. }else if( c>='a' && c<='z' ){
  121876. zReverse[j] = c;
  121877. }else{
  121878. /* The use of a character not in [a-zA-Z] means that we fallback
  121879. ** to the copy stemmer */
  121880. copy_stemmer(zIn, nIn, zOut, pnOut);
  121881. return;
  121882. }
  121883. }
  121884. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  121885. z = &zReverse[j+1];
  121886. /* Step 1a */
  121887. if( z[0]=='s' ){
  121888. if(
  121889. !stem(&z, "sess", "ss", 0) &&
  121890. !stem(&z, "sei", "i", 0) &&
  121891. !stem(&z, "ss", "ss", 0)
  121892. ){
  121893. z++;
  121894. }
  121895. }
  121896. /* Step 1b */
  121897. z2 = z;
  121898. if( stem(&z, "dee", "ee", m_gt_0) ){
  121899. /* Do nothing. The work was all in the test */
  121900. }else if(
  121901. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  121902. && z!=z2
  121903. ){
  121904. if( stem(&z, "ta", "ate", 0) ||
  121905. stem(&z, "lb", "ble", 0) ||
  121906. stem(&z, "zi", "ize", 0) ){
  121907. /* Do nothing. The work was all in the test */
  121908. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  121909. z++;
  121910. }else if( m_eq_1(z) && star_oh(z) ){
  121911. *(--z) = 'e';
  121912. }
  121913. }
  121914. /* Step 1c */
  121915. if( z[0]=='y' && hasVowel(z+1) ){
  121916. z[0] = 'i';
  121917. }
  121918. /* Step 2 */
  121919. switch( z[1] ){
  121920. case 'a':
  121921. stem(&z, "lanoita", "ate", m_gt_0) ||
  121922. stem(&z, "lanoit", "tion", m_gt_0);
  121923. break;
  121924. case 'c':
  121925. stem(&z, "icne", "ence", m_gt_0) ||
  121926. stem(&z, "icna", "ance", m_gt_0);
  121927. break;
  121928. case 'e':
  121929. stem(&z, "rezi", "ize", m_gt_0);
  121930. break;
  121931. case 'g':
  121932. stem(&z, "igol", "log", m_gt_0);
  121933. break;
  121934. case 'l':
  121935. stem(&z, "ilb", "ble", m_gt_0) ||
  121936. stem(&z, "illa", "al", m_gt_0) ||
  121937. stem(&z, "iltne", "ent", m_gt_0) ||
  121938. stem(&z, "ile", "e", m_gt_0) ||
  121939. stem(&z, "ilsuo", "ous", m_gt_0);
  121940. break;
  121941. case 'o':
  121942. stem(&z, "noitazi", "ize", m_gt_0) ||
  121943. stem(&z, "noita", "ate", m_gt_0) ||
  121944. stem(&z, "rota", "ate", m_gt_0);
  121945. break;
  121946. case 's':
  121947. stem(&z, "msila", "al", m_gt_0) ||
  121948. stem(&z, "ssenevi", "ive", m_gt_0) ||
  121949. stem(&z, "ssenluf", "ful", m_gt_0) ||
  121950. stem(&z, "ssensuo", "ous", m_gt_0);
  121951. break;
  121952. case 't':
  121953. stem(&z, "itila", "al", m_gt_0) ||
  121954. stem(&z, "itivi", "ive", m_gt_0) ||
  121955. stem(&z, "itilib", "ble", m_gt_0);
  121956. break;
  121957. }
  121958. /* Step 3 */
  121959. switch( z[0] ){
  121960. case 'e':
  121961. stem(&z, "etaci", "ic", m_gt_0) ||
  121962. stem(&z, "evita", "", m_gt_0) ||
  121963. stem(&z, "ezila", "al", m_gt_0);
  121964. break;
  121965. case 'i':
  121966. stem(&z, "itici", "ic", m_gt_0);
  121967. break;
  121968. case 'l':
  121969. stem(&z, "laci", "ic", m_gt_0) ||
  121970. stem(&z, "luf", "", m_gt_0);
  121971. break;
  121972. case 's':
  121973. stem(&z, "ssen", "", m_gt_0);
  121974. break;
  121975. }
  121976. /* Step 4 */
  121977. switch( z[1] ){
  121978. case 'a':
  121979. if( z[0]=='l' && m_gt_1(z+2) ){
  121980. z += 2;
  121981. }
  121982. break;
  121983. case 'c':
  121984. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  121985. z += 4;
  121986. }
  121987. break;
  121988. case 'e':
  121989. if( z[0]=='r' && m_gt_1(z+2) ){
  121990. z += 2;
  121991. }
  121992. break;
  121993. case 'i':
  121994. if( z[0]=='c' && m_gt_1(z+2) ){
  121995. z += 2;
  121996. }
  121997. break;
  121998. case 'l':
  121999. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  122000. z += 4;
  122001. }
  122002. break;
  122003. case 'n':
  122004. if( z[0]=='t' ){
  122005. if( z[2]=='a' ){
  122006. if( m_gt_1(z+3) ){
  122007. z += 3;
  122008. }
  122009. }else if( z[2]=='e' ){
  122010. stem(&z, "tneme", "", m_gt_1) ||
  122011. stem(&z, "tnem", "", m_gt_1) ||
  122012. stem(&z, "tne", "", m_gt_1);
  122013. }
  122014. }
  122015. break;
  122016. case 'o':
  122017. if( z[0]=='u' ){
  122018. if( m_gt_1(z+2) ){
  122019. z += 2;
  122020. }
  122021. }else if( z[3]=='s' || z[3]=='t' ){
  122022. stem(&z, "noi", "", m_gt_1);
  122023. }
  122024. break;
  122025. case 's':
  122026. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  122027. z += 3;
  122028. }
  122029. break;
  122030. case 't':
  122031. stem(&z, "eta", "", m_gt_1) ||
  122032. stem(&z, "iti", "", m_gt_1);
  122033. break;
  122034. case 'u':
  122035. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  122036. z += 3;
  122037. }
  122038. break;
  122039. case 'v':
  122040. case 'z':
  122041. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  122042. z += 3;
  122043. }
  122044. break;
  122045. }
  122046. /* Step 5a */
  122047. if( z[0]=='e' ){
  122048. if( m_gt_1(z+1) ){
  122049. z++;
  122050. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  122051. z++;
  122052. }
  122053. }
  122054. /* Step 5b */
  122055. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  122056. z++;
  122057. }
  122058. /* z[] is now the stemmed word in reverse order. Flip it back
  122059. ** around into forward order and return.
  122060. */
  122061. *pnOut = i = (int)strlen(z);
  122062. zOut[i] = 0;
  122063. while( *z ){
  122064. zOut[--i] = *(z++);
  122065. }
  122066. }
  122067. /*
  122068. ** Characters that can be part of a token. We assume any character
  122069. ** whose value is greater than 0x80 (any UTF character) can be
  122070. ** part of a token. In other words, delimiters all must have
  122071. ** values of 0x7f or lower.
  122072. */
  122073. static const char porterIdChar[] = {
  122074. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  122075. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  122076. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  122077. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  122078. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  122079. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  122080. };
  122081. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  122082. /*
  122083. ** Extract the next token from a tokenization cursor. The cursor must
  122084. ** have been opened by a prior call to porterOpen().
  122085. */
  122086. static int porterNext(
  122087. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  122088. const char **pzToken, /* OUT: *pzToken is the token text */
  122089. int *pnBytes, /* OUT: Number of bytes in token */
  122090. int *piStartOffset, /* OUT: Starting offset of token */
  122091. int *piEndOffset, /* OUT: Ending offset of token */
  122092. int *piPosition /* OUT: Position integer of token */
  122093. ){
  122094. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  122095. const char *z = c->zInput;
  122096. while( c->iOffset<c->nInput ){
  122097. int iStartOffset, ch;
  122098. /* Scan past delimiter characters */
  122099. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  122100. c->iOffset++;
  122101. }
  122102. /* Count non-delimiter characters. */
  122103. iStartOffset = c->iOffset;
  122104. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  122105. c->iOffset++;
  122106. }
  122107. if( c->iOffset>iStartOffset ){
  122108. int n = c->iOffset-iStartOffset;
  122109. if( n>c->nAllocated ){
  122110. char *pNew;
  122111. c->nAllocated = n+20;
  122112. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  122113. if( !pNew ) return SQLITE_NOMEM;
  122114. c->zToken = pNew;
  122115. }
  122116. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  122117. *pzToken = c->zToken;
  122118. *piStartOffset = iStartOffset;
  122119. *piEndOffset = c->iOffset;
  122120. *piPosition = c->iToken++;
  122121. return SQLITE_OK;
  122122. }
  122123. }
  122124. return SQLITE_DONE;
  122125. }
  122126. /*
  122127. ** The set of routines that implement the porter-stemmer tokenizer
  122128. */
  122129. static const sqlite3_tokenizer_module porterTokenizerModule = {
  122130. 0,
  122131. porterCreate,
  122132. porterDestroy,
  122133. porterOpen,
  122134. porterClose,
  122135. porterNext,
  122136. 0
  122137. };
  122138. /*
  122139. ** Allocate a new porter tokenizer. Return a pointer to the new
  122140. ** tokenizer in *ppModule
  122141. */
  122142. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  122143. sqlite3_tokenizer_module const**ppModule
  122144. ){
  122145. *ppModule = &porterTokenizerModule;
  122146. }
  122147. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  122148. /************** End of fts3_porter.c *****************************************/
  122149. /************** Begin file fts3_tokenizer.c **********************************/
  122150. /*
  122151. ** 2007 June 22
  122152. **
  122153. ** The author disclaims copyright to this source code. In place of
  122154. ** a legal notice, here is a blessing:
  122155. **
  122156. ** May you do good and not evil.
  122157. ** May you find forgiveness for yourself and forgive others.
  122158. ** May you share freely, never taking more than you give.
  122159. **
  122160. ******************************************************************************
  122161. **
  122162. ** This is part of an SQLite module implementing full-text search.
  122163. ** This particular file implements the generic tokenizer interface.
  122164. */
  122165. /*
  122166. ** The code in this file is only compiled if:
  122167. **
  122168. ** * The FTS3 module is being built as an extension
  122169. ** (in which case SQLITE_CORE is not defined), or
  122170. **
  122171. ** * The FTS3 module is being built into the core of
  122172. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  122173. */
  122174. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  122175. /* #include <assert.h> */
  122176. /* #include <string.h> */
  122177. /*
  122178. ** Implementation of the SQL scalar function for accessing the underlying
  122179. ** hash table. This function may be called as follows:
  122180. **
  122181. ** SELECT <function-name>(<key-name>);
  122182. ** SELECT <function-name>(<key-name>, <pointer>);
  122183. **
  122184. ** where <function-name> is the name passed as the second argument
  122185. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  122186. **
  122187. ** If the <pointer> argument is specified, it must be a blob value
  122188. ** containing a pointer to be stored as the hash data corresponding
  122189. ** to the string <key-name>. If <pointer> is not specified, then
  122190. ** the string <key-name> must already exist in the has table. Otherwise,
  122191. ** an error is returned.
  122192. **
  122193. ** Whether or not the <pointer> argument is specified, the value returned
  122194. ** is a blob containing the pointer stored as the hash data corresponding
  122195. ** to string <key-name> (after the hash-table is updated, if applicable).
  122196. */
  122197. static void scalarFunc(
  122198. sqlite3_context *context,
  122199. int argc,
  122200. sqlite3_value **argv
  122201. ){
  122202. Fts3Hash *pHash;
  122203. void *pPtr = 0;
  122204. const unsigned char *zName;
  122205. int nName;
  122206. assert( argc==1 || argc==2 );
  122207. pHash = (Fts3Hash *)sqlite3_user_data(context);
  122208. zName = sqlite3_value_text(argv[0]);
  122209. nName = sqlite3_value_bytes(argv[0])+1;
  122210. if( argc==2 ){
  122211. void *pOld;
  122212. int n = sqlite3_value_bytes(argv[1]);
  122213. if( n!=sizeof(pPtr) ){
  122214. sqlite3_result_error(context, "argument type mismatch", -1);
  122215. return;
  122216. }
  122217. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  122218. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  122219. if( pOld==pPtr ){
  122220. sqlite3_result_error(context, "out of memory", -1);
  122221. return;
  122222. }
  122223. }else{
  122224. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  122225. if( !pPtr ){
  122226. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  122227. sqlite3_result_error(context, zErr, -1);
  122228. sqlite3_free(zErr);
  122229. return;
  122230. }
  122231. }
  122232. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  122233. }
  122234. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  122235. static const char isFtsIdChar[] = {
  122236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  122237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  122238. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  122239. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  122240. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  122241. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  122242. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  122243. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  122244. };
  122245. return (c&0x80 || isFtsIdChar[(int)(c)]);
  122246. }
  122247. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  122248. const char *z1;
  122249. const char *z2 = 0;
  122250. /* Find the start of the next token. */
  122251. z1 = zStr;
  122252. while( z2==0 ){
  122253. char c = *z1;
  122254. switch( c ){
  122255. case '\0': return 0; /* No more tokens here */
  122256. case '\'':
  122257. case '"':
  122258. case '`': {
  122259. z2 = z1;
  122260. while( *++z2 && (*z2!=c || *++z2==c) );
  122261. break;
  122262. }
  122263. case '[':
  122264. z2 = &z1[1];
  122265. while( *z2 && z2[0]!=']' ) z2++;
  122266. if( *z2 ) z2++;
  122267. break;
  122268. default:
  122269. if( sqlite3Fts3IsIdChar(*z1) ){
  122270. z2 = &z1[1];
  122271. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  122272. }else{
  122273. z1++;
  122274. }
  122275. }
  122276. }
  122277. *pn = (int)(z2-z1);
  122278. return z1;
  122279. }
  122280. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  122281. Fts3Hash *pHash, /* Tokenizer hash table */
  122282. const char *zArg, /* Tokenizer name */
  122283. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  122284. char **pzErr /* OUT: Set to malloced error message */
  122285. ){
  122286. int rc;
  122287. char *z = (char *)zArg;
  122288. int n = 0;
  122289. char *zCopy;
  122290. char *zEnd; /* Pointer to nul-term of zCopy */
  122291. sqlite3_tokenizer_module *m;
  122292. zCopy = sqlite3_mprintf("%s", zArg);
  122293. if( !zCopy ) return SQLITE_NOMEM;
  122294. zEnd = &zCopy[strlen(zCopy)];
  122295. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  122296. z[n] = '\0';
  122297. sqlite3Fts3Dequote(z);
  122298. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  122299. if( !m ){
  122300. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
  122301. rc = SQLITE_ERROR;
  122302. }else{
  122303. char const **aArg = 0;
  122304. int iArg = 0;
  122305. z = &z[n+1];
  122306. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  122307. int nNew = sizeof(char *)*(iArg+1);
  122308. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  122309. if( !aNew ){
  122310. sqlite3_free(zCopy);
  122311. sqlite3_free((void *)aArg);
  122312. return SQLITE_NOMEM;
  122313. }
  122314. aArg = aNew;
  122315. aArg[iArg++] = z;
  122316. z[n] = '\0';
  122317. sqlite3Fts3Dequote(z);
  122318. z = &z[n+1];
  122319. }
  122320. rc = m->xCreate(iArg, aArg, ppTok);
  122321. assert( rc!=SQLITE_OK || *ppTok );
  122322. if( rc!=SQLITE_OK ){
  122323. *pzErr = sqlite3_mprintf("unknown tokenizer");
  122324. }else{
  122325. (*ppTok)->pModule = m;
  122326. }
  122327. sqlite3_free((void *)aArg);
  122328. }
  122329. sqlite3_free(zCopy);
  122330. return rc;
  122331. }
  122332. #ifdef SQLITE_TEST
  122333. #include <tcl.h>
  122334. /* #include <string.h> */
  122335. /*
  122336. ** Implementation of a special SQL scalar function for testing tokenizers
  122337. ** designed to be used in concert with the Tcl testing framework. This
  122338. ** function must be called with two or more arguments:
  122339. **
  122340. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  122341. **
  122342. ** where <function-name> is the name passed as the second argument
  122343. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  122344. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  122345. **
  122346. ** The return value is a string that may be interpreted as a Tcl
  122347. ** list. For each token in the <input-string>, three elements are
  122348. ** added to the returned list. The first is the token position, the
  122349. ** second is the token text (folded, stemmed, etc.) and the third is the
  122350. ** substring of <input-string> associated with the token. For example,
  122351. ** using the built-in "simple" tokenizer:
  122352. **
  122353. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  122354. **
  122355. ** will return the string:
  122356. **
  122357. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  122358. **
  122359. */
  122360. static void testFunc(
  122361. sqlite3_context *context,
  122362. int argc,
  122363. sqlite3_value **argv
  122364. ){
  122365. Fts3Hash *pHash;
  122366. sqlite3_tokenizer_module *p;
  122367. sqlite3_tokenizer *pTokenizer = 0;
  122368. sqlite3_tokenizer_cursor *pCsr = 0;
  122369. const char *zErr = 0;
  122370. const char *zName;
  122371. int nName;
  122372. const char *zInput;
  122373. int nInput;
  122374. const char *azArg[64];
  122375. const char *zToken;
  122376. int nToken = 0;
  122377. int iStart = 0;
  122378. int iEnd = 0;
  122379. int iPos = 0;
  122380. int i;
  122381. Tcl_Obj *pRet;
  122382. if( argc<2 ){
  122383. sqlite3_result_error(context, "insufficient arguments", -1);
  122384. return;
  122385. }
  122386. nName = sqlite3_value_bytes(argv[0]);
  122387. zName = (const char *)sqlite3_value_text(argv[0]);
  122388. nInput = sqlite3_value_bytes(argv[argc-1]);
  122389. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  122390. pHash = (Fts3Hash *)sqlite3_user_data(context);
  122391. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  122392. if( !p ){
  122393. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  122394. sqlite3_result_error(context, zErr, -1);
  122395. sqlite3_free(zErr);
  122396. return;
  122397. }
  122398. pRet = Tcl_NewObj();
  122399. Tcl_IncrRefCount(pRet);
  122400. for(i=1; i<argc-1; i++){
  122401. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  122402. }
  122403. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  122404. zErr = "error in xCreate()";
  122405. goto finish;
  122406. }
  122407. pTokenizer->pModule = p;
  122408. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  122409. zErr = "error in xOpen()";
  122410. goto finish;
  122411. }
  122412. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  122413. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  122414. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  122415. zToken = &zInput[iStart];
  122416. nToken = iEnd-iStart;
  122417. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  122418. }
  122419. if( SQLITE_OK!=p->xClose(pCsr) ){
  122420. zErr = "error in xClose()";
  122421. goto finish;
  122422. }
  122423. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  122424. zErr = "error in xDestroy()";
  122425. goto finish;
  122426. }
  122427. finish:
  122428. if( zErr ){
  122429. sqlite3_result_error(context, zErr, -1);
  122430. }else{
  122431. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  122432. }
  122433. Tcl_DecrRefCount(pRet);
  122434. }
  122435. static
  122436. int registerTokenizer(
  122437. sqlite3 *db,
  122438. char *zName,
  122439. const sqlite3_tokenizer_module *p
  122440. ){
  122441. int rc;
  122442. sqlite3_stmt *pStmt;
  122443. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  122444. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  122445. if( rc!=SQLITE_OK ){
  122446. return rc;
  122447. }
  122448. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  122449. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  122450. sqlite3_step(pStmt);
  122451. return sqlite3_finalize(pStmt);
  122452. }
  122453. static
  122454. int queryTokenizer(
  122455. sqlite3 *db,
  122456. char *zName,
  122457. const sqlite3_tokenizer_module **pp
  122458. ){
  122459. int rc;
  122460. sqlite3_stmt *pStmt;
  122461. const char zSql[] = "SELECT fts3_tokenizer(?)";
  122462. *pp = 0;
  122463. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  122464. if( rc!=SQLITE_OK ){
  122465. return rc;
  122466. }
  122467. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  122468. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  122469. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  122470. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  122471. }
  122472. }
  122473. return sqlite3_finalize(pStmt);
  122474. }
  122475. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  122476. /*
  122477. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  122478. ** This function is used for testing only, it is not included in the
  122479. ** build unless SQLITE_TEST is defined.
  122480. **
  122481. ** The purpose of this is to test that the fts3_tokenizer() function
  122482. ** can be used as designed by the C-code in the queryTokenizer and
  122483. ** registerTokenizer() functions above. These two functions are repeated
  122484. ** in the README.tokenizer file as an example, so it is important to
  122485. ** test them.
  122486. **
  122487. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  122488. ** function with no arguments. An assert() will fail if a problem is
  122489. ** detected. i.e.:
  122490. **
  122491. ** SELECT fts3_tokenizer_internal_test();
  122492. **
  122493. */
  122494. static void intTestFunc(
  122495. sqlite3_context *context,
  122496. int argc,
  122497. sqlite3_value **argv
  122498. ){
  122499. int rc;
  122500. const sqlite3_tokenizer_module *p1;
  122501. const sqlite3_tokenizer_module *p2;
  122502. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  122503. UNUSED_PARAMETER(argc);
  122504. UNUSED_PARAMETER(argv);
  122505. /* Test the query function */
  122506. sqlite3Fts3SimpleTokenizerModule(&p1);
  122507. rc = queryTokenizer(db, "simple", &p2);
  122508. assert( rc==SQLITE_OK );
  122509. assert( p1==p2 );
  122510. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  122511. assert( rc==SQLITE_ERROR );
  122512. assert( p2==0 );
  122513. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  122514. /* Test the storage function */
  122515. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  122516. assert( rc==SQLITE_OK );
  122517. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  122518. assert( rc==SQLITE_OK );
  122519. assert( p2==p1 );
  122520. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  122521. }
  122522. #endif
  122523. /*
  122524. ** Set up SQL objects in database db used to access the contents of
  122525. ** the hash table pointed to by argument pHash. The hash table must
  122526. ** been initialized to use string keys, and to take a private copy
  122527. ** of the key when a value is inserted. i.e. by a call similar to:
  122528. **
  122529. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  122530. **
  122531. ** This function adds a scalar function (see header comment above
  122532. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  122533. ** defined at compilation time, a temporary virtual table (see header
  122534. ** comment above struct HashTableVtab) to the database schema. Both
  122535. ** provide read/write access to the contents of *pHash.
  122536. **
  122537. ** The third argument to this function, zName, is used as the name
  122538. ** of both the scalar and, if created, the virtual table.
  122539. */
  122540. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  122541. sqlite3 *db,
  122542. Fts3Hash *pHash,
  122543. const char *zName
  122544. ){
  122545. int rc = SQLITE_OK;
  122546. void *p = (void *)pHash;
  122547. const int any = SQLITE_ANY;
  122548. #ifdef SQLITE_TEST
  122549. char *zTest = 0;
  122550. char *zTest2 = 0;
  122551. void *pdb = (void *)db;
  122552. zTest = sqlite3_mprintf("%s_test", zName);
  122553. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  122554. if( !zTest || !zTest2 ){
  122555. rc = SQLITE_NOMEM;
  122556. }
  122557. #endif
  122558. if( SQLITE_OK==rc ){
  122559. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  122560. }
  122561. if( SQLITE_OK==rc ){
  122562. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  122563. }
  122564. #ifdef SQLITE_TEST
  122565. if( SQLITE_OK==rc ){
  122566. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  122567. }
  122568. if( SQLITE_OK==rc ){
  122569. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  122570. }
  122571. #endif
  122572. #ifdef SQLITE_TEST
  122573. sqlite3_free(zTest);
  122574. sqlite3_free(zTest2);
  122575. #endif
  122576. return rc;
  122577. }
  122578. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  122579. /************** End of fts3_tokenizer.c **************************************/
  122580. /************** Begin file fts3_tokenizer1.c *********************************/
  122581. /*
  122582. ** 2006 Oct 10
  122583. **
  122584. ** The author disclaims copyright to this source code. In place of
  122585. ** a legal notice, here is a blessing:
  122586. **
  122587. ** May you do good and not evil.
  122588. ** May you find forgiveness for yourself and forgive others.
  122589. ** May you share freely, never taking more than you give.
  122590. **
  122591. ******************************************************************************
  122592. **
  122593. ** Implementation of the "simple" full-text-search tokenizer.
  122594. */
  122595. /*
  122596. ** The code in this file is only compiled if:
  122597. **
  122598. ** * The FTS3 module is being built as an extension
  122599. ** (in which case SQLITE_CORE is not defined), or
  122600. **
  122601. ** * The FTS3 module is being built into the core of
  122602. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  122603. */
  122604. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  122605. /* #include <assert.h> */
  122606. /* #include <stdlib.h> */
  122607. /* #include <stdio.h> */
  122608. /* #include <string.h> */
  122609. typedef struct simple_tokenizer {
  122610. sqlite3_tokenizer base;
  122611. char delim[128]; /* flag ASCII delimiters */
  122612. } simple_tokenizer;
  122613. typedef struct simple_tokenizer_cursor {
  122614. sqlite3_tokenizer_cursor base;
  122615. const char *pInput; /* input we are tokenizing */
  122616. int nBytes; /* size of the input */
  122617. int iOffset; /* current position in pInput */
  122618. int iToken; /* index of next token to be returned */
  122619. char *pToken; /* storage for current token */
  122620. int nTokenAllocated; /* space allocated to zToken buffer */
  122621. } simple_tokenizer_cursor;
  122622. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  122623. return c<0x80 && t->delim[c];
  122624. }
  122625. static int fts3_isalnum(int x){
  122626. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  122627. }
  122628. /*
  122629. ** Create a new tokenizer instance.
  122630. */
  122631. static int simpleCreate(
  122632. int argc, const char * const *argv,
  122633. sqlite3_tokenizer **ppTokenizer
  122634. ){
  122635. simple_tokenizer *t;
  122636. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  122637. if( t==NULL ) return SQLITE_NOMEM;
  122638. memset(t, 0, sizeof(*t));
  122639. /* TODO(shess) Delimiters need to remain the same from run to run,
  122640. ** else we need to reindex. One solution would be a meta-table to
  122641. ** track such information in the database, then we'd only want this
  122642. ** information on the initial create.
  122643. */
  122644. if( argc>1 ){
  122645. int i, n = (int)strlen(argv[1]);
  122646. for(i=0; i<n; i++){
  122647. unsigned char ch = argv[1][i];
  122648. /* We explicitly don't support UTF-8 delimiters for now. */
  122649. if( ch>=0x80 ){
  122650. sqlite3_free(t);
  122651. return SQLITE_ERROR;
  122652. }
  122653. t->delim[ch] = 1;
  122654. }
  122655. } else {
  122656. /* Mark non-alphanumeric ASCII characters as delimiters */
  122657. int i;
  122658. for(i=1; i<0x80; i++){
  122659. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  122660. }
  122661. }
  122662. *ppTokenizer = &t->base;
  122663. return SQLITE_OK;
  122664. }
  122665. /*
  122666. ** Destroy a tokenizer
  122667. */
  122668. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  122669. sqlite3_free(pTokenizer);
  122670. return SQLITE_OK;
  122671. }
  122672. /*
  122673. ** Prepare to begin tokenizing a particular string. The input
  122674. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  122675. ** used to incrementally tokenize this string is returned in
  122676. ** *ppCursor.
  122677. */
  122678. static int simpleOpen(
  122679. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  122680. const char *pInput, int nBytes, /* String to be tokenized */
  122681. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  122682. ){
  122683. simple_tokenizer_cursor *c;
  122684. UNUSED_PARAMETER(pTokenizer);
  122685. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  122686. if( c==NULL ) return SQLITE_NOMEM;
  122687. c->pInput = pInput;
  122688. if( pInput==0 ){
  122689. c->nBytes = 0;
  122690. }else if( nBytes<0 ){
  122691. c->nBytes = (int)strlen(pInput);
  122692. }else{
  122693. c->nBytes = nBytes;
  122694. }
  122695. c->iOffset = 0; /* start tokenizing at the beginning */
  122696. c->iToken = 0;
  122697. c->pToken = NULL; /* no space allocated, yet. */
  122698. c->nTokenAllocated = 0;
  122699. *ppCursor = &c->base;
  122700. return SQLITE_OK;
  122701. }
  122702. /*
  122703. ** Close a tokenization cursor previously opened by a call to
  122704. ** simpleOpen() above.
  122705. */
  122706. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  122707. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  122708. sqlite3_free(c->pToken);
  122709. sqlite3_free(c);
  122710. return SQLITE_OK;
  122711. }
  122712. /*
  122713. ** Extract the next token from a tokenization cursor. The cursor must
  122714. ** have been opened by a prior call to simpleOpen().
  122715. */
  122716. static int simpleNext(
  122717. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  122718. const char **ppToken, /* OUT: *ppToken is the token text */
  122719. int *pnBytes, /* OUT: Number of bytes in token */
  122720. int *piStartOffset, /* OUT: Starting offset of token */
  122721. int *piEndOffset, /* OUT: Ending offset of token */
  122722. int *piPosition /* OUT: Position integer of token */
  122723. ){
  122724. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  122725. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  122726. unsigned char *p = (unsigned char *)c->pInput;
  122727. while( c->iOffset<c->nBytes ){
  122728. int iStartOffset;
  122729. /* Scan past delimiter characters */
  122730. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  122731. c->iOffset++;
  122732. }
  122733. /* Count non-delimiter characters. */
  122734. iStartOffset = c->iOffset;
  122735. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  122736. c->iOffset++;
  122737. }
  122738. if( c->iOffset>iStartOffset ){
  122739. int i, n = c->iOffset-iStartOffset;
  122740. if( n>c->nTokenAllocated ){
  122741. char *pNew;
  122742. c->nTokenAllocated = n+20;
  122743. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  122744. if( !pNew ) return SQLITE_NOMEM;
  122745. c->pToken = pNew;
  122746. }
  122747. for(i=0; i<n; i++){
  122748. /* TODO(shess) This needs expansion to handle UTF-8
  122749. ** case-insensitivity.
  122750. */
  122751. unsigned char ch = p[iStartOffset+i];
  122752. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  122753. }
  122754. *ppToken = c->pToken;
  122755. *pnBytes = n;
  122756. *piStartOffset = iStartOffset;
  122757. *piEndOffset = c->iOffset;
  122758. *piPosition = c->iToken++;
  122759. return SQLITE_OK;
  122760. }
  122761. }
  122762. return SQLITE_DONE;
  122763. }
  122764. /*
  122765. ** The set of routines that implement the simple tokenizer
  122766. */
  122767. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  122768. 0,
  122769. simpleCreate,
  122770. simpleDestroy,
  122771. simpleOpen,
  122772. simpleClose,
  122773. simpleNext,
  122774. 0,
  122775. };
  122776. /*
  122777. ** Allocate a new simple tokenizer. Return a pointer to the new
  122778. ** tokenizer in *ppModule
  122779. */
  122780. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  122781. sqlite3_tokenizer_module const**ppModule
  122782. ){
  122783. *ppModule = &simpleTokenizerModule;
  122784. }
  122785. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  122786. /************** End of fts3_tokenizer1.c *************************************/
  122787. /************** Begin file fts3_tokenize_vtab.c ******************************/
  122788. /*
  122789. ** 2013 Apr 22
  122790. **
  122791. ** The author disclaims copyright to this source code. In place of
  122792. ** a legal notice, here is a blessing:
  122793. **
  122794. ** May you do good and not evil.
  122795. ** May you find forgiveness for yourself and forgive others.
  122796. ** May you share freely, never taking more than you give.
  122797. **
  122798. ******************************************************************************
  122799. **
  122800. ** This file contains code for the "fts3tokenize" virtual table module.
  122801. ** An fts3tokenize virtual table is created as follows:
  122802. **
  122803. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  122804. ** <tokenizer-name>, <arg-1>, ...
  122805. ** );
  122806. **
  122807. ** The table created has the following schema:
  122808. **
  122809. ** CREATE TABLE <tbl>(input, token, start, end, position)
  122810. **
  122811. ** When queried, the query must include a WHERE clause of type:
  122812. **
  122813. ** input = <string>
  122814. **
  122815. ** The virtual table module tokenizes this <string>, using the FTS3
  122816. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  122817. ** statement and returns one row for each token in the result. With
  122818. ** fields set as follows:
  122819. **
  122820. ** input: Always set to a copy of <string>
  122821. ** token: A token from the input.
  122822. ** start: Byte offset of the token within the input <string>.
  122823. ** end: Byte offset of the byte immediately following the end of the
  122824. ** token within the input string.
  122825. ** pos: Token offset of token within input.
  122826. **
  122827. */
  122828. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  122829. /* #include <string.h> */
  122830. /* #include <assert.h> */
  122831. typedef struct Fts3tokTable Fts3tokTable;
  122832. typedef struct Fts3tokCursor Fts3tokCursor;
  122833. /*
  122834. ** Virtual table structure.
  122835. */
  122836. struct Fts3tokTable {
  122837. sqlite3_vtab base; /* Base class used by SQLite core */
  122838. const sqlite3_tokenizer_module *pMod;
  122839. sqlite3_tokenizer *pTok;
  122840. };
  122841. /*
  122842. ** Virtual table cursor structure.
  122843. */
  122844. struct Fts3tokCursor {
  122845. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  122846. char *zInput; /* Input string */
  122847. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  122848. int iRowid; /* Current 'rowid' value */
  122849. const char *zToken; /* Current 'token' value */
  122850. int nToken; /* Size of zToken in bytes */
  122851. int iStart; /* Current 'start' value */
  122852. int iEnd; /* Current 'end' value */
  122853. int iPos; /* Current 'pos' value */
  122854. };
  122855. /*
  122856. ** Query FTS for the tokenizer implementation named zName.
  122857. */
  122858. static int fts3tokQueryTokenizer(
  122859. Fts3Hash *pHash,
  122860. const char *zName,
  122861. const sqlite3_tokenizer_module **pp,
  122862. char **pzErr
  122863. ){
  122864. sqlite3_tokenizer_module *p;
  122865. int nName = (int)strlen(zName);
  122866. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  122867. if( !p ){
  122868. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  122869. return SQLITE_ERROR;
  122870. }
  122871. *pp = p;
  122872. return SQLITE_OK;
  122873. }
  122874. /*
  122875. ** The second argument, argv[], is an array of pointers to nul-terminated
  122876. ** strings. This function makes a copy of the array and strings into a
  122877. ** single block of memory. It then dequotes any of the strings that appear
  122878. ** to be quoted.
  122879. **
  122880. ** If successful, output parameter *pazDequote is set to point at the
  122881. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  122882. ** responsible for eventually calling sqlite3_free() to free the array
  122883. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  122884. ** The final value of *pazDequote is undefined in this case.
  122885. */
  122886. static int fts3tokDequoteArray(
  122887. int argc, /* Number of elements in argv[] */
  122888. const char * const *argv, /* Input array */
  122889. char ***pazDequote /* Output array */
  122890. ){
  122891. int rc = SQLITE_OK; /* Return code */
  122892. if( argc==0 ){
  122893. *pazDequote = 0;
  122894. }else{
  122895. int i;
  122896. int nByte = 0;
  122897. char **azDequote;
  122898. for(i=0; i<argc; i++){
  122899. nByte += (int)(strlen(argv[i]) + 1);
  122900. }
  122901. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  122902. if( azDequote==0 ){
  122903. rc = SQLITE_NOMEM;
  122904. }else{
  122905. char *pSpace = (char *)&azDequote[argc];
  122906. for(i=0; i<argc; i++){
  122907. int n = (int)strlen(argv[i]);
  122908. azDequote[i] = pSpace;
  122909. memcpy(pSpace, argv[i], n+1);
  122910. sqlite3Fts3Dequote(pSpace);
  122911. pSpace += (n+1);
  122912. }
  122913. }
  122914. }
  122915. return rc;
  122916. }
  122917. /*
  122918. ** Schema of the tokenizer table.
  122919. */
  122920. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  122921. /*
  122922. ** This function does all the work for both the xConnect and xCreate methods.
  122923. ** These tables have no persistent representation of their own, so xConnect
  122924. ** and xCreate are identical operations.
  122925. **
  122926. ** argv[0]: module name
  122927. ** argv[1]: database name
  122928. ** argv[2]: table name
  122929. ** argv[3]: first argument (tokenizer name)
  122930. */
  122931. static int fts3tokConnectMethod(
  122932. sqlite3 *db, /* Database connection */
  122933. void *pHash, /* Hash table of tokenizers */
  122934. int argc, /* Number of elements in argv array */
  122935. const char * const *argv, /* xCreate/xConnect argument array */
  122936. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  122937. char **pzErr /* OUT: sqlite3_malloc'd error message */
  122938. ){
  122939. Fts3tokTable *pTab;
  122940. const sqlite3_tokenizer_module *pMod = 0;
  122941. sqlite3_tokenizer *pTok = 0;
  122942. int rc;
  122943. char **azDequote = 0;
  122944. int nDequote;
  122945. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  122946. if( rc!=SQLITE_OK ) return rc;
  122947. nDequote = argc-3;
  122948. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  122949. if( rc==SQLITE_OK ){
  122950. const char *zModule;
  122951. if( nDequote<1 ){
  122952. zModule = "simple";
  122953. }else{
  122954. zModule = azDequote[0];
  122955. }
  122956. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  122957. }
  122958. assert( (rc==SQLITE_OK)==(pMod!=0) );
  122959. if( rc==SQLITE_OK ){
  122960. const char * const *azArg = (const char * const *)&azDequote[1];
  122961. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  122962. }
  122963. if( rc==SQLITE_OK ){
  122964. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  122965. if( pTab==0 ){
  122966. rc = SQLITE_NOMEM;
  122967. }
  122968. }
  122969. if( rc==SQLITE_OK ){
  122970. memset(pTab, 0, sizeof(Fts3tokTable));
  122971. pTab->pMod = pMod;
  122972. pTab->pTok = pTok;
  122973. *ppVtab = &pTab->base;
  122974. }else{
  122975. if( pTok ){
  122976. pMod->xDestroy(pTok);
  122977. }
  122978. }
  122979. sqlite3_free(azDequote);
  122980. return rc;
  122981. }
  122982. /*
  122983. ** This function does the work for both the xDisconnect and xDestroy methods.
  122984. ** These tables have no persistent representation of their own, so xDisconnect
  122985. ** and xDestroy are identical operations.
  122986. */
  122987. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  122988. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  122989. pTab->pMod->xDestroy(pTab->pTok);
  122990. sqlite3_free(pTab);
  122991. return SQLITE_OK;
  122992. }
  122993. /*
  122994. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  122995. */
  122996. static int fts3tokBestIndexMethod(
  122997. sqlite3_vtab *pVTab,
  122998. sqlite3_index_info *pInfo
  122999. ){
  123000. int i;
  123001. UNUSED_PARAMETER(pVTab);
  123002. for(i=0; i<pInfo->nConstraint; i++){
  123003. if( pInfo->aConstraint[i].usable
  123004. && pInfo->aConstraint[i].iColumn==0
  123005. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  123006. ){
  123007. pInfo->idxNum = 1;
  123008. pInfo->aConstraintUsage[i].argvIndex = 1;
  123009. pInfo->aConstraintUsage[i].omit = 1;
  123010. pInfo->estimatedCost = 1;
  123011. return SQLITE_OK;
  123012. }
  123013. }
  123014. pInfo->idxNum = 0;
  123015. assert( pInfo->estimatedCost>1000000.0 );
  123016. return SQLITE_OK;
  123017. }
  123018. /*
  123019. ** xOpen - Open a cursor.
  123020. */
  123021. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  123022. Fts3tokCursor *pCsr;
  123023. UNUSED_PARAMETER(pVTab);
  123024. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  123025. if( pCsr==0 ){
  123026. return SQLITE_NOMEM;
  123027. }
  123028. memset(pCsr, 0, sizeof(Fts3tokCursor));
  123029. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  123030. return SQLITE_OK;
  123031. }
  123032. /*
  123033. ** Reset the tokenizer cursor passed as the only argument. As if it had
  123034. ** just been returned by fts3tokOpenMethod().
  123035. */
  123036. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  123037. if( pCsr->pCsr ){
  123038. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  123039. pTab->pMod->xClose(pCsr->pCsr);
  123040. pCsr->pCsr = 0;
  123041. }
  123042. sqlite3_free(pCsr->zInput);
  123043. pCsr->zInput = 0;
  123044. pCsr->zToken = 0;
  123045. pCsr->nToken = 0;
  123046. pCsr->iStart = 0;
  123047. pCsr->iEnd = 0;
  123048. pCsr->iPos = 0;
  123049. pCsr->iRowid = 0;
  123050. }
  123051. /*
  123052. ** xClose - Close a cursor.
  123053. */
  123054. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  123055. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  123056. fts3tokResetCursor(pCsr);
  123057. sqlite3_free(pCsr);
  123058. return SQLITE_OK;
  123059. }
  123060. /*
  123061. ** xNext - Advance the cursor to the next row, if any.
  123062. */
  123063. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  123064. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  123065. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  123066. int rc; /* Return code */
  123067. pCsr->iRowid++;
  123068. rc = pTab->pMod->xNext(pCsr->pCsr,
  123069. &pCsr->zToken, &pCsr->nToken,
  123070. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  123071. );
  123072. if( rc!=SQLITE_OK ){
  123073. fts3tokResetCursor(pCsr);
  123074. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  123075. }
  123076. return rc;
  123077. }
  123078. /*
  123079. ** xFilter - Initialize a cursor to point at the start of its data.
  123080. */
  123081. static int fts3tokFilterMethod(
  123082. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  123083. int idxNum, /* Strategy index */
  123084. const char *idxStr, /* Unused */
  123085. int nVal, /* Number of elements in apVal */
  123086. sqlite3_value **apVal /* Arguments for the indexing scheme */
  123087. ){
  123088. int rc = SQLITE_ERROR;
  123089. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  123090. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  123091. UNUSED_PARAMETER(idxStr);
  123092. UNUSED_PARAMETER(nVal);
  123093. fts3tokResetCursor(pCsr);
  123094. if( idxNum==1 ){
  123095. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  123096. int nByte = sqlite3_value_bytes(apVal[0]);
  123097. pCsr->zInput = sqlite3_malloc(nByte+1);
  123098. if( pCsr->zInput==0 ){
  123099. rc = SQLITE_NOMEM;
  123100. }else{
  123101. memcpy(pCsr->zInput, zByte, nByte);
  123102. pCsr->zInput[nByte] = 0;
  123103. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  123104. if( rc==SQLITE_OK ){
  123105. pCsr->pCsr->pTokenizer = pTab->pTok;
  123106. }
  123107. }
  123108. }
  123109. if( rc!=SQLITE_OK ) return rc;
  123110. return fts3tokNextMethod(pCursor);
  123111. }
  123112. /*
  123113. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  123114. */
  123115. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  123116. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  123117. return (pCsr->zToken==0);
  123118. }
  123119. /*
  123120. ** xColumn - Return a column value.
  123121. */
  123122. static int fts3tokColumnMethod(
  123123. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  123124. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  123125. int iCol /* Index of column to read value from */
  123126. ){
  123127. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  123128. /* CREATE TABLE x(input, token, start, end, position) */
  123129. switch( iCol ){
  123130. case 0:
  123131. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  123132. break;
  123133. case 1:
  123134. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  123135. break;
  123136. case 2:
  123137. sqlite3_result_int(pCtx, pCsr->iStart);
  123138. break;
  123139. case 3:
  123140. sqlite3_result_int(pCtx, pCsr->iEnd);
  123141. break;
  123142. default:
  123143. assert( iCol==4 );
  123144. sqlite3_result_int(pCtx, pCsr->iPos);
  123145. break;
  123146. }
  123147. return SQLITE_OK;
  123148. }
  123149. /*
  123150. ** xRowid - Return the current rowid for the cursor.
  123151. */
  123152. static int fts3tokRowidMethod(
  123153. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  123154. sqlite_int64 *pRowid /* OUT: Rowid value */
  123155. ){
  123156. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  123157. *pRowid = (sqlite3_int64)pCsr->iRowid;
  123158. return SQLITE_OK;
  123159. }
  123160. /*
  123161. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  123162. ** if successful or an error code if sqlite3_create_module() fails.
  123163. */
  123164. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  123165. static const sqlite3_module fts3tok_module = {
  123166. 0, /* iVersion */
  123167. fts3tokConnectMethod, /* xCreate */
  123168. fts3tokConnectMethod, /* xConnect */
  123169. fts3tokBestIndexMethod, /* xBestIndex */
  123170. fts3tokDisconnectMethod, /* xDisconnect */
  123171. fts3tokDisconnectMethod, /* xDestroy */
  123172. fts3tokOpenMethod, /* xOpen */
  123173. fts3tokCloseMethod, /* xClose */
  123174. fts3tokFilterMethod, /* xFilter */
  123175. fts3tokNextMethod, /* xNext */
  123176. fts3tokEofMethod, /* xEof */
  123177. fts3tokColumnMethod, /* xColumn */
  123178. fts3tokRowidMethod, /* xRowid */
  123179. 0, /* xUpdate */
  123180. 0, /* xBegin */
  123181. 0, /* xSync */
  123182. 0, /* xCommit */
  123183. 0, /* xRollback */
  123184. 0, /* xFindFunction */
  123185. 0, /* xRename */
  123186. 0, /* xSavepoint */
  123187. 0, /* xRelease */
  123188. 0 /* xRollbackTo */
  123189. };
  123190. int rc; /* Return code */
  123191. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  123192. return rc;
  123193. }
  123194. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  123195. /************** End of fts3_tokenize_vtab.c **********************************/
  123196. /************** Begin file fts3_write.c **************************************/
  123197. /*
  123198. ** 2009 Oct 23
  123199. **
  123200. ** The author disclaims copyright to this source code. In place of
  123201. ** a legal notice, here is a blessing:
  123202. **
  123203. ** May you do good and not evil.
  123204. ** May you find forgiveness for yourself and forgive others.
  123205. ** May you share freely, never taking more than you give.
  123206. **
  123207. ******************************************************************************
  123208. **
  123209. ** This file is part of the SQLite FTS3 extension module. Specifically,
  123210. ** this file contains code to insert, update and delete rows from FTS3
  123211. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  123212. ** of the sub-routines used to merge segments are also used by the query
  123213. ** code in fts3.c.
  123214. */
  123215. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  123216. /* #include <string.h> */
  123217. /* #include <assert.h> */
  123218. /* #include <stdlib.h> */
  123219. #define FTS_MAX_APPENDABLE_HEIGHT 16
  123220. /*
  123221. ** When full-text index nodes are loaded from disk, the buffer that they
  123222. ** are loaded into has the following number of bytes of padding at the end
  123223. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  123224. ** of 920 bytes is allocated for it.
  123225. **
  123226. ** This means that if we have a pointer into a buffer containing node data,
  123227. ** it is always safe to read up to two varints from it without risking an
  123228. ** overread, even if the node data is corrupted.
  123229. */
  123230. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  123231. /*
  123232. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  123233. ** memory incrementally instead of all at once. This can be a big performance
  123234. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  123235. ** method before retrieving all query results (as may happen, for example,
  123236. ** if a query has a LIMIT clause).
  123237. **
  123238. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  123239. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  123240. ** The code is written so that the hard lower-limit for each of these values
  123241. ** is 1. Clearly such small values would be inefficient, but can be useful
  123242. ** for testing purposes.
  123243. **
  123244. ** If this module is built with SQLITE_TEST defined, these constants may
  123245. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  123246. ** a Tcl interface to read and write the values.
  123247. */
  123248. #ifdef SQLITE_TEST
  123249. int test_fts3_node_chunksize = (4*1024);
  123250. int test_fts3_node_chunk_threshold = (4*1024)*4;
  123251. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  123252. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  123253. #else
  123254. # define FTS3_NODE_CHUNKSIZE (4*1024)
  123255. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  123256. #endif
  123257. /*
  123258. ** The two values that may be meaningfully bound to the :1 parameter in
  123259. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  123260. */
  123261. #define FTS_STAT_DOCTOTAL 0
  123262. #define FTS_STAT_INCRMERGEHINT 1
  123263. #define FTS_STAT_AUTOINCRMERGE 2
  123264. /*
  123265. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  123266. ** and incremental merge operation that takes place. This is used for
  123267. ** debugging FTS only, it should not usually be turned on in production
  123268. ** systems.
  123269. */
  123270. #ifdef FTS3_LOG_MERGES
  123271. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  123272. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  123273. }
  123274. #else
  123275. #define fts3LogMerge(x, y)
  123276. #endif
  123277. typedef struct PendingList PendingList;
  123278. typedef struct SegmentNode SegmentNode;
  123279. typedef struct SegmentWriter SegmentWriter;
  123280. /*
  123281. ** An instance of the following data structure is used to build doclists
  123282. ** incrementally. See function fts3PendingListAppend() for details.
  123283. */
  123284. struct PendingList {
  123285. int nData;
  123286. char *aData;
  123287. int nSpace;
  123288. sqlite3_int64 iLastDocid;
  123289. sqlite3_int64 iLastCol;
  123290. sqlite3_int64 iLastPos;
  123291. };
  123292. /*
  123293. ** Each cursor has a (possibly empty) linked list of the following objects.
  123294. */
  123295. struct Fts3DeferredToken {
  123296. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  123297. int iCol; /* Column token must occur in */
  123298. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  123299. PendingList *pList; /* Doclist is assembled here */
  123300. };
  123301. /*
  123302. ** An instance of this structure is used to iterate through the terms on
  123303. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  123304. ** this structure are only manipulated by code in this file, opaque handles
  123305. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  123306. ** terms when querying the full-text index. See functions:
  123307. **
  123308. ** sqlite3Fts3SegReaderNew()
  123309. ** sqlite3Fts3SegReaderFree()
  123310. ** sqlite3Fts3SegReaderIterate()
  123311. **
  123312. ** Methods used to manipulate Fts3SegReader structures:
  123313. **
  123314. ** fts3SegReaderNext()
  123315. ** fts3SegReaderFirstDocid()
  123316. ** fts3SegReaderNextDocid()
  123317. */
  123318. struct Fts3SegReader {
  123319. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  123320. u8 bLookup; /* True for a lookup only */
  123321. u8 rootOnly; /* True for a root-only reader */
  123322. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  123323. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  123324. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  123325. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  123326. char *aNode; /* Pointer to node data (or NULL) */
  123327. int nNode; /* Size of buffer at aNode (or 0) */
  123328. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  123329. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  123330. Fts3HashElem **ppNextElem;
  123331. /* Variables set by fts3SegReaderNext(). These may be read directly
  123332. ** by the caller. They are valid from the time SegmentReaderNew() returns
  123333. ** until SegmentReaderNext() returns something other than SQLITE_OK
  123334. ** (i.e. SQLITE_DONE).
  123335. */
  123336. int nTerm; /* Number of bytes in current term */
  123337. char *zTerm; /* Pointer to current term */
  123338. int nTermAlloc; /* Allocated size of zTerm buffer */
  123339. char *aDoclist; /* Pointer to doclist of current entry */
  123340. int nDoclist; /* Size of doclist in current entry */
  123341. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  123342. ** through the current doclist (aDoclist/nDoclist).
  123343. */
  123344. char *pOffsetList;
  123345. int nOffsetList; /* For descending pending seg-readers only */
  123346. sqlite3_int64 iDocid;
  123347. };
  123348. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  123349. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  123350. /*
  123351. ** An instance of this structure is used to create a segment b-tree in the
  123352. ** database. The internal details of this type are only accessed by the
  123353. ** following functions:
  123354. **
  123355. ** fts3SegWriterAdd()
  123356. ** fts3SegWriterFlush()
  123357. ** fts3SegWriterFree()
  123358. */
  123359. struct SegmentWriter {
  123360. SegmentNode *pTree; /* Pointer to interior tree structure */
  123361. sqlite3_int64 iFirst; /* First slot in %_segments written */
  123362. sqlite3_int64 iFree; /* Next free slot in %_segments */
  123363. char *zTerm; /* Pointer to previous term buffer */
  123364. int nTerm; /* Number of bytes in zTerm */
  123365. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  123366. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  123367. int nSize; /* Size of allocation at aData */
  123368. int nData; /* Bytes of data in aData */
  123369. char *aData; /* Pointer to block from malloc() */
  123370. };
  123371. /*
  123372. ** Type SegmentNode is used by the following three functions to create
  123373. ** the interior part of the segment b+-tree structures (everything except
  123374. ** the leaf nodes). These functions and type are only ever used by code
  123375. ** within the fts3SegWriterXXX() family of functions described above.
  123376. **
  123377. ** fts3NodeAddTerm()
  123378. ** fts3NodeWrite()
  123379. ** fts3NodeFree()
  123380. **
  123381. ** When a b+tree is written to the database (either as a result of a merge
  123382. ** or the pending-terms table being flushed), leaves are written into the
  123383. ** database file as soon as they are completely populated. The interior of
  123384. ** the tree is assembled in memory and written out only once all leaves have
  123385. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  123386. ** very large, meaning that the interior of the tree consumes relatively
  123387. ** little memory.
  123388. */
  123389. struct SegmentNode {
  123390. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  123391. SegmentNode *pRight; /* Pointer to right-sibling */
  123392. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  123393. int nEntry; /* Number of terms written to node so far */
  123394. char *zTerm; /* Pointer to previous term buffer */
  123395. int nTerm; /* Number of bytes in zTerm */
  123396. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  123397. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  123398. int nData; /* Bytes of valid data so far */
  123399. char *aData; /* Node data */
  123400. };
  123401. /*
  123402. ** Valid values for the second argument to fts3SqlStmt().
  123403. */
  123404. #define SQL_DELETE_CONTENT 0
  123405. #define SQL_IS_EMPTY 1
  123406. #define SQL_DELETE_ALL_CONTENT 2
  123407. #define SQL_DELETE_ALL_SEGMENTS 3
  123408. #define SQL_DELETE_ALL_SEGDIR 4
  123409. #define SQL_DELETE_ALL_DOCSIZE 5
  123410. #define SQL_DELETE_ALL_STAT 6
  123411. #define SQL_SELECT_CONTENT_BY_ROWID 7
  123412. #define SQL_NEXT_SEGMENT_INDEX 8
  123413. #define SQL_INSERT_SEGMENTS 9
  123414. #define SQL_NEXT_SEGMENTS_ID 10
  123415. #define SQL_INSERT_SEGDIR 11
  123416. #define SQL_SELECT_LEVEL 12
  123417. #define SQL_SELECT_LEVEL_RANGE 13
  123418. #define SQL_SELECT_LEVEL_COUNT 14
  123419. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  123420. #define SQL_DELETE_SEGDIR_LEVEL 16
  123421. #define SQL_DELETE_SEGMENTS_RANGE 17
  123422. #define SQL_CONTENT_INSERT 18
  123423. #define SQL_DELETE_DOCSIZE 19
  123424. #define SQL_REPLACE_DOCSIZE 20
  123425. #define SQL_SELECT_DOCSIZE 21
  123426. #define SQL_SELECT_STAT 22
  123427. #define SQL_REPLACE_STAT 23
  123428. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  123429. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  123430. #define SQL_DELETE_SEGDIR_RANGE 26
  123431. #define SQL_SELECT_ALL_LANGID 27
  123432. #define SQL_FIND_MERGE_LEVEL 28
  123433. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  123434. #define SQL_DELETE_SEGDIR_ENTRY 30
  123435. #define SQL_SHIFT_SEGDIR_ENTRY 31
  123436. #define SQL_SELECT_SEGDIR 32
  123437. #define SQL_CHOMP_SEGDIR 33
  123438. #define SQL_SEGMENT_IS_APPENDABLE 34
  123439. #define SQL_SELECT_INDEXES 35
  123440. #define SQL_SELECT_MXLEVEL 36
  123441. /*
  123442. ** This function is used to obtain an SQLite prepared statement handle
  123443. ** for the statement identified by the second argument. If successful,
  123444. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  123445. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  123446. **
  123447. ** If argument apVal is not NULL, then it must point to an array with
  123448. ** at least as many entries as the requested statement has bound
  123449. ** parameters. The values are bound to the statements parameters before
  123450. ** returning.
  123451. */
  123452. static int fts3SqlStmt(
  123453. Fts3Table *p, /* Virtual table handle */
  123454. int eStmt, /* One of the SQL_XXX constants above */
  123455. sqlite3_stmt **pp, /* OUT: Statement handle */
  123456. sqlite3_value **apVal /* Values to bind to statement */
  123457. ){
  123458. const char *azSql[] = {
  123459. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  123460. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  123461. /* 2 */ "DELETE FROM %Q.'%q_content'",
  123462. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  123463. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  123464. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  123465. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  123466. /* 7 */ "SELECT %s WHERE rowid=?",
  123467. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  123468. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  123469. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  123470. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  123471. /* Return segments in order from oldest to newest.*/
  123472. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  123473. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  123474. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  123475. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  123476. "ORDER BY level DESC, idx ASC",
  123477. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  123478. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  123479. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  123480. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  123481. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  123482. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  123483. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  123484. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  123485. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  123486. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  123487. /* 24 */ "",
  123488. /* 25 */ "",
  123489. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  123490. /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
  123491. /* This statement is used to determine which level to read the input from
  123492. ** when performing an incremental merge. It returns the absolute level number
  123493. ** of the oldest level in the db that contains at least ? segments. Or,
  123494. ** if no level in the FTS index contains more than ? segments, the statement
  123495. ** returns zero rows. */
  123496. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  123497. " ORDER BY (level %% 1024) ASC LIMIT 1",
  123498. /* Estimate the upper limit on the number of leaf nodes in a new segment
  123499. ** created by merging the oldest :2 segments from absolute level :1. See
  123500. ** function sqlite3Fts3Incrmerge() for details. */
  123501. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  123502. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  123503. /* SQL_DELETE_SEGDIR_ENTRY
  123504. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  123505. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  123506. /* SQL_SHIFT_SEGDIR_ENTRY
  123507. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  123508. ** to :1. */
  123509. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  123510. /* SQL_SELECT_SEGDIR
  123511. ** Read a single entry from the %_segdir table. The entry from absolute
  123512. ** level :1 with index value :2. */
  123513. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  123514. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  123515. /* SQL_CHOMP_SEGDIR
  123516. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  123517. ** entry located on absolute level :3 with index :4. */
  123518. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  123519. "WHERE level = ? AND idx = ?",
  123520. /* SQL_SEGMENT_IS_APPENDABLE
  123521. ** Return a single row if the segment with end_block=? is appendable. Or
  123522. ** no rows otherwise. */
  123523. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  123524. /* SQL_SELECT_INDEXES
  123525. ** Return the list of valid segment indexes for absolute level ? */
  123526. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  123527. /* SQL_SELECT_MXLEVEL
  123528. ** Return the largest relative level in the FTS index or indexes. */
  123529. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
  123530. };
  123531. int rc = SQLITE_OK;
  123532. sqlite3_stmt *pStmt;
  123533. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  123534. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  123535. pStmt = p->aStmt[eStmt];
  123536. if( !pStmt ){
  123537. char *zSql;
  123538. if( eStmt==SQL_CONTENT_INSERT ){
  123539. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  123540. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  123541. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  123542. }else{
  123543. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  123544. }
  123545. if( !zSql ){
  123546. rc = SQLITE_NOMEM;
  123547. }else{
  123548. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  123549. sqlite3_free(zSql);
  123550. assert( rc==SQLITE_OK || pStmt==0 );
  123551. p->aStmt[eStmt] = pStmt;
  123552. }
  123553. }
  123554. if( apVal ){
  123555. int i;
  123556. int nParam = sqlite3_bind_parameter_count(pStmt);
  123557. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  123558. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  123559. }
  123560. }
  123561. *pp = pStmt;
  123562. return rc;
  123563. }
  123564. static int fts3SelectDocsize(
  123565. Fts3Table *pTab, /* FTS3 table handle */
  123566. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  123567. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  123568. ){
  123569. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  123570. int rc; /* Return code */
  123571. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  123572. if( rc==SQLITE_OK ){
  123573. sqlite3_bind_int64(pStmt, 1, iDocid);
  123574. rc = sqlite3_step(pStmt);
  123575. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  123576. rc = sqlite3_reset(pStmt);
  123577. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  123578. pStmt = 0;
  123579. }else{
  123580. rc = SQLITE_OK;
  123581. }
  123582. }
  123583. *ppStmt = pStmt;
  123584. return rc;
  123585. }
  123586. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  123587. Fts3Table *pTab, /* Fts3 table handle */
  123588. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  123589. ){
  123590. sqlite3_stmt *pStmt = 0;
  123591. int rc;
  123592. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  123593. if( rc==SQLITE_OK ){
  123594. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  123595. if( sqlite3_step(pStmt)!=SQLITE_ROW
  123596. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  123597. ){
  123598. rc = sqlite3_reset(pStmt);
  123599. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  123600. pStmt = 0;
  123601. }
  123602. }
  123603. *ppStmt = pStmt;
  123604. return rc;
  123605. }
  123606. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  123607. Fts3Table *pTab, /* Fts3 table handle */
  123608. sqlite3_int64 iDocid, /* Docid to read size data for */
  123609. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  123610. ){
  123611. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  123612. }
  123613. /*
  123614. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  123615. ** array apVal[] to the SQL statement identified by eStmt, the statement
  123616. ** is executed.
  123617. **
  123618. ** Returns SQLITE_OK if the statement is successfully executed, or an
  123619. ** SQLite error code otherwise.
  123620. */
  123621. static void fts3SqlExec(
  123622. int *pRC, /* Result code */
  123623. Fts3Table *p, /* The FTS3 table */
  123624. int eStmt, /* Index of statement to evaluate */
  123625. sqlite3_value **apVal /* Parameters to bind */
  123626. ){
  123627. sqlite3_stmt *pStmt;
  123628. int rc;
  123629. if( *pRC ) return;
  123630. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  123631. if( rc==SQLITE_OK ){
  123632. sqlite3_step(pStmt);
  123633. rc = sqlite3_reset(pStmt);
  123634. }
  123635. *pRC = rc;
  123636. }
  123637. /*
  123638. ** This function ensures that the caller has obtained an exclusive
  123639. ** shared-cache table-lock on the %_segdir table. This is required before
  123640. ** writing data to the fts3 table. If this lock is not acquired first, then
  123641. ** the caller may end up attempting to take this lock as part of committing
  123642. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  123643. ** LOCKED_SHAREDCACHEto a COMMIT command.
  123644. **
  123645. ** It is best to avoid this because if FTS3 returns any error when
  123646. ** committing a transaction, the whole transaction will be rolled back.
  123647. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  123648. ** It can still happen if the user locks the underlying tables directly
  123649. ** instead of accessing them via FTS.
  123650. */
  123651. static int fts3Writelock(Fts3Table *p){
  123652. int rc = SQLITE_OK;
  123653. if( p->nPendingData==0 ){
  123654. sqlite3_stmt *pStmt;
  123655. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  123656. if( rc==SQLITE_OK ){
  123657. sqlite3_bind_null(pStmt, 1);
  123658. sqlite3_step(pStmt);
  123659. rc = sqlite3_reset(pStmt);
  123660. }
  123661. }
  123662. return rc;
  123663. }
  123664. /*
  123665. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  123666. ** Within each language id, a separate index is maintained to store the
  123667. ** document terms, and each configured prefix size (configured the FTS
  123668. ** "prefix=" option). And each index consists of multiple levels ("relative
  123669. ** levels").
  123670. **
  123671. ** All three of these values (the language id, the specific index and the
  123672. ** level within the index) are encoded in 64-bit integer values stored
  123673. ** in the %_segdir table on disk. This function is used to convert three
  123674. ** separate component values into the single 64-bit integer value that
  123675. ** can be used to query the %_segdir table.
  123676. **
  123677. ** Specifically, each language-id/index combination is allocated 1024
  123678. ** 64-bit integer level values ("absolute levels"). The main terms index
  123679. ** for language-id 0 is allocate values 0-1023. The first prefix index
  123680. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  123681. ** Language 1 indexes are allocated immediately following language 0.
  123682. **
  123683. ** So, for a system with nPrefix prefix indexes configured, the block of
  123684. ** absolute levels that corresponds to language-id iLangid and index
  123685. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  123686. */
  123687. static sqlite3_int64 getAbsoluteLevel(
  123688. Fts3Table *p, /* FTS3 table handle */
  123689. int iLangid, /* Language id */
  123690. int iIndex, /* Index in p->aIndex[] */
  123691. int iLevel /* Level of segments */
  123692. ){
  123693. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  123694. assert( iLangid>=0 );
  123695. assert( p->nIndex>0 );
  123696. assert( iIndex>=0 && iIndex<p->nIndex );
  123697. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  123698. return iBase + iLevel;
  123699. }
  123700. /*
  123701. ** Set *ppStmt to a statement handle that may be used to iterate through
  123702. ** all rows in the %_segdir table, from oldest to newest. If successful,
  123703. ** return SQLITE_OK. If an error occurs while preparing the statement,
  123704. ** return an SQLite error code.
  123705. **
  123706. ** There is only ever one instance of this SQL statement compiled for
  123707. ** each FTS3 table.
  123708. **
  123709. ** The statement returns the following columns from the %_segdir table:
  123710. **
  123711. ** 0: idx
  123712. ** 1: start_block
  123713. ** 2: leaves_end_block
  123714. ** 3: end_block
  123715. ** 4: root
  123716. */
  123717. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  123718. Fts3Table *p, /* FTS3 table */
  123719. int iLangid, /* Language being queried */
  123720. int iIndex, /* Index for p->aIndex[] */
  123721. int iLevel, /* Level to select (relative level) */
  123722. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  123723. ){
  123724. int rc;
  123725. sqlite3_stmt *pStmt = 0;
  123726. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  123727. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  123728. assert( iIndex>=0 && iIndex<p->nIndex );
  123729. if( iLevel<0 ){
  123730. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  123731. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  123732. if( rc==SQLITE_OK ){
  123733. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  123734. sqlite3_bind_int64(pStmt, 2,
  123735. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  123736. );
  123737. }
  123738. }else{
  123739. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  123740. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  123741. if( rc==SQLITE_OK ){
  123742. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  123743. }
  123744. }
  123745. *ppStmt = pStmt;
  123746. return rc;
  123747. }
  123748. /*
  123749. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  123750. ** if successful, or an SQLite error code otherwise.
  123751. **
  123752. ** This function also serves to allocate the PendingList structure itself.
  123753. ** For example, to create a new PendingList structure containing two
  123754. ** varints:
  123755. **
  123756. ** PendingList *p = 0;
  123757. ** fts3PendingListAppendVarint(&p, 1);
  123758. ** fts3PendingListAppendVarint(&p, 2);
  123759. */
  123760. static int fts3PendingListAppendVarint(
  123761. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  123762. sqlite3_int64 i /* Value to append to data */
  123763. ){
  123764. PendingList *p = *pp;
  123765. /* Allocate or grow the PendingList as required. */
  123766. if( !p ){
  123767. p = sqlite3_malloc(sizeof(*p) + 100);
  123768. if( !p ){
  123769. return SQLITE_NOMEM;
  123770. }
  123771. p->nSpace = 100;
  123772. p->aData = (char *)&p[1];
  123773. p->nData = 0;
  123774. }
  123775. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  123776. int nNew = p->nSpace * 2;
  123777. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  123778. if( !p ){
  123779. sqlite3_free(*pp);
  123780. *pp = 0;
  123781. return SQLITE_NOMEM;
  123782. }
  123783. p->nSpace = nNew;
  123784. p->aData = (char *)&p[1];
  123785. }
  123786. /* Append the new serialized varint to the end of the list. */
  123787. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  123788. p->aData[p->nData] = '\0';
  123789. *pp = p;
  123790. return SQLITE_OK;
  123791. }
  123792. /*
  123793. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  123794. ** is returned if the structure is sqlite3_realloced as part of adding
  123795. ** the entry. Otherwise, zero.
  123796. **
  123797. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  123798. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  123799. ** it is set to SQLITE_OK.
  123800. */
  123801. static int fts3PendingListAppend(
  123802. PendingList **pp, /* IN/OUT: PendingList structure */
  123803. sqlite3_int64 iDocid, /* Docid for entry to add */
  123804. sqlite3_int64 iCol, /* Column for entry to add */
  123805. sqlite3_int64 iPos, /* Position of term for entry to add */
  123806. int *pRc /* OUT: Return code */
  123807. ){
  123808. PendingList *p = *pp;
  123809. int rc = SQLITE_OK;
  123810. assert( !p || p->iLastDocid<=iDocid );
  123811. if( !p || p->iLastDocid!=iDocid ){
  123812. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  123813. if( p ){
  123814. assert( p->nData<p->nSpace );
  123815. assert( p->aData[p->nData]==0 );
  123816. p->nData++;
  123817. }
  123818. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  123819. goto pendinglistappend_out;
  123820. }
  123821. p->iLastCol = -1;
  123822. p->iLastPos = 0;
  123823. p->iLastDocid = iDocid;
  123824. }
  123825. if( iCol>0 && p->iLastCol!=iCol ){
  123826. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  123827. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  123828. ){
  123829. goto pendinglistappend_out;
  123830. }
  123831. p->iLastCol = iCol;
  123832. p->iLastPos = 0;
  123833. }
  123834. if( iCol>=0 ){
  123835. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  123836. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  123837. if( rc==SQLITE_OK ){
  123838. p->iLastPos = iPos;
  123839. }
  123840. }
  123841. pendinglistappend_out:
  123842. *pRc = rc;
  123843. if( p!=*pp ){
  123844. *pp = p;
  123845. return 1;
  123846. }
  123847. return 0;
  123848. }
  123849. /*
  123850. ** Free a PendingList object allocated by fts3PendingListAppend().
  123851. */
  123852. static void fts3PendingListDelete(PendingList *pList){
  123853. sqlite3_free(pList);
  123854. }
  123855. /*
  123856. ** Add an entry to one of the pending-terms hash tables.
  123857. */
  123858. static int fts3PendingTermsAddOne(
  123859. Fts3Table *p,
  123860. int iCol,
  123861. int iPos,
  123862. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  123863. const char *zToken,
  123864. int nToken
  123865. ){
  123866. PendingList *pList;
  123867. int rc = SQLITE_OK;
  123868. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  123869. if( pList ){
  123870. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  123871. }
  123872. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  123873. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  123874. /* Malloc failed while inserting the new entry. This can only
  123875. ** happen if there was no previous entry for this token.
  123876. */
  123877. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  123878. sqlite3_free(pList);
  123879. rc = SQLITE_NOMEM;
  123880. }
  123881. }
  123882. if( rc==SQLITE_OK ){
  123883. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  123884. }
  123885. return rc;
  123886. }
  123887. /*
  123888. ** Tokenize the nul-terminated string zText and add all tokens to the
  123889. ** pending-terms hash-table. The docid used is that currently stored in
  123890. ** p->iPrevDocid, and the column is specified by argument iCol.
  123891. **
  123892. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  123893. */
  123894. static int fts3PendingTermsAdd(
  123895. Fts3Table *p, /* Table into which text will be inserted */
  123896. int iLangid, /* Language id to use */
  123897. const char *zText, /* Text of document to be inserted */
  123898. int iCol, /* Column into which text is being inserted */
  123899. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  123900. ){
  123901. int rc;
  123902. int iStart = 0;
  123903. int iEnd = 0;
  123904. int iPos = 0;
  123905. int nWord = 0;
  123906. char const *zToken;
  123907. int nToken = 0;
  123908. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  123909. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  123910. sqlite3_tokenizer_cursor *pCsr;
  123911. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  123912. const char**,int*,int*,int*,int*);
  123913. assert( pTokenizer && pModule );
  123914. /* If the user has inserted a NULL value, this function may be called with
  123915. ** zText==0. In this case, add zero token entries to the hash table and
  123916. ** return early. */
  123917. if( zText==0 ){
  123918. *pnWord = 0;
  123919. return SQLITE_OK;
  123920. }
  123921. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  123922. if( rc!=SQLITE_OK ){
  123923. return rc;
  123924. }
  123925. xNext = pModule->xNext;
  123926. while( SQLITE_OK==rc
  123927. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  123928. ){
  123929. int i;
  123930. if( iPos>=nWord ) nWord = iPos+1;
  123931. /* Positions cannot be negative; we use -1 as a terminator internally.
  123932. ** Tokens must have a non-zero length.
  123933. */
  123934. if( iPos<0 || !zToken || nToken<=0 ){
  123935. rc = SQLITE_ERROR;
  123936. break;
  123937. }
  123938. /* Add the term to the terms index */
  123939. rc = fts3PendingTermsAddOne(
  123940. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  123941. );
  123942. /* Add the term to each of the prefix indexes that it is not too
  123943. ** short for. */
  123944. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  123945. struct Fts3Index *pIndex = &p->aIndex[i];
  123946. if( nToken<pIndex->nPrefix ) continue;
  123947. rc = fts3PendingTermsAddOne(
  123948. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  123949. );
  123950. }
  123951. }
  123952. pModule->xClose(pCsr);
  123953. *pnWord += nWord;
  123954. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  123955. }
  123956. /*
  123957. ** Calling this function indicates that subsequent calls to
  123958. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  123959. ** contents of the document with docid iDocid.
  123960. */
  123961. static int fts3PendingTermsDocid(
  123962. Fts3Table *p, /* Full-text table handle */
  123963. int iLangid, /* Language id of row being written */
  123964. sqlite_int64 iDocid /* Docid of row being written */
  123965. ){
  123966. assert( iLangid>=0 );
  123967. /* TODO(shess) Explore whether partially flushing the buffer on
  123968. ** forced-flush would provide better performance. I suspect that if
  123969. ** we ordered the doclists by size and flushed the largest until the
  123970. ** buffer was half empty, that would let the less frequent terms
  123971. ** generate longer doclists.
  123972. */
  123973. if( iDocid<=p->iPrevDocid
  123974. || p->iPrevLangid!=iLangid
  123975. || p->nPendingData>p->nMaxPendingData
  123976. ){
  123977. int rc = sqlite3Fts3PendingTermsFlush(p);
  123978. if( rc!=SQLITE_OK ) return rc;
  123979. }
  123980. p->iPrevDocid = iDocid;
  123981. p->iPrevLangid = iLangid;
  123982. return SQLITE_OK;
  123983. }
  123984. /*
  123985. ** Discard the contents of the pending-terms hash tables.
  123986. */
  123987. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  123988. int i;
  123989. for(i=0; i<p->nIndex; i++){
  123990. Fts3HashElem *pElem;
  123991. Fts3Hash *pHash = &p->aIndex[i].hPending;
  123992. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  123993. PendingList *pList = (PendingList *)fts3HashData(pElem);
  123994. fts3PendingListDelete(pList);
  123995. }
  123996. fts3HashClear(pHash);
  123997. }
  123998. p->nPendingData = 0;
  123999. }
  124000. /*
  124001. ** This function is called by the xUpdate() method as part of an INSERT
  124002. ** operation. It adds entries for each term in the new record to the
  124003. ** pendingTerms hash table.
  124004. **
  124005. ** Argument apVal is the same as the similarly named argument passed to
  124006. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  124007. */
  124008. static int fts3InsertTerms(
  124009. Fts3Table *p,
  124010. int iLangid,
  124011. sqlite3_value **apVal,
  124012. u32 *aSz
  124013. ){
  124014. int i; /* Iterator variable */
  124015. for(i=2; i<p->nColumn+2; i++){
  124016. int iCol = i-2;
  124017. if( p->abNotindexed[iCol]==0 ){
  124018. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  124019. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  124020. if( rc!=SQLITE_OK ){
  124021. return rc;
  124022. }
  124023. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  124024. }
  124025. }
  124026. return SQLITE_OK;
  124027. }
  124028. /*
  124029. ** This function is called by the xUpdate() method for an INSERT operation.
  124030. ** The apVal parameter is passed a copy of the apVal argument passed by
  124031. ** SQLite to the xUpdate() method. i.e:
  124032. **
  124033. ** apVal[0] Not used for INSERT.
  124034. ** apVal[1] rowid
  124035. ** apVal[2] Left-most user-defined column
  124036. ** ...
  124037. ** apVal[p->nColumn+1] Right-most user-defined column
  124038. ** apVal[p->nColumn+2] Hidden column with same name as table
  124039. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  124040. ** apVal[p->nColumn+4] Hidden languageid column
  124041. */
  124042. static int fts3InsertData(
  124043. Fts3Table *p, /* Full-text table */
  124044. sqlite3_value **apVal, /* Array of values to insert */
  124045. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  124046. ){
  124047. int rc; /* Return code */
  124048. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  124049. if( p->zContentTbl ){
  124050. sqlite3_value *pRowid = apVal[p->nColumn+3];
  124051. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  124052. pRowid = apVal[1];
  124053. }
  124054. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  124055. return SQLITE_CONSTRAINT;
  124056. }
  124057. *piDocid = sqlite3_value_int64(pRowid);
  124058. return SQLITE_OK;
  124059. }
  124060. /* Locate the statement handle used to insert data into the %_content
  124061. ** table. The SQL for this statement is:
  124062. **
  124063. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  124064. **
  124065. ** The statement features N '?' variables, where N is the number of user
  124066. ** defined columns in the FTS3 table, plus one for the docid field.
  124067. */
  124068. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  124069. if( rc==SQLITE_OK && p->zLanguageid ){
  124070. rc = sqlite3_bind_int(
  124071. pContentInsert, p->nColumn+2,
  124072. sqlite3_value_int(apVal[p->nColumn+4])
  124073. );
  124074. }
  124075. if( rc!=SQLITE_OK ) return rc;
  124076. /* There is a quirk here. The users INSERT statement may have specified
  124077. ** a value for the "rowid" field, for the "docid" field, or for both.
  124078. ** Which is a problem, since "rowid" and "docid" are aliases for the
  124079. ** same value. For example:
  124080. **
  124081. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  124082. **
  124083. ** In FTS3, this is an error. It is an error to specify non-NULL values
  124084. ** for both docid and some other rowid alias.
  124085. */
  124086. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  124087. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  124088. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  124089. ){
  124090. /* A rowid/docid conflict. */
  124091. return SQLITE_ERROR;
  124092. }
  124093. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  124094. if( rc!=SQLITE_OK ) return rc;
  124095. }
  124096. /* Execute the statement to insert the record. Set *piDocid to the
  124097. ** new docid value.
  124098. */
  124099. sqlite3_step(pContentInsert);
  124100. rc = sqlite3_reset(pContentInsert);
  124101. *piDocid = sqlite3_last_insert_rowid(p->db);
  124102. return rc;
  124103. }
  124104. /*
  124105. ** Remove all data from the FTS3 table. Clear the hash table containing
  124106. ** pending terms.
  124107. */
  124108. static int fts3DeleteAll(Fts3Table *p, int bContent){
  124109. int rc = SQLITE_OK; /* Return code */
  124110. /* Discard the contents of the pending-terms hash table. */
  124111. sqlite3Fts3PendingTermsClear(p);
  124112. /* Delete everything from the shadow tables. Except, leave %_content as
  124113. ** is if bContent is false. */
  124114. assert( p->zContentTbl==0 || bContent==0 );
  124115. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  124116. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  124117. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  124118. if( p->bHasDocsize ){
  124119. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  124120. }
  124121. if( p->bHasStat ){
  124122. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  124123. }
  124124. return rc;
  124125. }
  124126. /*
  124127. **
  124128. */
  124129. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  124130. int iLangid = 0;
  124131. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  124132. return iLangid;
  124133. }
  124134. /*
  124135. ** The first element in the apVal[] array is assumed to contain the docid
  124136. ** (an integer) of a row about to be deleted. Remove all terms from the
  124137. ** full-text index.
  124138. */
  124139. static void fts3DeleteTerms(
  124140. int *pRC, /* Result code */
  124141. Fts3Table *p, /* The FTS table to delete from */
  124142. sqlite3_value *pRowid, /* The docid to be deleted */
  124143. u32 *aSz, /* Sizes of deleted document written here */
  124144. int *pbFound /* OUT: Set to true if row really does exist */
  124145. ){
  124146. int rc;
  124147. sqlite3_stmt *pSelect;
  124148. assert( *pbFound==0 );
  124149. if( *pRC ) return;
  124150. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  124151. if( rc==SQLITE_OK ){
  124152. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  124153. int i;
  124154. int iLangid = langidFromSelect(p, pSelect);
  124155. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
  124156. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  124157. int iCol = i-1;
  124158. if( p->abNotindexed[iCol]==0 ){
  124159. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  124160. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  124161. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  124162. }
  124163. }
  124164. if( rc!=SQLITE_OK ){
  124165. sqlite3_reset(pSelect);
  124166. *pRC = rc;
  124167. return;
  124168. }
  124169. *pbFound = 1;
  124170. }
  124171. rc = sqlite3_reset(pSelect);
  124172. }else{
  124173. sqlite3_reset(pSelect);
  124174. }
  124175. *pRC = rc;
  124176. }
  124177. /*
  124178. ** Forward declaration to account for the circular dependency between
  124179. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  124180. */
  124181. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  124182. /*
  124183. ** This function allocates a new level iLevel index in the segdir table.
  124184. ** Usually, indexes are allocated within a level sequentially starting
  124185. ** with 0, so the allocated index is one greater than the value returned
  124186. ** by:
  124187. **
  124188. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  124189. **
  124190. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  124191. ** level, they are merged into a single level (iLevel+1) segment and the
  124192. ** allocated index is 0.
  124193. **
  124194. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  124195. ** returned. Otherwise, an SQLite error code is returned.
  124196. */
  124197. static int fts3AllocateSegdirIdx(
  124198. Fts3Table *p,
  124199. int iLangid, /* Language id */
  124200. int iIndex, /* Index for p->aIndex */
  124201. int iLevel,
  124202. int *piIdx
  124203. ){
  124204. int rc; /* Return Code */
  124205. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  124206. int iNext = 0; /* Result of query pNextIdx */
  124207. assert( iLangid>=0 );
  124208. assert( p->nIndex>=1 );
  124209. /* Set variable iNext to the next available segdir index at level iLevel. */
  124210. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  124211. if( rc==SQLITE_OK ){
  124212. sqlite3_bind_int64(
  124213. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  124214. );
  124215. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  124216. iNext = sqlite3_column_int(pNextIdx, 0);
  124217. }
  124218. rc = sqlite3_reset(pNextIdx);
  124219. }
  124220. if( rc==SQLITE_OK ){
  124221. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  124222. ** full, merge all segments in level iLevel into a single iLevel+1
  124223. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  124224. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  124225. */
  124226. if( iNext>=FTS3_MERGE_COUNT ){
  124227. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  124228. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  124229. *piIdx = 0;
  124230. }else{
  124231. *piIdx = iNext;
  124232. }
  124233. }
  124234. return rc;
  124235. }
  124236. /*
  124237. ** The %_segments table is declared as follows:
  124238. **
  124239. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  124240. **
  124241. ** This function reads data from a single row of the %_segments table. The
  124242. ** specific row is identified by the iBlockid parameter. If paBlob is not
  124243. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  124244. ** with the contents of the blob stored in the "block" column of the
  124245. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  124246. ** to the size of the blob in bytes before returning.
  124247. **
  124248. ** If an error occurs, or the table does not contain the specified row,
  124249. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  124250. ** paBlob is non-NULL, then it is the responsibility of the caller to
  124251. ** eventually free the returned buffer.
  124252. **
  124253. ** This function may leave an open sqlite3_blob* handle in the
  124254. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  124255. ** to this function. The handle may be closed by calling the
  124256. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  124257. ** performance improvement, but the blob handle should always be closed
  124258. ** before control is returned to the user (to prevent a lock being held
  124259. ** on the database file for longer than necessary). Thus, any virtual table
  124260. ** method (xFilter etc.) that may directly or indirectly call this function
  124261. ** must call sqlite3Fts3SegmentsClose() before returning.
  124262. */
  124263. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  124264. Fts3Table *p, /* FTS3 table handle */
  124265. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  124266. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  124267. int *pnBlob, /* OUT: Size of blob data */
  124268. int *pnLoad /* OUT: Bytes actually loaded */
  124269. ){
  124270. int rc; /* Return code */
  124271. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  124272. assert( pnBlob );
  124273. if( p->pSegments ){
  124274. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  124275. }else{
  124276. if( 0==p->zSegmentsTbl ){
  124277. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  124278. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  124279. }
  124280. rc = sqlite3_blob_open(
  124281. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  124282. );
  124283. }
  124284. if( rc==SQLITE_OK ){
  124285. int nByte = sqlite3_blob_bytes(p->pSegments);
  124286. *pnBlob = nByte;
  124287. if( paBlob ){
  124288. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  124289. if( !aByte ){
  124290. rc = SQLITE_NOMEM;
  124291. }else{
  124292. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  124293. nByte = FTS3_NODE_CHUNKSIZE;
  124294. *pnLoad = nByte;
  124295. }
  124296. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  124297. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  124298. if( rc!=SQLITE_OK ){
  124299. sqlite3_free(aByte);
  124300. aByte = 0;
  124301. }
  124302. }
  124303. *paBlob = aByte;
  124304. }
  124305. }
  124306. return rc;
  124307. }
  124308. /*
  124309. ** Close the blob handle at p->pSegments, if it is open. See comments above
  124310. ** the sqlite3Fts3ReadBlock() function for details.
  124311. */
  124312. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  124313. sqlite3_blob_close(p->pSegments);
  124314. p->pSegments = 0;
  124315. }
  124316. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  124317. int nRead; /* Number of bytes to read */
  124318. int rc; /* Return code */
  124319. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  124320. rc = sqlite3_blob_read(
  124321. pReader->pBlob,
  124322. &pReader->aNode[pReader->nPopulate],
  124323. nRead,
  124324. pReader->nPopulate
  124325. );
  124326. if( rc==SQLITE_OK ){
  124327. pReader->nPopulate += nRead;
  124328. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  124329. if( pReader->nPopulate==pReader->nNode ){
  124330. sqlite3_blob_close(pReader->pBlob);
  124331. pReader->pBlob = 0;
  124332. pReader->nPopulate = 0;
  124333. }
  124334. }
  124335. return rc;
  124336. }
  124337. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  124338. int rc = SQLITE_OK;
  124339. assert( !pReader->pBlob
  124340. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  124341. );
  124342. while( pReader->pBlob && rc==SQLITE_OK
  124343. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  124344. ){
  124345. rc = fts3SegReaderIncrRead(pReader);
  124346. }
  124347. return rc;
  124348. }
  124349. /*
  124350. ** Set an Fts3SegReader cursor to point at EOF.
  124351. */
  124352. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  124353. if( !fts3SegReaderIsRootOnly(pSeg) ){
  124354. sqlite3_free(pSeg->aNode);
  124355. sqlite3_blob_close(pSeg->pBlob);
  124356. pSeg->pBlob = 0;
  124357. }
  124358. pSeg->aNode = 0;
  124359. }
  124360. /*
  124361. ** Move the iterator passed as the first argument to the next term in the
  124362. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  124363. ** SQLITE_DONE. Otherwise, an SQLite error code.
  124364. */
  124365. static int fts3SegReaderNext(
  124366. Fts3Table *p,
  124367. Fts3SegReader *pReader,
  124368. int bIncr
  124369. ){
  124370. int rc; /* Return code of various sub-routines */
  124371. char *pNext; /* Cursor variable */
  124372. int nPrefix; /* Number of bytes in term prefix */
  124373. int nSuffix; /* Number of bytes in term suffix */
  124374. if( !pReader->aDoclist ){
  124375. pNext = pReader->aNode;
  124376. }else{
  124377. pNext = &pReader->aDoclist[pReader->nDoclist];
  124378. }
  124379. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  124380. if( fts3SegReaderIsPending(pReader) ){
  124381. Fts3HashElem *pElem = *(pReader->ppNextElem);
  124382. if( pElem==0 ){
  124383. pReader->aNode = 0;
  124384. }else{
  124385. PendingList *pList = (PendingList *)fts3HashData(pElem);
  124386. pReader->zTerm = (char *)fts3HashKey(pElem);
  124387. pReader->nTerm = fts3HashKeysize(pElem);
  124388. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  124389. pReader->aNode = pReader->aDoclist = pList->aData;
  124390. pReader->ppNextElem++;
  124391. assert( pReader->aNode );
  124392. }
  124393. return SQLITE_OK;
  124394. }
  124395. fts3SegReaderSetEof(pReader);
  124396. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  124397. ** blocks have already been traversed. */
  124398. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  124399. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  124400. return SQLITE_OK;
  124401. }
  124402. rc = sqlite3Fts3ReadBlock(
  124403. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  124404. (bIncr ? &pReader->nPopulate : 0)
  124405. );
  124406. if( rc!=SQLITE_OK ) return rc;
  124407. assert( pReader->pBlob==0 );
  124408. if( bIncr && pReader->nPopulate<pReader->nNode ){
  124409. pReader->pBlob = p->pSegments;
  124410. p->pSegments = 0;
  124411. }
  124412. pNext = pReader->aNode;
  124413. }
  124414. assert( !fts3SegReaderIsPending(pReader) );
  124415. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  124416. if( rc!=SQLITE_OK ) return rc;
  124417. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  124418. ** safe (no risk of overread) even if the node data is corrupted. */
  124419. pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
  124420. pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
  124421. if( nPrefix<0 || nSuffix<=0
  124422. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  124423. ){
  124424. return FTS_CORRUPT_VTAB;
  124425. }
  124426. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  124427. int nNew = (nPrefix+nSuffix)*2;
  124428. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  124429. if( !zNew ){
  124430. return SQLITE_NOMEM;
  124431. }
  124432. pReader->zTerm = zNew;
  124433. pReader->nTermAlloc = nNew;
  124434. }
  124435. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  124436. if( rc!=SQLITE_OK ) return rc;
  124437. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  124438. pReader->nTerm = nPrefix+nSuffix;
  124439. pNext += nSuffix;
  124440. pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
  124441. pReader->aDoclist = pNext;
  124442. pReader->pOffsetList = 0;
  124443. /* Check that the doclist does not appear to extend past the end of the
  124444. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  124445. ** of these statements is untrue, then the data structure is corrupt.
  124446. */
  124447. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  124448. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  124449. ){
  124450. return FTS_CORRUPT_VTAB;
  124451. }
  124452. return SQLITE_OK;
  124453. }
  124454. /*
  124455. ** Set the SegReader to point to the first docid in the doclist associated
  124456. ** with the current term.
  124457. */
  124458. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  124459. int rc = SQLITE_OK;
  124460. assert( pReader->aDoclist );
  124461. assert( !pReader->pOffsetList );
  124462. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  124463. u8 bEof = 0;
  124464. pReader->iDocid = 0;
  124465. pReader->nOffsetList = 0;
  124466. sqlite3Fts3DoclistPrev(0,
  124467. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  124468. &pReader->iDocid, &pReader->nOffsetList, &bEof
  124469. );
  124470. }else{
  124471. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  124472. if( rc==SQLITE_OK ){
  124473. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  124474. pReader->pOffsetList = &pReader->aDoclist[n];
  124475. }
  124476. }
  124477. return rc;
  124478. }
  124479. /*
  124480. ** Advance the SegReader to point to the next docid in the doclist
  124481. ** associated with the current term.
  124482. **
  124483. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  124484. ** *ppOffsetList is set to point to the first column-offset list
  124485. ** in the doclist entry (i.e. immediately past the docid varint).
  124486. ** *pnOffsetList is set to the length of the set of column-offset
  124487. ** lists, not including the nul-terminator byte. For example:
  124488. */
  124489. static int fts3SegReaderNextDocid(
  124490. Fts3Table *pTab,
  124491. Fts3SegReader *pReader, /* Reader to advance to next docid */
  124492. char **ppOffsetList, /* OUT: Pointer to current position-list */
  124493. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  124494. ){
  124495. int rc = SQLITE_OK;
  124496. char *p = pReader->pOffsetList;
  124497. char c = 0;
  124498. assert( p );
  124499. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  124500. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  124501. ** Pending-terms doclists are always built up in ascending order, so
  124502. ** we have to iterate through them backwards here. */
  124503. u8 bEof = 0;
  124504. if( ppOffsetList ){
  124505. *ppOffsetList = pReader->pOffsetList;
  124506. *pnOffsetList = pReader->nOffsetList - 1;
  124507. }
  124508. sqlite3Fts3DoclistPrev(0,
  124509. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  124510. &pReader->nOffsetList, &bEof
  124511. );
  124512. if( bEof ){
  124513. pReader->pOffsetList = 0;
  124514. }else{
  124515. pReader->pOffsetList = p;
  124516. }
  124517. }else{
  124518. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  124519. /* Pointer p currently points at the first byte of an offset list. The
  124520. ** following block advances it to point one byte past the end of
  124521. ** the same offset list. */
  124522. while( 1 ){
  124523. /* The following line of code (and the "p++" below the while() loop) is
  124524. ** normally all that is required to move pointer p to the desired
  124525. ** position. The exception is if this node is being loaded from disk
  124526. ** incrementally and pointer "p" now points to the first byte past
  124527. ** the populated part of pReader->aNode[].
  124528. */
  124529. while( *p | c ) c = *p++ & 0x80;
  124530. assert( *p==0 );
  124531. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  124532. rc = fts3SegReaderIncrRead(pReader);
  124533. if( rc!=SQLITE_OK ) return rc;
  124534. }
  124535. p++;
  124536. /* If required, populate the output variables with a pointer to and the
  124537. ** size of the previous offset-list.
  124538. */
  124539. if( ppOffsetList ){
  124540. *ppOffsetList = pReader->pOffsetList;
  124541. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  124542. }
  124543. /* List may have been edited in place by fts3EvalNearTrim() */
  124544. while( p<pEnd && *p==0 ) p++;
  124545. /* If there are no more entries in the doclist, set pOffsetList to
  124546. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  124547. ** Fts3SegReader.pOffsetList to point to the next offset list before
  124548. ** returning.
  124549. */
  124550. if( p>=pEnd ){
  124551. pReader->pOffsetList = 0;
  124552. }else{
  124553. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  124554. if( rc==SQLITE_OK ){
  124555. sqlite3_int64 iDelta;
  124556. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  124557. if( pTab->bDescIdx ){
  124558. pReader->iDocid -= iDelta;
  124559. }else{
  124560. pReader->iDocid += iDelta;
  124561. }
  124562. }
  124563. }
  124564. }
  124565. return SQLITE_OK;
  124566. }
  124567. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  124568. Fts3Cursor *pCsr,
  124569. Fts3MultiSegReader *pMsr,
  124570. int *pnOvfl
  124571. ){
  124572. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  124573. int nOvfl = 0;
  124574. int ii;
  124575. int rc = SQLITE_OK;
  124576. int pgsz = p->nPgsz;
  124577. assert( p->bFts4 );
  124578. assert( pgsz>0 );
  124579. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  124580. Fts3SegReader *pReader = pMsr->apSegment[ii];
  124581. if( !fts3SegReaderIsPending(pReader)
  124582. && !fts3SegReaderIsRootOnly(pReader)
  124583. ){
  124584. sqlite3_int64 jj;
  124585. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  124586. int nBlob;
  124587. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  124588. if( rc!=SQLITE_OK ) break;
  124589. if( (nBlob+35)>pgsz ){
  124590. nOvfl += (nBlob + 34)/pgsz;
  124591. }
  124592. }
  124593. }
  124594. }
  124595. *pnOvfl = nOvfl;
  124596. return rc;
  124597. }
  124598. /*
  124599. ** Free all allocations associated with the iterator passed as the
  124600. ** second argument.
  124601. */
  124602. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  124603. if( pReader && !fts3SegReaderIsPending(pReader) ){
  124604. sqlite3_free(pReader->zTerm);
  124605. if( !fts3SegReaderIsRootOnly(pReader) ){
  124606. sqlite3_free(pReader->aNode);
  124607. sqlite3_blob_close(pReader->pBlob);
  124608. }
  124609. }
  124610. sqlite3_free(pReader);
  124611. }
  124612. /*
  124613. ** Allocate a new SegReader object.
  124614. */
  124615. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  124616. int iAge, /* Segment "age". */
  124617. int bLookup, /* True for a lookup only */
  124618. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  124619. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  124620. sqlite3_int64 iEndBlock, /* Final block of segment */
  124621. const char *zRoot, /* Buffer containing root node */
  124622. int nRoot, /* Size of buffer containing root node */
  124623. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  124624. ){
  124625. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  124626. int nExtra = 0; /* Bytes to allocate segment root node */
  124627. assert( iStartLeaf<=iEndLeaf );
  124628. if( iStartLeaf==0 ){
  124629. nExtra = nRoot + FTS3_NODE_PADDING;
  124630. }
  124631. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  124632. if( !pReader ){
  124633. return SQLITE_NOMEM;
  124634. }
  124635. memset(pReader, 0, sizeof(Fts3SegReader));
  124636. pReader->iIdx = iAge;
  124637. pReader->bLookup = bLookup!=0;
  124638. pReader->iStartBlock = iStartLeaf;
  124639. pReader->iLeafEndBlock = iEndLeaf;
  124640. pReader->iEndBlock = iEndBlock;
  124641. if( nExtra ){
  124642. /* The entire segment is stored in the root node. */
  124643. pReader->aNode = (char *)&pReader[1];
  124644. pReader->rootOnly = 1;
  124645. pReader->nNode = nRoot;
  124646. memcpy(pReader->aNode, zRoot, nRoot);
  124647. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  124648. }else{
  124649. pReader->iCurrentBlock = iStartLeaf-1;
  124650. }
  124651. *ppReader = pReader;
  124652. return SQLITE_OK;
  124653. }
  124654. /*
  124655. ** This is a comparison function used as a qsort() callback when sorting
  124656. ** an array of pending terms by term. This occurs as part of flushing
  124657. ** the contents of the pending-terms hash table to the database.
  124658. */
  124659. static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
  124660. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  124661. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  124662. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  124663. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  124664. int n = (n1<n2 ? n1 : n2);
  124665. int c = memcmp(z1, z2, n);
  124666. if( c==0 ){
  124667. c = n1 - n2;
  124668. }
  124669. return c;
  124670. }
  124671. /*
  124672. ** This function is used to allocate an Fts3SegReader that iterates through
  124673. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  124674. **
  124675. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  124676. ** through each term in the pending-terms table. Or, if isPrefixIter is
  124677. ** non-zero, it iterates through each term and its prefixes. For example, if
  124678. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  124679. ** "firebird", then the iterator visits the following 'terms' (in the order
  124680. ** shown):
  124681. **
  124682. ** f fi fir fire fireb firebi firebir firebird
  124683. ** m my mys mysq mysql
  124684. ** s sq sql sqli sqlit sqlite
  124685. **
  124686. ** Whereas if isPrefixIter is zero, the terms visited are:
  124687. **
  124688. ** firebird mysql sqlite
  124689. */
  124690. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  124691. Fts3Table *p, /* Virtual table handle */
  124692. int iIndex, /* Index for p->aIndex */
  124693. const char *zTerm, /* Term to search for */
  124694. int nTerm, /* Size of buffer zTerm */
  124695. int bPrefix, /* True for a prefix iterator */
  124696. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  124697. ){
  124698. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  124699. Fts3HashElem *pE; /* Iterator variable */
  124700. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  124701. int nElem = 0; /* Size of array at aElem */
  124702. int rc = SQLITE_OK; /* Return Code */
  124703. Fts3Hash *pHash;
  124704. pHash = &p->aIndex[iIndex].hPending;
  124705. if( bPrefix ){
  124706. int nAlloc = 0; /* Size of allocated array at aElem */
  124707. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  124708. char *zKey = (char *)fts3HashKey(pE);
  124709. int nKey = fts3HashKeysize(pE);
  124710. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  124711. if( nElem==nAlloc ){
  124712. Fts3HashElem **aElem2;
  124713. nAlloc += 16;
  124714. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  124715. aElem, nAlloc*sizeof(Fts3HashElem *)
  124716. );
  124717. if( !aElem2 ){
  124718. rc = SQLITE_NOMEM;
  124719. nElem = 0;
  124720. break;
  124721. }
  124722. aElem = aElem2;
  124723. }
  124724. aElem[nElem++] = pE;
  124725. }
  124726. }
  124727. /* If more than one term matches the prefix, sort the Fts3HashElem
  124728. ** objects in term order using qsort(). This uses the same comparison
  124729. ** callback as is used when flushing terms to disk.
  124730. */
  124731. if( nElem>1 ){
  124732. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  124733. }
  124734. }else{
  124735. /* The query is a simple term lookup that matches at most one term in
  124736. ** the index. All that is required is a straight hash-lookup.
  124737. **
  124738. ** Because the stack address of pE may be accessed via the aElem pointer
  124739. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  124740. ** within this entire function, not just this "else{...}" block.
  124741. */
  124742. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  124743. if( pE ){
  124744. aElem = &pE;
  124745. nElem = 1;
  124746. }
  124747. }
  124748. if( nElem>0 ){
  124749. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  124750. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  124751. if( !pReader ){
  124752. rc = SQLITE_NOMEM;
  124753. }else{
  124754. memset(pReader, 0, nByte);
  124755. pReader->iIdx = 0x7FFFFFFF;
  124756. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  124757. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  124758. }
  124759. }
  124760. if( bPrefix ){
  124761. sqlite3_free(aElem);
  124762. }
  124763. *ppReader = pReader;
  124764. return rc;
  124765. }
  124766. /*
  124767. ** Compare the entries pointed to by two Fts3SegReader structures.
  124768. ** Comparison is as follows:
  124769. **
  124770. ** 1) EOF is greater than not EOF.
  124771. **
  124772. ** 2) The current terms (if any) are compared using memcmp(). If one
  124773. ** term is a prefix of another, the longer term is considered the
  124774. ** larger.
  124775. **
  124776. ** 3) By segment age. An older segment is considered larger.
  124777. */
  124778. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  124779. int rc;
  124780. if( pLhs->aNode && pRhs->aNode ){
  124781. int rc2 = pLhs->nTerm - pRhs->nTerm;
  124782. if( rc2<0 ){
  124783. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  124784. }else{
  124785. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  124786. }
  124787. if( rc==0 ){
  124788. rc = rc2;
  124789. }
  124790. }else{
  124791. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  124792. }
  124793. if( rc==0 ){
  124794. rc = pRhs->iIdx - pLhs->iIdx;
  124795. }
  124796. assert( rc!=0 );
  124797. return rc;
  124798. }
  124799. /*
  124800. ** A different comparison function for SegReader structures. In this
  124801. ** version, it is assumed that each SegReader points to an entry in
  124802. ** a doclist for identical terms. Comparison is made as follows:
  124803. **
  124804. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  124805. **
  124806. ** 2) By current docid.
  124807. **
  124808. ** 3) By segment age. An older segment is considered larger.
  124809. */
  124810. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  124811. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  124812. if( rc==0 ){
  124813. if( pLhs->iDocid==pRhs->iDocid ){
  124814. rc = pRhs->iIdx - pLhs->iIdx;
  124815. }else{
  124816. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  124817. }
  124818. }
  124819. assert( pLhs->aNode && pRhs->aNode );
  124820. return rc;
  124821. }
  124822. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  124823. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  124824. if( rc==0 ){
  124825. if( pLhs->iDocid==pRhs->iDocid ){
  124826. rc = pRhs->iIdx - pLhs->iIdx;
  124827. }else{
  124828. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  124829. }
  124830. }
  124831. assert( pLhs->aNode && pRhs->aNode );
  124832. return rc;
  124833. }
  124834. /*
  124835. ** Compare the term that the Fts3SegReader object passed as the first argument
  124836. ** points to with the term specified by arguments zTerm and nTerm.
  124837. **
  124838. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  124839. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  124840. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  124841. */
  124842. static int fts3SegReaderTermCmp(
  124843. Fts3SegReader *pSeg, /* Segment reader object */
  124844. const char *zTerm, /* Term to compare to */
  124845. int nTerm /* Size of term zTerm in bytes */
  124846. ){
  124847. int res = 0;
  124848. if( pSeg->aNode ){
  124849. if( pSeg->nTerm>nTerm ){
  124850. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  124851. }else{
  124852. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  124853. }
  124854. if( res==0 ){
  124855. res = pSeg->nTerm-nTerm;
  124856. }
  124857. }
  124858. return res;
  124859. }
  124860. /*
  124861. ** Argument apSegment is an array of nSegment elements. It is known that
  124862. ** the final (nSegment-nSuspect) members are already in sorted order
  124863. ** (according to the comparison function provided). This function shuffles
  124864. ** the array around until all entries are in sorted order.
  124865. */
  124866. static void fts3SegReaderSort(
  124867. Fts3SegReader **apSegment, /* Array to sort entries of */
  124868. int nSegment, /* Size of apSegment array */
  124869. int nSuspect, /* Unsorted entry count */
  124870. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  124871. ){
  124872. int i; /* Iterator variable */
  124873. assert( nSuspect<=nSegment );
  124874. if( nSuspect==nSegment ) nSuspect--;
  124875. for(i=nSuspect-1; i>=0; i--){
  124876. int j;
  124877. for(j=i; j<(nSegment-1); j++){
  124878. Fts3SegReader *pTmp;
  124879. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  124880. pTmp = apSegment[j+1];
  124881. apSegment[j+1] = apSegment[j];
  124882. apSegment[j] = pTmp;
  124883. }
  124884. }
  124885. #ifndef NDEBUG
  124886. /* Check that the list really is sorted now. */
  124887. for(i=0; i<(nSuspect-1); i++){
  124888. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  124889. }
  124890. #endif
  124891. }
  124892. /*
  124893. ** Insert a record into the %_segments table.
  124894. */
  124895. static int fts3WriteSegment(
  124896. Fts3Table *p, /* Virtual table handle */
  124897. sqlite3_int64 iBlock, /* Block id for new block */
  124898. char *z, /* Pointer to buffer containing block data */
  124899. int n /* Size of buffer z in bytes */
  124900. ){
  124901. sqlite3_stmt *pStmt;
  124902. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  124903. if( rc==SQLITE_OK ){
  124904. sqlite3_bind_int64(pStmt, 1, iBlock);
  124905. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  124906. sqlite3_step(pStmt);
  124907. rc = sqlite3_reset(pStmt);
  124908. }
  124909. return rc;
  124910. }
  124911. /*
  124912. ** Find the largest relative level number in the table. If successful, set
  124913. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  124914. ** set *pnMax to zero and return an SQLite error code.
  124915. */
  124916. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  124917. int rc;
  124918. int mxLevel = 0;
  124919. sqlite3_stmt *pStmt = 0;
  124920. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  124921. if( rc==SQLITE_OK ){
  124922. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  124923. mxLevel = sqlite3_column_int(pStmt, 0);
  124924. }
  124925. rc = sqlite3_reset(pStmt);
  124926. }
  124927. *pnMax = mxLevel;
  124928. return rc;
  124929. }
  124930. /*
  124931. ** Insert a record into the %_segdir table.
  124932. */
  124933. static int fts3WriteSegdir(
  124934. Fts3Table *p, /* Virtual table handle */
  124935. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  124936. int iIdx, /* Value for "idx" field */
  124937. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  124938. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  124939. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  124940. char *zRoot, /* Blob value for "root" field */
  124941. int nRoot /* Number of bytes in buffer zRoot */
  124942. ){
  124943. sqlite3_stmt *pStmt;
  124944. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  124945. if( rc==SQLITE_OK ){
  124946. sqlite3_bind_int64(pStmt, 1, iLevel);
  124947. sqlite3_bind_int(pStmt, 2, iIdx);
  124948. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  124949. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  124950. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  124951. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  124952. sqlite3_step(pStmt);
  124953. rc = sqlite3_reset(pStmt);
  124954. }
  124955. return rc;
  124956. }
  124957. /*
  124958. ** Return the size of the common prefix (if any) shared by zPrev and
  124959. ** zNext, in bytes. For example,
  124960. **
  124961. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  124962. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  124963. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  124964. */
  124965. static int fts3PrefixCompress(
  124966. const char *zPrev, /* Buffer containing previous term */
  124967. int nPrev, /* Size of buffer zPrev in bytes */
  124968. const char *zNext, /* Buffer containing next term */
  124969. int nNext /* Size of buffer zNext in bytes */
  124970. ){
  124971. int n;
  124972. UNUSED_PARAMETER(nNext);
  124973. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  124974. return n;
  124975. }
  124976. /*
  124977. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  124978. ** (according to memcmp) than the previous term.
  124979. */
  124980. static int fts3NodeAddTerm(
  124981. Fts3Table *p, /* Virtual table handle */
  124982. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  124983. int isCopyTerm, /* True if zTerm/nTerm is transient */
  124984. const char *zTerm, /* Pointer to buffer containing term */
  124985. int nTerm /* Size of term in bytes */
  124986. ){
  124987. SegmentNode *pTree = *ppTree;
  124988. int rc;
  124989. SegmentNode *pNew;
  124990. /* First try to append the term to the current node. Return early if
  124991. ** this is possible.
  124992. */
  124993. if( pTree ){
  124994. int nData = pTree->nData; /* Current size of node in bytes */
  124995. int nReq = nData; /* Required space after adding zTerm */
  124996. int nPrefix; /* Number of bytes of prefix compression */
  124997. int nSuffix; /* Suffix length */
  124998. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  124999. nSuffix = nTerm-nPrefix;
  125000. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  125001. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  125002. if( nReq>p->nNodeSize ){
  125003. /* An unusual case: this is the first term to be added to the node
  125004. ** and the static node buffer (p->nNodeSize bytes) is not large
  125005. ** enough. Use a separately malloced buffer instead This wastes
  125006. ** p->nNodeSize bytes, but since this scenario only comes about when
  125007. ** the database contain two terms that share a prefix of almost 2KB,
  125008. ** this is not expected to be a serious problem.
  125009. */
  125010. assert( pTree->aData==(char *)&pTree[1] );
  125011. pTree->aData = (char *)sqlite3_malloc(nReq);
  125012. if( !pTree->aData ){
  125013. return SQLITE_NOMEM;
  125014. }
  125015. }
  125016. if( pTree->zTerm ){
  125017. /* There is no prefix-length field for first term in a node */
  125018. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  125019. }
  125020. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  125021. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  125022. pTree->nData = nData + nSuffix;
  125023. pTree->nEntry++;
  125024. if( isCopyTerm ){
  125025. if( pTree->nMalloc<nTerm ){
  125026. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  125027. if( !zNew ){
  125028. return SQLITE_NOMEM;
  125029. }
  125030. pTree->nMalloc = nTerm*2;
  125031. pTree->zMalloc = zNew;
  125032. }
  125033. pTree->zTerm = pTree->zMalloc;
  125034. memcpy(pTree->zTerm, zTerm, nTerm);
  125035. pTree->nTerm = nTerm;
  125036. }else{
  125037. pTree->zTerm = (char *)zTerm;
  125038. pTree->nTerm = nTerm;
  125039. }
  125040. return SQLITE_OK;
  125041. }
  125042. }
  125043. /* If control flows to here, it was not possible to append zTerm to the
  125044. ** current node. Create a new node (a right-sibling of the current node).
  125045. ** If this is the first node in the tree, the term is added to it.
  125046. **
  125047. ** Otherwise, the term is not added to the new node, it is left empty for
  125048. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  125049. ** has no parent, one is created here.
  125050. */
  125051. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  125052. if( !pNew ){
  125053. return SQLITE_NOMEM;
  125054. }
  125055. memset(pNew, 0, sizeof(SegmentNode));
  125056. pNew->nData = 1 + FTS3_VARINT_MAX;
  125057. pNew->aData = (char *)&pNew[1];
  125058. if( pTree ){
  125059. SegmentNode *pParent = pTree->pParent;
  125060. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  125061. if( pTree->pParent==0 ){
  125062. pTree->pParent = pParent;
  125063. }
  125064. pTree->pRight = pNew;
  125065. pNew->pLeftmost = pTree->pLeftmost;
  125066. pNew->pParent = pParent;
  125067. pNew->zMalloc = pTree->zMalloc;
  125068. pNew->nMalloc = pTree->nMalloc;
  125069. pTree->zMalloc = 0;
  125070. }else{
  125071. pNew->pLeftmost = pNew;
  125072. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  125073. }
  125074. *ppTree = pNew;
  125075. return rc;
  125076. }
  125077. /*
  125078. ** Helper function for fts3NodeWrite().
  125079. */
  125080. static int fts3TreeFinishNode(
  125081. SegmentNode *pTree,
  125082. int iHeight,
  125083. sqlite3_int64 iLeftChild
  125084. ){
  125085. int nStart;
  125086. assert( iHeight>=1 && iHeight<128 );
  125087. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  125088. pTree->aData[nStart] = (char)iHeight;
  125089. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  125090. return nStart;
  125091. }
  125092. /*
  125093. ** Write the buffer for the segment node pTree and all of its peers to the
  125094. ** database. Then call this function recursively to write the parent of
  125095. ** pTree and its peers to the database.
  125096. **
  125097. ** Except, if pTree is a root node, do not write it to the database. Instead,
  125098. ** set output variables *paRoot and *pnRoot to contain the root node.
  125099. **
  125100. ** If successful, SQLITE_OK is returned and output variable *piLast is
  125101. ** set to the largest blockid written to the database (or zero if no
  125102. ** blocks were written to the db). Otherwise, an SQLite error code is
  125103. ** returned.
  125104. */
  125105. static int fts3NodeWrite(
  125106. Fts3Table *p, /* Virtual table handle */
  125107. SegmentNode *pTree, /* SegmentNode handle */
  125108. int iHeight, /* Height of this node in tree */
  125109. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  125110. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  125111. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  125112. char **paRoot, /* OUT: Data for root node */
  125113. int *pnRoot /* OUT: Size of root node in bytes */
  125114. ){
  125115. int rc = SQLITE_OK;
  125116. if( !pTree->pParent ){
  125117. /* Root node of the tree. */
  125118. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  125119. *piLast = iFree-1;
  125120. *pnRoot = pTree->nData - nStart;
  125121. *paRoot = &pTree->aData[nStart];
  125122. }else{
  125123. SegmentNode *pIter;
  125124. sqlite3_int64 iNextFree = iFree;
  125125. sqlite3_int64 iNextLeaf = iLeaf;
  125126. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  125127. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  125128. int nWrite = pIter->nData - nStart;
  125129. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  125130. iNextFree++;
  125131. iNextLeaf += (pIter->nEntry+1);
  125132. }
  125133. if( rc==SQLITE_OK ){
  125134. assert( iNextLeaf==iFree );
  125135. rc = fts3NodeWrite(
  125136. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  125137. );
  125138. }
  125139. }
  125140. return rc;
  125141. }
  125142. /*
  125143. ** Free all memory allocations associated with the tree pTree.
  125144. */
  125145. static void fts3NodeFree(SegmentNode *pTree){
  125146. if( pTree ){
  125147. SegmentNode *p = pTree->pLeftmost;
  125148. fts3NodeFree(p->pParent);
  125149. while( p ){
  125150. SegmentNode *pRight = p->pRight;
  125151. if( p->aData!=(char *)&p[1] ){
  125152. sqlite3_free(p->aData);
  125153. }
  125154. assert( pRight==0 || p->zMalloc==0 );
  125155. sqlite3_free(p->zMalloc);
  125156. sqlite3_free(p);
  125157. p = pRight;
  125158. }
  125159. }
  125160. }
  125161. /*
  125162. ** Add a term to the segment being constructed by the SegmentWriter object
  125163. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  125164. ** be passed NULL. This function will allocate a new SegmentWriter object
  125165. ** and return it via the input/output variable *ppWriter in this case.
  125166. **
  125167. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  125168. */
  125169. static int fts3SegWriterAdd(
  125170. Fts3Table *p, /* Virtual table handle */
  125171. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  125172. int isCopyTerm, /* True if buffer zTerm must be copied */
  125173. const char *zTerm, /* Pointer to buffer containing term */
  125174. int nTerm, /* Size of term in bytes */
  125175. const char *aDoclist, /* Pointer to buffer containing doclist */
  125176. int nDoclist /* Size of doclist in bytes */
  125177. ){
  125178. int nPrefix; /* Size of term prefix in bytes */
  125179. int nSuffix; /* Size of term suffix in bytes */
  125180. int nReq; /* Number of bytes required on leaf page */
  125181. int nData;
  125182. SegmentWriter *pWriter = *ppWriter;
  125183. if( !pWriter ){
  125184. int rc;
  125185. sqlite3_stmt *pStmt;
  125186. /* Allocate the SegmentWriter structure */
  125187. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  125188. if( !pWriter ) return SQLITE_NOMEM;
  125189. memset(pWriter, 0, sizeof(SegmentWriter));
  125190. *ppWriter = pWriter;
  125191. /* Allocate a buffer in which to accumulate data */
  125192. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  125193. if( !pWriter->aData ) return SQLITE_NOMEM;
  125194. pWriter->nSize = p->nNodeSize;
  125195. /* Find the next free blockid in the %_segments table */
  125196. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  125197. if( rc!=SQLITE_OK ) return rc;
  125198. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  125199. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  125200. pWriter->iFirst = pWriter->iFree;
  125201. }
  125202. rc = sqlite3_reset(pStmt);
  125203. if( rc!=SQLITE_OK ) return rc;
  125204. }
  125205. nData = pWriter->nData;
  125206. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  125207. nSuffix = nTerm-nPrefix;
  125208. /* Figure out how many bytes are required by this new entry */
  125209. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  125210. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  125211. nSuffix + /* Term suffix */
  125212. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  125213. nDoclist; /* Doclist data */
  125214. if( nData>0 && nData+nReq>p->nNodeSize ){
  125215. int rc;
  125216. /* The current leaf node is full. Write it out to the database. */
  125217. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  125218. if( rc!=SQLITE_OK ) return rc;
  125219. p->nLeafAdd++;
  125220. /* Add the current term to the interior node tree. The term added to
  125221. ** the interior tree must:
  125222. **
  125223. ** a) be greater than the largest term on the leaf node just written
  125224. ** to the database (still available in pWriter->zTerm), and
  125225. **
  125226. ** b) be less than or equal to the term about to be added to the new
  125227. ** leaf node (zTerm/nTerm).
  125228. **
  125229. ** In other words, it must be the prefix of zTerm 1 byte longer than
  125230. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  125231. */
  125232. assert( nPrefix<nTerm );
  125233. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  125234. if( rc!=SQLITE_OK ) return rc;
  125235. nData = 0;
  125236. pWriter->nTerm = 0;
  125237. nPrefix = 0;
  125238. nSuffix = nTerm;
  125239. nReq = 1 + /* varint containing prefix size */
  125240. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  125241. nTerm + /* Term suffix */
  125242. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  125243. nDoclist; /* Doclist data */
  125244. }
  125245. /* If the buffer currently allocated is too small for this entry, realloc
  125246. ** the buffer to make it large enough.
  125247. */
  125248. if( nReq>pWriter->nSize ){
  125249. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  125250. if( !aNew ) return SQLITE_NOMEM;
  125251. pWriter->aData = aNew;
  125252. pWriter->nSize = nReq;
  125253. }
  125254. assert( nData+nReq<=pWriter->nSize );
  125255. /* Append the prefix-compressed term and doclist to the buffer. */
  125256. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  125257. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  125258. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  125259. nData += nSuffix;
  125260. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  125261. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  125262. pWriter->nData = nData + nDoclist;
  125263. /* Save the current term so that it can be used to prefix-compress the next.
  125264. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  125265. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  125266. ** store a copy of the pointer.
  125267. */
  125268. if( isCopyTerm ){
  125269. if( nTerm>pWriter->nMalloc ){
  125270. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  125271. if( !zNew ){
  125272. return SQLITE_NOMEM;
  125273. }
  125274. pWriter->nMalloc = nTerm*2;
  125275. pWriter->zMalloc = zNew;
  125276. pWriter->zTerm = zNew;
  125277. }
  125278. assert( pWriter->zTerm==pWriter->zMalloc );
  125279. memcpy(pWriter->zTerm, zTerm, nTerm);
  125280. }else{
  125281. pWriter->zTerm = (char *)zTerm;
  125282. }
  125283. pWriter->nTerm = nTerm;
  125284. return SQLITE_OK;
  125285. }
  125286. /*
  125287. ** Flush all data associated with the SegmentWriter object pWriter to the
  125288. ** database. This function must be called after all terms have been added
  125289. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  125290. ** returned. Otherwise, an SQLite error code.
  125291. */
  125292. static int fts3SegWriterFlush(
  125293. Fts3Table *p, /* Virtual table handle */
  125294. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  125295. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  125296. int iIdx /* Value for 'idx' column of %_segdir */
  125297. ){
  125298. int rc; /* Return code */
  125299. if( pWriter->pTree ){
  125300. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  125301. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  125302. char *zRoot = NULL; /* Pointer to buffer containing root node */
  125303. int nRoot = 0; /* Size of buffer zRoot */
  125304. iLastLeaf = pWriter->iFree;
  125305. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  125306. if( rc==SQLITE_OK ){
  125307. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  125308. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  125309. }
  125310. if( rc==SQLITE_OK ){
  125311. rc = fts3WriteSegdir(
  125312. p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
  125313. }
  125314. }else{
  125315. /* The entire tree fits on the root node. Write it to the segdir table. */
  125316. rc = fts3WriteSegdir(
  125317. p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
  125318. }
  125319. p->nLeafAdd++;
  125320. return rc;
  125321. }
  125322. /*
  125323. ** Release all memory held by the SegmentWriter object passed as the
  125324. ** first argument.
  125325. */
  125326. static void fts3SegWriterFree(SegmentWriter *pWriter){
  125327. if( pWriter ){
  125328. sqlite3_free(pWriter->aData);
  125329. sqlite3_free(pWriter->zMalloc);
  125330. fts3NodeFree(pWriter->pTree);
  125331. sqlite3_free(pWriter);
  125332. }
  125333. }
  125334. /*
  125335. ** The first value in the apVal[] array is assumed to contain an integer.
  125336. ** This function tests if there exist any documents with docid values that
  125337. ** are different from that integer. i.e. if deleting the document with docid
  125338. ** pRowid would mean the FTS3 table were empty.
  125339. **
  125340. ** If successful, *pisEmpty is set to true if the table is empty except for
  125341. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  125342. ** error occurs, an SQLite error code is returned.
  125343. */
  125344. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  125345. sqlite3_stmt *pStmt;
  125346. int rc;
  125347. if( p->zContentTbl ){
  125348. /* If using the content=xxx option, assume the table is never empty */
  125349. *pisEmpty = 0;
  125350. rc = SQLITE_OK;
  125351. }else{
  125352. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  125353. if( rc==SQLITE_OK ){
  125354. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  125355. *pisEmpty = sqlite3_column_int(pStmt, 0);
  125356. }
  125357. rc = sqlite3_reset(pStmt);
  125358. }
  125359. }
  125360. return rc;
  125361. }
  125362. /*
  125363. ** Set *pnMax to the largest segment level in the database for the index
  125364. ** iIndex.
  125365. **
  125366. ** Segment levels are stored in the 'level' column of the %_segdir table.
  125367. **
  125368. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  125369. */
  125370. static int fts3SegmentMaxLevel(
  125371. Fts3Table *p,
  125372. int iLangid,
  125373. int iIndex,
  125374. sqlite3_int64 *pnMax
  125375. ){
  125376. sqlite3_stmt *pStmt;
  125377. int rc;
  125378. assert( iIndex>=0 && iIndex<p->nIndex );
  125379. /* Set pStmt to the compiled version of:
  125380. **
  125381. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  125382. **
  125383. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  125384. */
  125385. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  125386. if( rc!=SQLITE_OK ) return rc;
  125387. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  125388. sqlite3_bind_int64(pStmt, 2,
  125389. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  125390. );
  125391. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  125392. *pnMax = sqlite3_column_int64(pStmt, 0);
  125393. }
  125394. return sqlite3_reset(pStmt);
  125395. }
  125396. /*
  125397. ** Delete all entries in the %_segments table associated with the segment
  125398. ** opened with seg-reader pSeg. This function does not affect the contents
  125399. ** of the %_segdir table.
  125400. */
  125401. static int fts3DeleteSegment(
  125402. Fts3Table *p, /* FTS table handle */
  125403. Fts3SegReader *pSeg /* Segment to delete */
  125404. ){
  125405. int rc = SQLITE_OK; /* Return code */
  125406. if( pSeg->iStartBlock ){
  125407. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  125408. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  125409. if( rc==SQLITE_OK ){
  125410. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  125411. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  125412. sqlite3_step(pDelete);
  125413. rc = sqlite3_reset(pDelete);
  125414. }
  125415. }
  125416. return rc;
  125417. }
  125418. /*
  125419. ** This function is used after merging multiple segments into a single large
  125420. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  125421. ** it:
  125422. **
  125423. ** 1) Deletes all %_segments entries for the segments associated with
  125424. ** each of the SegReader objects in the array passed as the third
  125425. ** argument, and
  125426. **
  125427. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  125428. ** entries regardless of level if (iLevel<0).
  125429. **
  125430. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  125431. */
  125432. static int fts3DeleteSegdir(
  125433. Fts3Table *p, /* Virtual table handle */
  125434. int iLangid, /* Language id */
  125435. int iIndex, /* Index for p->aIndex */
  125436. int iLevel, /* Level of %_segdir entries to delete */
  125437. Fts3SegReader **apSegment, /* Array of SegReader objects */
  125438. int nReader /* Size of array apSegment */
  125439. ){
  125440. int rc = SQLITE_OK; /* Return Code */
  125441. int i; /* Iterator variable */
  125442. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  125443. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  125444. rc = fts3DeleteSegment(p, apSegment[i]);
  125445. }
  125446. if( rc!=SQLITE_OK ){
  125447. return rc;
  125448. }
  125449. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  125450. if( iLevel==FTS3_SEGCURSOR_ALL ){
  125451. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  125452. if( rc==SQLITE_OK ){
  125453. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  125454. sqlite3_bind_int64(pDelete, 2,
  125455. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  125456. );
  125457. }
  125458. }else{
  125459. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  125460. if( rc==SQLITE_OK ){
  125461. sqlite3_bind_int64(
  125462. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  125463. );
  125464. }
  125465. }
  125466. if( rc==SQLITE_OK ){
  125467. sqlite3_step(pDelete);
  125468. rc = sqlite3_reset(pDelete);
  125469. }
  125470. return rc;
  125471. }
  125472. /*
  125473. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  125474. ** a position list that may (or may not) feature multiple columns. This
  125475. ** function adjusts the pointer *ppList and the length *pnList so that they
  125476. ** identify the subset of the position list that corresponds to column iCol.
  125477. **
  125478. ** If there are no entries in the input position list for column iCol, then
  125479. ** *pnList is set to zero before returning.
  125480. **
  125481. ** If parameter bZero is non-zero, then any part of the input list following
  125482. ** the end of the output list is zeroed before returning.
  125483. */
  125484. static void fts3ColumnFilter(
  125485. int iCol, /* Column to filter on */
  125486. int bZero, /* Zero out anything following *ppList */
  125487. char **ppList, /* IN/OUT: Pointer to position list */
  125488. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  125489. ){
  125490. char *pList = *ppList;
  125491. int nList = *pnList;
  125492. char *pEnd = &pList[nList];
  125493. int iCurrent = 0;
  125494. char *p = pList;
  125495. assert( iCol>=0 );
  125496. while( 1 ){
  125497. char c = 0;
  125498. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  125499. if( iCol==iCurrent ){
  125500. nList = (int)(p - pList);
  125501. break;
  125502. }
  125503. nList -= (int)(p - pList);
  125504. pList = p;
  125505. if( nList==0 ){
  125506. break;
  125507. }
  125508. p = &pList[1];
  125509. p += sqlite3Fts3GetVarint32(p, &iCurrent);
  125510. }
  125511. if( bZero && &pList[nList]!=pEnd ){
  125512. memset(&pList[nList], 0, pEnd - &pList[nList]);
  125513. }
  125514. *ppList = pList;
  125515. *pnList = nList;
  125516. }
  125517. /*
  125518. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  125519. ** existing data). Grow the buffer if required.
  125520. **
  125521. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  125522. ** trying to resize the buffer, return SQLITE_NOMEM.
  125523. */
  125524. static int fts3MsrBufferData(
  125525. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  125526. char *pList,
  125527. int nList
  125528. ){
  125529. if( nList>pMsr->nBuffer ){
  125530. char *pNew;
  125531. pMsr->nBuffer = nList*2;
  125532. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  125533. if( !pNew ) return SQLITE_NOMEM;
  125534. pMsr->aBuffer = pNew;
  125535. }
  125536. memcpy(pMsr->aBuffer, pList, nList);
  125537. return SQLITE_OK;
  125538. }
  125539. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  125540. Fts3Table *p, /* Virtual table handle */
  125541. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  125542. sqlite3_int64 *piDocid, /* OUT: Docid value */
  125543. char **paPoslist, /* OUT: Pointer to position list */
  125544. int *pnPoslist /* OUT: Size of position list in bytes */
  125545. ){
  125546. int nMerge = pMsr->nAdvance;
  125547. Fts3SegReader **apSegment = pMsr->apSegment;
  125548. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  125549. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  125550. );
  125551. if( nMerge==0 ){
  125552. *paPoslist = 0;
  125553. return SQLITE_OK;
  125554. }
  125555. while( 1 ){
  125556. Fts3SegReader *pSeg;
  125557. pSeg = pMsr->apSegment[0];
  125558. if( pSeg->pOffsetList==0 ){
  125559. *paPoslist = 0;
  125560. break;
  125561. }else{
  125562. int rc;
  125563. char *pList;
  125564. int nList;
  125565. int j;
  125566. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  125567. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  125568. j = 1;
  125569. while( rc==SQLITE_OK
  125570. && j<nMerge
  125571. && apSegment[j]->pOffsetList
  125572. && apSegment[j]->iDocid==iDocid
  125573. ){
  125574. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  125575. j++;
  125576. }
  125577. if( rc!=SQLITE_OK ) return rc;
  125578. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  125579. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  125580. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  125581. if( rc!=SQLITE_OK ) return rc;
  125582. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  125583. pList = pMsr->aBuffer;
  125584. }
  125585. if( pMsr->iColFilter>=0 ){
  125586. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  125587. }
  125588. if( nList>0 ){
  125589. *paPoslist = pList;
  125590. *piDocid = iDocid;
  125591. *pnPoslist = nList;
  125592. break;
  125593. }
  125594. }
  125595. }
  125596. return SQLITE_OK;
  125597. }
  125598. static int fts3SegReaderStart(
  125599. Fts3Table *p, /* Virtual table handle */
  125600. Fts3MultiSegReader *pCsr, /* Cursor object */
  125601. const char *zTerm, /* Term searched for (or NULL) */
  125602. int nTerm /* Length of zTerm in bytes */
  125603. ){
  125604. int i;
  125605. int nSeg = pCsr->nSegment;
  125606. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  125607. ** for, then advance each segment iterator until it points to a term of
  125608. ** equal or greater value than the specified term. This prevents many
  125609. ** unnecessary merge/sort operations for the case where single segment
  125610. ** b-tree leaf nodes contain more than one term.
  125611. */
  125612. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  125613. int res = 0;
  125614. Fts3SegReader *pSeg = pCsr->apSegment[i];
  125615. do {
  125616. int rc = fts3SegReaderNext(p, pSeg, 0);
  125617. if( rc!=SQLITE_OK ) return rc;
  125618. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  125619. if( pSeg->bLookup && res!=0 ){
  125620. fts3SegReaderSetEof(pSeg);
  125621. }
  125622. }
  125623. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  125624. return SQLITE_OK;
  125625. }
  125626. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  125627. Fts3Table *p, /* Virtual table handle */
  125628. Fts3MultiSegReader *pCsr, /* Cursor object */
  125629. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  125630. ){
  125631. pCsr->pFilter = pFilter;
  125632. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  125633. }
  125634. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  125635. Fts3Table *p, /* Virtual table handle */
  125636. Fts3MultiSegReader *pCsr, /* Cursor object */
  125637. int iCol, /* Column to match on. */
  125638. const char *zTerm, /* Term to iterate through a doclist for */
  125639. int nTerm /* Number of bytes in zTerm */
  125640. ){
  125641. int i;
  125642. int rc;
  125643. int nSegment = pCsr->nSegment;
  125644. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  125645. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  125646. );
  125647. assert( pCsr->pFilter==0 );
  125648. assert( zTerm && nTerm>0 );
  125649. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  125650. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  125651. if( rc!=SQLITE_OK ) return rc;
  125652. /* Determine how many of the segments actually point to zTerm/nTerm. */
  125653. for(i=0; i<nSegment; i++){
  125654. Fts3SegReader *pSeg = pCsr->apSegment[i];
  125655. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  125656. break;
  125657. }
  125658. }
  125659. pCsr->nAdvance = i;
  125660. /* Advance each of the segments to point to the first docid. */
  125661. for(i=0; i<pCsr->nAdvance; i++){
  125662. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  125663. if( rc!=SQLITE_OK ) return rc;
  125664. }
  125665. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  125666. assert( iCol<0 || iCol<p->nColumn );
  125667. pCsr->iColFilter = iCol;
  125668. return SQLITE_OK;
  125669. }
  125670. /*
  125671. ** This function is called on a MultiSegReader that has been started using
  125672. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  125673. ** have been made. Calling this function puts the MultiSegReader in such
  125674. ** a state that if the next two calls are:
  125675. **
  125676. ** sqlite3Fts3SegReaderStart()
  125677. ** sqlite3Fts3SegReaderStep()
  125678. **
  125679. ** then the entire doclist for the term is available in
  125680. ** MultiSegReader.aDoclist/nDoclist.
  125681. */
  125682. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  125683. int i; /* Used to iterate through segment-readers */
  125684. assert( pCsr->zTerm==0 );
  125685. assert( pCsr->nTerm==0 );
  125686. assert( pCsr->aDoclist==0 );
  125687. assert( pCsr->nDoclist==0 );
  125688. pCsr->nAdvance = 0;
  125689. pCsr->bRestart = 1;
  125690. for(i=0; i<pCsr->nSegment; i++){
  125691. pCsr->apSegment[i]->pOffsetList = 0;
  125692. pCsr->apSegment[i]->nOffsetList = 0;
  125693. pCsr->apSegment[i]->iDocid = 0;
  125694. }
  125695. return SQLITE_OK;
  125696. }
  125697. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  125698. Fts3Table *p, /* Virtual table handle */
  125699. Fts3MultiSegReader *pCsr /* Cursor object */
  125700. ){
  125701. int rc = SQLITE_OK;
  125702. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  125703. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  125704. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  125705. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  125706. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  125707. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  125708. Fts3SegReader **apSegment = pCsr->apSegment;
  125709. int nSegment = pCsr->nSegment;
  125710. Fts3SegFilter *pFilter = pCsr->pFilter;
  125711. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  125712. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  125713. );
  125714. if( pCsr->nSegment==0 ) return SQLITE_OK;
  125715. do {
  125716. int nMerge;
  125717. int i;
  125718. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  125719. ** forward. Then sort the list in order of current term again.
  125720. */
  125721. for(i=0; i<pCsr->nAdvance; i++){
  125722. Fts3SegReader *pSeg = apSegment[i];
  125723. if( pSeg->bLookup ){
  125724. fts3SegReaderSetEof(pSeg);
  125725. }else{
  125726. rc = fts3SegReaderNext(p, pSeg, 0);
  125727. }
  125728. if( rc!=SQLITE_OK ) return rc;
  125729. }
  125730. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  125731. pCsr->nAdvance = 0;
  125732. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  125733. assert( rc==SQLITE_OK );
  125734. if( apSegment[0]->aNode==0 ) break;
  125735. pCsr->nTerm = apSegment[0]->nTerm;
  125736. pCsr->zTerm = apSegment[0]->zTerm;
  125737. /* If this is a prefix-search, and if the term that apSegment[0] points
  125738. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  125739. ** required callbacks have been made. In this case exit early.
  125740. **
  125741. ** Similarly, if this is a search for an exact match, and the first term
  125742. ** of segment apSegment[0] is not a match, exit early.
  125743. */
  125744. if( pFilter->zTerm && !isScan ){
  125745. if( pCsr->nTerm<pFilter->nTerm
  125746. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  125747. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  125748. ){
  125749. break;
  125750. }
  125751. }
  125752. nMerge = 1;
  125753. while( nMerge<nSegment
  125754. && apSegment[nMerge]->aNode
  125755. && apSegment[nMerge]->nTerm==pCsr->nTerm
  125756. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  125757. ){
  125758. nMerge++;
  125759. }
  125760. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  125761. if( nMerge==1
  125762. && !isIgnoreEmpty
  125763. && !isFirst
  125764. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  125765. ){
  125766. pCsr->nDoclist = apSegment[0]->nDoclist;
  125767. if( fts3SegReaderIsPending(apSegment[0]) ){
  125768. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  125769. pCsr->aDoclist = pCsr->aBuffer;
  125770. }else{
  125771. pCsr->aDoclist = apSegment[0]->aDoclist;
  125772. }
  125773. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  125774. }else{
  125775. int nDoclist = 0; /* Size of doclist */
  125776. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  125777. /* The current term of the first nMerge entries in the array
  125778. ** of Fts3SegReader objects is the same. The doclists must be merged
  125779. ** and a single term returned with the merged doclist.
  125780. */
  125781. for(i=0; i<nMerge; i++){
  125782. fts3SegReaderFirstDocid(p, apSegment[i]);
  125783. }
  125784. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  125785. while( apSegment[0]->pOffsetList ){
  125786. int j; /* Number of segments that share a docid */
  125787. char *pList = 0;
  125788. int nList = 0;
  125789. int nByte;
  125790. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  125791. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  125792. j = 1;
  125793. while( j<nMerge
  125794. && apSegment[j]->pOffsetList
  125795. && apSegment[j]->iDocid==iDocid
  125796. ){
  125797. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  125798. j++;
  125799. }
  125800. if( isColFilter ){
  125801. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  125802. }
  125803. if( !isIgnoreEmpty || nList>0 ){
  125804. /* Calculate the 'docid' delta value to write into the merged
  125805. ** doclist. */
  125806. sqlite3_int64 iDelta;
  125807. if( p->bDescIdx && nDoclist>0 ){
  125808. iDelta = iPrev - iDocid;
  125809. }else{
  125810. iDelta = iDocid - iPrev;
  125811. }
  125812. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  125813. assert( nDoclist>0 || iDelta==iDocid );
  125814. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  125815. if( nDoclist+nByte>pCsr->nBuffer ){
  125816. char *aNew;
  125817. pCsr->nBuffer = (nDoclist+nByte)*2;
  125818. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  125819. if( !aNew ){
  125820. return SQLITE_NOMEM;
  125821. }
  125822. pCsr->aBuffer = aNew;
  125823. }
  125824. if( isFirst ){
  125825. char *a = &pCsr->aBuffer[nDoclist];
  125826. int nWrite;
  125827. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  125828. if( nWrite ){
  125829. iPrev = iDocid;
  125830. nDoclist += nWrite;
  125831. }
  125832. }else{
  125833. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  125834. iPrev = iDocid;
  125835. if( isRequirePos ){
  125836. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  125837. nDoclist += nList;
  125838. pCsr->aBuffer[nDoclist++] = '\0';
  125839. }
  125840. }
  125841. }
  125842. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  125843. }
  125844. if( nDoclist>0 ){
  125845. pCsr->aDoclist = pCsr->aBuffer;
  125846. pCsr->nDoclist = nDoclist;
  125847. rc = SQLITE_ROW;
  125848. }
  125849. }
  125850. pCsr->nAdvance = nMerge;
  125851. }while( rc==SQLITE_OK );
  125852. return rc;
  125853. }
  125854. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  125855. Fts3MultiSegReader *pCsr /* Cursor object */
  125856. ){
  125857. if( pCsr ){
  125858. int i;
  125859. for(i=0; i<pCsr->nSegment; i++){
  125860. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  125861. }
  125862. sqlite3_free(pCsr->apSegment);
  125863. sqlite3_free(pCsr->aBuffer);
  125864. pCsr->nSegment = 0;
  125865. pCsr->apSegment = 0;
  125866. pCsr->aBuffer = 0;
  125867. }
  125868. }
  125869. /*
  125870. ** Merge all level iLevel segments in the database into a single
  125871. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  125872. ** single segment with a level equal to the numerically largest level
  125873. ** currently present in the database.
  125874. **
  125875. ** If this function is called with iLevel<0, but there is only one
  125876. ** segment in the database, SQLITE_DONE is returned immediately.
  125877. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  125878. ** an SQLite error code is returned.
  125879. */
  125880. static int fts3SegmentMerge(
  125881. Fts3Table *p,
  125882. int iLangid, /* Language id to merge */
  125883. int iIndex, /* Index in p->aIndex[] to merge */
  125884. int iLevel /* Level to merge */
  125885. ){
  125886. int rc; /* Return code */
  125887. int iIdx = 0; /* Index of new segment */
  125888. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  125889. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  125890. Fts3SegFilter filter; /* Segment term filter condition */
  125891. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  125892. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  125893. assert( iLevel==FTS3_SEGCURSOR_ALL
  125894. || iLevel==FTS3_SEGCURSOR_PENDING
  125895. || iLevel>=0
  125896. );
  125897. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  125898. assert( iIndex>=0 && iIndex<p->nIndex );
  125899. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  125900. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  125901. if( iLevel==FTS3_SEGCURSOR_ALL ){
  125902. /* This call is to merge all segments in the database to a single
  125903. ** segment. The level of the new segment is equal to the numerically
  125904. ** greatest segment level currently present in the database for this
  125905. ** index. The idx of the new segment is always 0. */
  125906. if( csr.nSegment==1 ){
  125907. rc = SQLITE_DONE;
  125908. goto finished;
  125909. }
  125910. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
  125911. bIgnoreEmpty = 1;
  125912. }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
  125913. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
  125914. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
  125915. }else{
  125916. /* This call is to merge all segments at level iLevel. find the next
  125917. ** available segment index at level iLevel+1. The call to
  125918. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  125919. ** a single iLevel+2 segment if necessary. */
  125920. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  125921. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  125922. }
  125923. if( rc!=SQLITE_OK ) goto finished;
  125924. assert( csr.nSegment>0 );
  125925. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  125926. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  125927. memset(&filter, 0, sizeof(Fts3SegFilter));
  125928. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  125929. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  125930. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  125931. while( SQLITE_OK==rc ){
  125932. rc = sqlite3Fts3SegReaderStep(p, &csr);
  125933. if( rc!=SQLITE_ROW ) break;
  125934. rc = fts3SegWriterAdd(p, &pWriter, 1,
  125935. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  125936. }
  125937. if( rc!=SQLITE_OK ) goto finished;
  125938. assert( pWriter );
  125939. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  125940. rc = fts3DeleteSegdir(
  125941. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  125942. );
  125943. if( rc!=SQLITE_OK ) goto finished;
  125944. }
  125945. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  125946. finished:
  125947. fts3SegWriterFree(pWriter);
  125948. sqlite3Fts3SegReaderFinish(&csr);
  125949. return rc;
  125950. }
  125951. /*
  125952. ** Flush the contents of pendingTerms to level 0 segments.
  125953. */
  125954. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  125955. int rc = SQLITE_OK;
  125956. int i;
  125957. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  125958. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  125959. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  125960. }
  125961. sqlite3Fts3PendingTermsClear(p);
  125962. /* Determine the auto-incr-merge setting if unknown. If enabled,
  125963. ** estimate the number of leaf blocks of content to be written
  125964. */
  125965. if( rc==SQLITE_OK && p->bHasStat
  125966. && p->bAutoincrmerge==0xff && p->nLeafAdd>0
  125967. ){
  125968. sqlite3_stmt *pStmt = 0;
  125969. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  125970. if( rc==SQLITE_OK ){
  125971. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  125972. rc = sqlite3_step(pStmt);
  125973. p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
  125974. rc = sqlite3_reset(pStmt);
  125975. }
  125976. }
  125977. return rc;
  125978. }
  125979. /*
  125980. ** Encode N integers as varints into a blob.
  125981. */
  125982. static void fts3EncodeIntArray(
  125983. int N, /* The number of integers to encode */
  125984. u32 *a, /* The integer values */
  125985. char *zBuf, /* Write the BLOB here */
  125986. int *pNBuf /* Write number of bytes if zBuf[] used here */
  125987. ){
  125988. int i, j;
  125989. for(i=j=0; i<N; i++){
  125990. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  125991. }
  125992. *pNBuf = j;
  125993. }
  125994. /*
  125995. ** Decode a blob of varints into N integers
  125996. */
  125997. static void fts3DecodeIntArray(
  125998. int N, /* The number of integers to decode */
  125999. u32 *a, /* Write the integer values */
  126000. const char *zBuf, /* The BLOB containing the varints */
  126001. int nBuf /* size of the BLOB */
  126002. ){
  126003. int i, j;
  126004. UNUSED_PARAMETER(nBuf);
  126005. for(i=j=0; i<N; i++){
  126006. sqlite3_int64 x;
  126007. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  126008. assert(j<=nBuf);
  126009. a[i] = (u32)(x & 0xffffffff);
  126010. }
  126011. }
  126012. /*
  126013. ** Insert the sizes (in tokens) for each column of the document
  126014. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  126015. ** a blob of varints.
  126016. */
  126017. static void fts3InsertDocsize(
  126018. int *pRC, /* Result code */
  126019. Fts3Table *p, /* Table into which to insert */
  126020. u32 *aSz /* Sizes of each column, in tokens */
  126021. ){
  126022. char *pBlob; /* The BLOB encoding of the document size */
  126023. int nBlob; /* Number of bytes in the BLOB */
  126024. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  126025. int rc; /* Result code from subfunctions */
  126026. if( *pRC ) return;
  126027. pBlob = sqlite3_malloc( 10*p->nColumn );
  126028. if( pBlob==0 ){
  126029. *pRC = SQLITE_NOMEM;
  126030. return;
  126031. }
  126032. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  126033. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  126034. if( rc ){
  126035. sqlite3_free(pBlob);
  126036. *pRC = rc;
  126037. return;
  126038. }
  126039. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  126040. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  126041. sqlite3_step(pStmt);
  126042. *pRC = sqlite3_reset(pStmt);
  126043. }
  126044. /*
  126045. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  126046. ** where N is the number of user defined columns in the fts3 table plus
  126047. ** two. If nCol is the number of user defined columns, then values of the
  126048. ** varints are set as follows:
  126049. **
  126050. ** Varint 0: Total number of rows in the table.
  126051. **
  126052. ** Varint 1..nCol: For each column, the total number of tokens stored in
  126053. ** the column for all rows of the table.
  126054. **
  126055. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  126056. ** columns of all rows of the table.
  126057. **
  126058. */
  126059. static void fts3UpdateDocTotals(
  126060. int *pRC, /* The result code */
  126061. Fts3Table *p, /* Table being updated */
  126062. u32 *aSzIns, /* Size increases */
  126063. u32 *aSzDel, /* Size decreases */
  126064. int nChng /* Change in the number of documents */
  126065. ){
  126066. char *pBlob; /* Storage for BLOB written into %_stat */
  126067. int nBlob; /* Size of BLOB written into %_stat */
  126068. u32 *a; /* Array of integers that becomes the BLOB */
  126069. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  126070. int i; /* Loop counter */
  126071. int rc; /* Result code from subfunctions */
  126072. const int nStat = p->nColumn+2;
  126073. if( *pRC ) return;
  126074. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  126075. if( a==0 ){
  126076. *pRC = SQLITE_NOMEM;
  126077. return;
  126078. }
  126079. pBlob = (char*)&a[nStat];
  126080. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  126081. if( rc ){
  126082. sqlite3_free(a);
  126083. *pRC = rc;
  126084. return;
  126085. }
  126086. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  126087. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  126088. fts3DecodeIntArray(nStat, a,
  126089. sqlite3_column_blob(pStmt, 0),
  126090. sqlite3_column_bytes(pStmt, 0));
  126091. }else{
  126092. memset(a, 0, sizeof(u32)*(nStat) );
  126093. }
  126094. rc = sqlite3_reset(pStmt);
  126095. if( rc!=SQLITE_OK ){
  126096. sqlite3_free(a);
  126097. *pRC = rc;
  126098. return;
  126099. }
  126100. if( nChng<0 && a[0]<(u32)(-nChng) ){
  126101. a[0] = 0;
  126102. }else{
  126103. a[0] += nChng;
  126104. }
  126105. for(i=0; i<p->nColumn+1; i++){
  126106. u32 x = a[i+1];
  126107. if( x+aSzIns[i] < aSzDel[i] ){
  126108. x = 0;
  126109. }else{
  126110. x = x + aSzIns[i] - aSzDel[i];
  126111. }
  126112. a[i+1] = x;
  126113. }
  126114. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  126115. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  126116. if( rc ){
  126117. sqlite3_free(a);
  126118. *pRC = rc;
  126119. return;
  126120. }
  126121. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  126122. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  126123. sqlite3_step(pStmt);
  126124. *pRC = sqlite3_reset(pStmt);
  126125. sqlite3_free(a);
  126126. }
  126127. /*
  126128. ** Merge the entire database so that there is one segment for each
  126129. ** iIndex/iLangid combination.
  126130. */
  126131. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  126132. int bSeenDone = 0;
  126133. int rc;
  126134. sqlite3_stmt *pAllLangid = 0;
  126135. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  126136. if( rc==SQLITE_OK ){
  126137. int rc2;
  126138. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  126139. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  126140. int i;
  126141. int iLangid = sqlite3_column_int(pAllLangid, 0);
  126142. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  126143. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  126144. if( rc==SQLITE_DONE ){
  126145. bSeenDone = 1;
  126146. rc = SQLITE_OK;
  126147. }
  126148. }
  126149. }
  126150. rc2 = sqlite3_reset(pAllLangid);
  126151. if( rc==SQLITE_OK ) rc = rc2;
  126152. }
  126153. sqlite3Fts3SegmentsClose(p);
  126154. sqlite3Fts3PendingTermsClear(p);
  126155. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  126156. }
  126157. /*
  126158. ** This function is called when the user executes the following statement:
  126159. **
  126160. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  126161. **
  126162. ** The entire FTS index is discarded and rebuilt. If the table is one
  126163. ** created using the content=xxx option, then the new index is based on
  126164. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  126165. ** on the contents of the %_content table.
  126166. */
  126167. static int fts3DoRebuild(Fts3Table *p){
  126168. int rc; /* Return Code */
  126169. rc = fts3DeleteAll(p, 0);
  126170. if( rc==SQLITE_OK ){
  126171. u32 *aSz = 0;
  126172. u32 *aSzIns = 0;
  126173. u32 *aSzDel = 0;
  126174. sqlite3_stmt *pStmt = 0;
  126175. int nEntry = 0;
  126176. /* Compose and prepare an SQL statement to loop through the content table */
  126177. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  126178. if( !zSql ){
  126179. rc = SQLITE_NOMEM;
  126180. }else{
  126181. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  126182. sqlite3_free(zSql);
  126183. }
  126184. if( rc==SQLITE_OK ){
  126185. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  126186. aSz = (u32 *)sqlite3_malloc(nByte);
  126187. if( aSz==0 ){
  126188. rc = SQLITE_NOMEM;
  126189. }else{
  126190. memset(aSz, 0, nByte);
  126191. aSzIns = &aSz[p->nColumn+1];
  126192. aSzDel = &aSzIns[p->nColumn+1];
  126193. }
  126194. }
  126195. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  126196. int iCol;
  126197. int iLangid = langidFromSelect(p, pStmt);
  126198. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
  126199. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  126200. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  126201. if( p->abNotindexed[iCol]==0 ){
  126202. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  126203. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  126204. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  126205. }
  126206. }
  126207. if( p->bHasDocsize ){
  126208. fts3InsertDocsize(&rc, p, aSz);
  126209. }
  126210. if( rc!=SQLITE_OK ){
  126211. sqlite3_finalize(pStmt);
  126212. pStmt = 0;
  126213. }else{
  126214. nEntry++;
  126215. for(iCol=0; iCol<=p->nColumn; iCol++){
  126216. aSzIns[iCol] += aSz[iCol];
  126217. }
  126218. }
  126219. }
  126220. if( p->bFts4 ){
  126221. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  126222. }
  126223. sqlite3_free(aSz);
  126224. if( pStmt ){
  126225. int rc2 = sqlite3_finalize(pStmt);
  126226. if( rc==SQLITE_OK ){
  126227. rc = rc2;
  126228. }
  126229. }
  126230. }
  126231. return rc;
  126232. }
  126233. /*
  126234. ** This function opens a cursor used to read the input data for an
  126235. ** incremental merge operation. Specifically, it opens a cursor to scan
  126236. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  126237. ** level iAbsLevel.
  126238. */
  126239. static int fts3IncrmergeCsr(
  126240. Fts3Table *p, /* FTS3 table handle */
  126241. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  126242. int nSeg, /* Number of segments to merge */
  126243. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  126244. ){
  126245. int rc; /* Return Code */
  126246. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  126247. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  126248. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  126249. memset(pCsr, 0, sizeof(*pCsr));
  126250. nByte = sizeof(Fts3SegReader *) * nSeg;
  126251. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  126252. if( pCsr->apSegment==0 ){
  126253. rc = SQLITE_NOMEM;
  126254. }else{
  126255. memset(pCsr->apSegment, 0, nByte);
  126256. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  126257. }
  126258. if( rc==SQLITE_OK ){
  126259. int i;
  126260. int rc2;
  126261. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  126262. assert( pCsr->nSegment==0 );
  126263. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  126264. rc = sqlite3Fts3SegReaderNew(i, 0,
  126265. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  126266. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  126267. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  126268. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  126269. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  126270. &pCsr->apSegment[i]
  126271. );
  126272. pCsr->nSegment++;
  126273. }
  126274. rc2 = sqlite3_reset(pStmt);
  126275. if( rc==SQLITE_OK ) rc = rc2;
  126276. }
  126277. return rc;
  126278. }
  126279. typedef struct IncrmergeWriter IncrmergeWriter;
  126280. typedef struct NodeWriter NodeWriter;
  126281. typedef struct Blob Blob;
  126282. typedef struct NodeReader NodeReader;
  126283. /*
  126284. ** An instance of the following structure is used as a dynamic buffer
  126285. ** to build up nodes or other blobs of data in.
  126286. **
  126287. ** The function blobGrowBuffer() is used to extend the allocation.
  126288. */
  126289. struct Blob {
  126290. char *a; /* Pointer to allocation */
  126291. int n; /* Number of valid bytes of data in a[] */
  126292. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  126293. };
  126294. /*
  126295. ** This structure is used to build up buffers containing segment b-tree
  126296. ** nodes (blocks).
  126297. */
  126298. struct NodeWriter {
  126299. sqlite3_int64 iBlock; /* Current block id */
  126300. Blob key; /* Last key written to the current block */
  126301. Blob block; /* Current block image */
  126302. };
  126303. /*
  126304. ** An object of this type contains the state required to create or append
  126305. ** to an appendable b-tree segment.
  126306. */
  126307. struct IncrmergeWriter {
  126308. int nLeafEst; /* Space allocated for leaf blocks */
  126309. int nWork; /* Number of leaf pages flushed */
  126310. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  126311. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  126312. sqlite3_int64 iStart; /* Block number of first allocated block */
  126313. sqlite3_int64 iEnd; /* Block number of last allocated block */
  126314. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  126315. };
  126316. /*
  126317. ** An object of the following type is used to read data from a single
  126318. ** FTS segment node. See the following functions:
  126319. **
  126320. ** nodeReaderInit()
  126321. ** nodeReaderNext()
  126322. ** nodeReaderRelease()
  126323. */
  126324. struct NodeReader {
  126325. const char *aNode;
  126326. int nNode;
  126327. int iOff; /* Current offset within aNode[] */
  126328. /* Output variables. Containing the current node entry. */
  126329. sqlite3_int64 iChild; /* Pointer to child node */
  126330. Blob term; /* Current term */
  126331. const char *aDoclist; /* Pointer to doclist */
  126332. int nDoclist; /* Size of doclist in bytes */
  126333. };
  126334. /*
  126335. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  126336. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  126337. ** bytes in size, extend (realloc) it to be so.
  126338. **
  126339. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  126340. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  126341. ** to reflect the new size of the pBlob->a[] buffer.
  126342. */
  126343. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  126344. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  126345. int nAlloc = nMin;
  126346. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  126347. if( a ){
  126348. pBlob->nAlloc = nAlloc;
  126349. pBlob->a = a;
  126350. }else{
  126351. *pRc = SQLITE_NOMEM;
  126352. }
  126353. }
  126354. }
  126355. /*
  126356. ** Attempt to advance the node-reader object passed as the first argument to
  126357. ** the next entry on the node.
  126358. **
  126359. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  126360. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  126361. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  126362. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  126363. ** variables for the new entry.
  126364. */
  126365. static int nodeReaderNext(NodeReader *p){
  126366. int bFirst = (p->term.n==0); /* True for first term on the node */
  126367. int nPrefix = 0; /* Bytes to copy from previous term */
  126368. int nSuffix = 0; /* Bytes to append to the prefix */
  126369. int rc = SQLITE_OK; /* Return code */
  126370. assert( p->aNode );
  126371. if( p->iChild && bFirst==0 ) p->iChild++;
  126372. if( p->iOff>=p->nNode ){
  126373. /* EOF */
  126374. p->aNode = 0;
  126375. }else{
  126376. if( bFirst==0 ){
  126377. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  126378. }
  126379. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  126380. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  126381. if( rc==SQLITE_OK ){
  126382. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  126383. p->term.n = nPrefix+nSuffix;
  126384. p->iOff += nSuffix;
  126385. if( p->iChild==0 ){
  126386. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  126387. p->aDoclist = &p->aNode[p->iOff];
  126388. p->iOff += p->nDoclist;
  126389. }
  126390. }
  126391. }
  126392. assert( p->iOff<=p->nNode );
  126393. return rc;
  126394. }
  126395. /*
  126396. ** Release all dynamic resources held by node-reader object *p.
  126397. */
  126398. static void nodeReaderRelease(NodeReader *p){
  126399. sqlite3_free(p->term.a);
  126400. }
  126401. /*
  126402. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  126403. **
  126404. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  126405. ** point to the first entry on the node (if any). Otherwise, an SQLite
  126406. ** error code is returned.
  126407. */
  126408. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  126409. memset(p, 0, sizeof(NodeReader));
  126410. p->aNode = aNode;
  126411. p->nNode = nNode;
  126412. /* Figure out if this is a leaf or an internal node. */
  126413. if( p->aNode[0] ){
  126414. /* An internal node. */
  126415. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  126416. }else{
  126417. p->iOff = 1;
  126418. }
  126419. return nodeReaderNext(p);
  126420. }
  126421. /*
  126422. ** This function is called while writing an FTS segment each time a leaf o
  126423. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  126424. ** to be greater than the largest key on the node just written, but smaller
  126425. ** than or equal to the first key that will be written to the next leaf
  126426. ** node.
  126427. **
  126428. ** The block id of the leaf node just written to disk may be found in
  126429. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  126430. */
  126431. static int fts3IncrmergePush(
  126432. Fts3Table *p, /* Fts3 table handle */
  126433. IncrmergeWriter *pWriter, /* Writer object */
  126434. const char *zTerm, /* Term to write to internal node */
  126435. int nTerm /* Bytes at zTerm */
  126436. ){
  126437. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  126438. int iLayer;
  126439. assert( nTerm>0 );
  126440. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  126441. sqlite3_int64 iNextPtr = 0;
  126442. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  126443. int rc = SQLITE_OK;
  126444. int nPrefix;
  126445. int nSuffix;
  126446. int nSpace;
  126447. /* Figure out how much space the key will consume if it is written to
  126448. ** the current node of layer iLayer. Due to the prefix compression,
  126449. ** the space required changes depending on which node the key is to
  126450. ** be added to. */
  126451. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  126452. nSuffix = nTerm - nPrefix;
  126453. nSpace = sqlite3Fts3VarintLen(nPrefix);
  126454. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  126455. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  126456. /* If the current node of layer iLayer contains zero keys, or if adding
  126457. ** the key to it will not cause it to grow to larger than nNodeSize
  126458. ** bytes in size, write the key here. */
  126459. Blob *pBlk = &pNode->block;
  126460. if( pBlk->n==0 ){
  126461. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  126462. if( rc==SQLITE_OK ){
  126463. pBlk->a[0] = (char)iLayer;
  126464. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  126465. }
  126466. }
  126467. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  126468. blobGrowBuffer(&pNode->key, nTerm, &rc);
  126469. if( rc==SQLITE_OK ){
  126470. if( pNode->key.n ){
  126471. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  126472. }
  126473. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  126474. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  126475. pBlk->n += nSuffix;
  126476. memcpy(pNode->key.a, zTerm, nTerm);
  126477. pNode->key.n = nTerm;
  126478. }
  126479. }else{
  126480. /* Otherwise, flush the current node of layer iLayer to disk.
  126481. ** Then allocate a new, empty sibling node. The key will be written
  126482. ** into the parent of this node. */
  126483. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  126484. assert( pNode->block.nAlloc>=p->nNodeSize );
  126485. pNode->block.a[0] = (char)iLayer;
  126486. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  126487. iNextPtr = pNode->iBlock;
  126488. pNode->iBlock++;
  126489. pNode->key.n = 0;
  126490. }
  126491. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  126492. iPtr = iNextPtr;
  126493. }
  126494. assert( 0 );
  126495. return 0;
  126496. }
  126497. /*
  126498. ** Append a term and (optionally) doclist to the FTS segment node currently
  126499. ** stored in blob *pNode. The node need not contain any terms, but the
  126500. ** header must be written before this function is called.
  126501. **
  126502. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  126503. ** followed by the left-hand-child varint for an internal node.
  126504. **
  126505. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  126506. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  126507. ** node, both aDoclist and nDoclist must be passed 0.
  126508. **
  126509. ** If the size of the value in blob pPrev is zero, then this is the first
  126510. ** term written to the node. Otherwise, pPrev contains a copy of the
  126511. ** previous term. Before this function returns, it is updated to contain a
  126512. ** copy of zTerm/nTerm.
  126513. **
  126514. ** It is assumed that the buffer associated with pNode is already large
  126515. ** enough to accommodate the new entry. The buffer associated with pPrev
  126516. ** is extended by this function if requrired.
  126517. **
  126518. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  126519. ** returned. Otherwise, SQLITE_OK.
  126520. */
  126521. static int fts3AppendToNode(
  126522. Blob *pNode, /* Current node image to append to */
  126523. Blob *pPrev, /* Buffer containing previous term written */
  126524. const char *zTerm, /* New term to write */
  126525. int nTerm, /* Size of zTerm in bytes */
  126526. const char *aDoclist, /* Doclist (or NULL) to write */
  126527. int nDoclist /* Size of aDoclist in bytes */
  126528. ){
  126529. int rc = SQLITE_OK; /* Return code */
  126530. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  126531. int nPrefix; /* Size of term prefix in bytes */
  126532. int nSuffix; /* Size of term suffix in bytes */
  126533. /* Node must have already been started. There must be a doclist for a
  126534. ** leaf node, and there must not be a doclist for an internal node. */
  126535. assert( pNode->n>0 );
  126536. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  126537. blobGrowBuffer(pPrev, nTerm, &rc);
  126538. if( rc!=SQLITE_OK ) return rc;
  126539. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  126540. nSuffix = nTerm - nPrefix;
  126541. memcpy(pPrev->a, zTerm, nTerm);
  126542. pPrev->n = nTerm;
  126543. if( bFirst==0 ){
  126544. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  126545. }
  126546. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  126547. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  126548. pNode->n += nSuffix;
  126549. if( aDoclist ){
  126550. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  126551. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  126552. pNode->n += nDoclist;
  126553. }
  126554. assert( pNode->n<=pNode->nAlloc );
  126555. return SQLITE_OK;
  126556. }
  126557. /*
  126558. ** Append the current term and doclist pointed to by cursor pCsr to the
  126559. ** appendable b-tree segment opened for writing by pWriter.
  126560. **
  126561. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  126562. */
  126563. static int fts3IncrmergeAppend(
  126564. Fts3Table *p, /* Fts3 table handle */
  126565. IncrmergeWriter *pWriter, /* Writer object */
  126566. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  126567. ){
  126568. const char *zTerm = pCsr->zTerm;
  126569. int nTerm = pCsr->nTerm;
  126570. const char *aDoclist = pCsr->aDoclist;
  126571. int nDoclist = pCsr->nDoclist;
  126572. int rc = SQLITE_OK; /* Return code */
  126573. int nSpace; /* Total space in bytes required on leaf */
  126574. int nPrefix; /* Size of prefix shared with previous term */
  126575. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  126576. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  126577. pLeaf = &pWriter->aNodeWriter[0];
  126578. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  126579. nSuffix = nTerm - nPrefix;
  126580. nSpace = sqlite3Fts3VarintLen(nPrefix);
  126581. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  126582. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  126583. /* If the current block is not empty, and if adding this term/doclist
  126584. ** to the current block would make it larger than Fts3Table.nNodeSize
  126585. ** bytes, write this block out to the database. */
  126586. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  126587. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  126588. pWriter->nWork++;
  126589. /* Add the current term to the parent node. The term added to the
  126590. ** parent must:
  126591. **
  126592. ** a) be greater than the largest term on the leaf node just written
  126593. ** to the database (still available in pLeaf->key), and
  126594. **
  126595. ** b) be less than or equal to the term about to be added to the new
  126596. ** leaf node (zTerm/nTerm).
  126597. **
  126598. ** In other words, it must be the prefix of zTerm 1 byte longer than
  126599. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  126600. */
  126601. if( rc==SQLITE_OK ){
  126602. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  126603. }
  126604. /* Advance to the next output block */
  126605. pLeaf->iBlock++;
  126606. pLeaf->key.n = 0;
  126607. pLeaf->block.n = 0;
  126608. nSuffix = nTerm;
  126609. nSpace = 1;
  126610. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  126611. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  126612. }
  126613. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  126614. if( rc==SQLITE_OK ){
  126615. if( pLeaf->block.n==0 ){
  126616. pLeaf->block.n = 1;
  126617. pLeaf->block.a[0] = '\0';
  126618. }
  126619. rc = fts3AppendToNode(
  126620. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  126621. );
  126622. }
  126623. return rc;
  126624. }
  126625. /*
  126626. ** This function is called to release all dynamic resources held by the
  126627. ** merge-writer object pWriter, and if no error has occurred, to flush
  126628. ** all outstanding node buffers held by pWriter to disk.
  126629. **
  126630. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  126631. ** is made to write any data to disk. Instead, this function serves only
  126632. ** to release outstanding resources.
  126633. **
  126634. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  126635. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  126636. ** returning.
  126637. */
  126638. static void fts3IncrmergeRelease(
  126639. Fts3Table *p, /* FTS3 table handle */
  126640. IncrmergeWriter *pWriter, /* Merge-writer object */
  126641. int *pRc /* IN/OUT: Error code */
  126642. ){
  126643. int i; /* Used to iterate through non-root layers */
  126644. int iRoot; /* Index of root in pWriter->aNodeWriter */
  126645. NodeWriter *pRoot; /* NodeWriter for root node */
  126646. int rc = *pRc; /* Error code */
  126647. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  126648. ** root node. If the segment fits entirely on a single leaf node, iRoot
  126649. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  126650. ** will be 1. And so on. */
  126651. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  126652. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  126653. if( pNode->block.n>0 ) break;
  126654. assert( *pRc || pNode->block.nAlloc==0 );
  126655. assert( *pRc || pNode->key.nAlloc==0 );
  126656. sqlite3_free(pNode->block.a);
  126657. sqlite3_free(pNode->key.a);
  126658. }
  126659. /* Empty output segment. This is a no-op. */
  126660. if( iRoot<0 ) return;
  126661. /* The entire output segment fits on a single node. Normally, this means
  126662. ** the node would be stored as a blob in the "root" column of the %_segdir
  126663. ** table. However, this is not permitted in this case. The problem is that
  126664. ** space has already been reserved in the %_segments table, and so the
  126665. ** start_block and end_block fields of the %_segdir table must be populated.
  126666. ** And, by design or by accident, released versions of FTS cannot handle
  126667. ** segments that fit entirely on the root node with start_block!=0.
  126668. **
  126669. ** Instead, create a synthetic root node that contains nothing but a
  126670. ** pointer to the single content node. So that the segment consists of a
  126671. ** single leaf and a single interior (root) node.
  126672. **
  126673. ** Todo: Better might be to defer allocating space in the %_segments
  126674. ** table until we are sure it is needed.
  126675. */
  126676. if( iRoot==0 ){
  126677. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  126678. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  126679. if( rc==SQLITE_OK ){
  126680. pBlock->a[0] = 0x01;
  126681. pBlock->n = 1 + sqlite3Fts3PutVarint(
  126682. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  126683. );
  126684. }
  126685. iRoot = 1;
  126686. }
  126687. pRoot = &pWriter->aNodeWriter[iRoot];
  126688. /* Flush all currently outstanding nodes to disk. */
  126689. for(i=0; i<iRoot; i++){
  126690. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  126691. if( pNode->block.n>0 && rc==SQLITE_OK ){
  126692. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  126693. }
  126694. sqlite3_free(pNode->block.a);
  126695. sqlite3_free(pNode->key.a);
  126696. }
  126697. /* Write the %_segdir record. */
  126698. if( rc==SQLITE_OK ){
  126699. rc = fts3WriteSegdir(p,
  126700. pWriter->iAbsLevel+1, /* level */
  126701. pWriter->iIdx, /* idx */
  126702. pWriter->iStart, /* start_block */
  126703. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  126704. pWriter->iEnd, /* end_block */
  126705. pRoot->block.a, pRoot->block.n /* root */
  126706. );
  126707. }
  126708. sqlite3_free(pRoot->block.a);
  126709. sqlite3_free(pRoot->key.a);
  126710. *pRc = rc;
  126711. }
  126712. /*
  126713. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  126714. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  126715. ** the other, it is considered to be smaller than the other.
  126716. **
  126717. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  126718. ** if it is greater.
  126719. */
  126720. static int fts3TermCmp(
  126721. const char *zLhs, int nLhs, /* LHS of comparison */
  126722. const char *zRhs, int nRhs /* RHS of comparison */
  126723. ){
  126724. int nCmp = MIN(nLhs, nRhs);
  126725. int res;
  126726. res = memcmp(zLhs, zRhs, nCmp);
  126727. if( res==0 ) res = nLhs - nRhs;
  126728. return res;
  126729. }
  126730. /*
  126731. ** Query to see if the entry in the %_segments table with blockid iEnd is
  126732. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  126733. ** returning. Otherwise, set *pbRes to 0.
  126734. **
  126735. ** Or, if an error occurs while querying the database, return an SQLite
  126736. ** error code. The final value of *pbRes is undefined in this case.
  126737. **
  126738. ** This is used to test if a segment is an "appendable" segment. If it
  126739. ** is, then a NULL entry has been inserted into the %_segments table
  126740. ** with blockid %_segdir.end_block.
  126741. */
  126742. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  126743. int bRes = 0; /* Result to set *pbRes to */
  126744. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  126745. int rc; /* Return code */
  126746. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  126747. if( rc==SQLITE_OK ){
  126748. sqlite3_bind_int64(pCheck, 1, iEnd);
  126749. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  126750. rc = sqlite3_reset(pCheck);
  126751. }
  126752. *pbRes = bRes;
  126753. return rc;
  126754. }
  126755. /*
  126756. ** This function is called when initializing an incremental-merge operation.
  126757. ** It checks if the existing segment with index value iIdx at absolute level
  126758. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  126759. ** merge-writer object *pWriter is initialized to write to it.
  126760. **
  126761. ** An existing segment can be appended to by an incremental merge if:
  126762. **
  126763. ** * It was initially created as an appendable segment (with all required
  126764. ** space pre-allocated), and
  126765. **
  126766. ** * The first key read from the input (arguments zKey and nKey) is
  126767. ** greater than the largest key currently stored in the potential
  126768. ** output segment.
  126769. */
  126770. static int fts3IncrmergeLoad(
  126771. Fts3Table *p, /* Fts3 table handle */
  126772. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  126773. int iIdx, /* Index of candidate output segment */
  126774. const char *zKey, /* First key to write */
  126775. int nKey, /* Number of bytes in nKey */
  126776. IncrmergeWriter *pWriter /* Populate this object */
  126777. ){
  126778. int rc; /* Return code */
  126779. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  126780. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  126781. if( rc==SQLITE_OK ){
  126782. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  126783. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  126784. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  126785. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  126786. int nRoot = 0; /* Size of aRoot[] in bytes */
  126787. int rc2; /* Return code from sqlite3_reset() */
  126788. int bAppendable = 0; /* Set to true if segment is appendable */
  126789. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  126790. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  126791. sqlite3_bind_int(pSelect, 2, iIdx);
  126792. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  126793. iStart = sqlite3_column_int64(pSelect, 1);
  126794. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  126795. iEnd = sqlite3_column_int64(pSelect, 3);
  126796. nRoot = sqlite3_column_bytes(pSelect, 4);
  126797. aRoot = sqlite3_column_blob(pSelect, 4);
  126798. }else{
  126799. return sqlite3_reset(pSelect);
  126800. }
  126801. /* Check for the zero-length marker in the %_segments table */
  126802. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  126803. /* Check that zKey/nKey is larger than the largest key the candidate */
  126804. if( rc==SQLITE_OK && bAppendable ){
  126805. char *aLeaf = 0;
  126806. int nLeaf = 0;
  126807. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  126808. if( rc==SQLITE_OK ){
  126809. NodeReader reader;
  126810. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  126811. rc==SQLITE_OK && reader.aNode;
  126812. rc = nodeReaderNext(&reader)
  126813. ){
  126814. assert( reader.aNode );
  126815. }
  126816. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  126817. bAppendable = 0;
  126818. }
  126819. nodeReaderRelease(&reader);
  126820. }
  126821. sqlite3_free(aLeaf);
  126822. }
  126823. if( rc==SQLITE_OK && bAppendable ){
  126824. /* It is possible to append to this segment. Set up the IncrmergeWriter
  126825. ** object to do so. */
  126826. int i;
  126827. int nHeight = (int)aRoot[0];
  126828. NodeWriter *pNode;
  126829. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  126830. pWriter->iStart = iStart;
  126831. pWriter->iEnd = iEnd;
  126832. pWriter->iAbsLevel = iAbsLevel;
  126833. pWriter->iIdx = iIdx;
  126834. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  126835. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  126836. }
  126837. pNode = &pWriter->aNodeWriter[nHeight];
  126838. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  126839. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  126840. if( rc==SQLITE_OK ){
  126841. memcpy(pNode->block.a, aRoot, nRoot);
  126842. pNode->block.n = nRoot;
  126843. }
  126844. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  126845. NodeReader reader;
  126846. pNode = &pWriter->aNodeWriter[i];
  126847. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  126848. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  126849. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  126850. if( rc==SQLITE_OK ){
  126851. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  126852. pNode->key.n = reader.term.n;
  126853. if( i>0 ){
  126854. char *aBlock = 0;
  126855. int nBlock = 0;
  126856. pNode = &pWriter->aNodeWriter[i-1];
  126857. pNode->iBlock = reader.iChild;
  126858. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  126859. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  126860. if( rc==SQLITE_OK ){
  126861. memcpy(pNode->block.a, aBlock, nBlock);
  126862. pNode->block.n = nBlock;
  126863. }
  126864. sqlite3_free(aBlock);
  126865. }
  126866. }
  126867. nodeReaderRelease(&reader);
  126868. }
  126869. }
  126870. rc2 = sqlite3_reset(pSelect);
  126871. if( rc==SQLITE_OK ) rc = rc2;
  126872. }
  126873. return rc;
  126874. }
  126875. /*
  126876. ** Determine the largest segment index value that exists within absolute
  126877. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  126878. ** one before returning SQLITE_OK. Or, if there are no segments at all
  126879. ** within level iAbsLevel, set *piIdx to zero.
  126880. **
  126881. ** If an error occurs, return an SQLite error code. The final value of
  126882. ** *piIdx is undefined in this case.
  126883. */
  126884. static int fts3IncrmergeOutputIdx(
  126885. Fts3Table *p, /* FTS Table handle */
  126886. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  126887. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  126888. ){
  126889. int rc;
  126890. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  126891. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  126892. if( rc==SQLITE_OK ){
  126893. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  126894. sqlite3_step(pOutputIdx);
  126895. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  126896. rc = sqlite3_reset(pOutputIdx);
  126897. }
  126898. return rc;
  126899. }
  126900. /*
  126901. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  126902. ** with idx value iIdx.
  126903. **
  126904. ** In the %_segdir table, a segment is defined by the values in three
  126905. ** columns:
  126906. **
  126907. ** start_block
  126908. ** leaves_end_block
  126909. ** end_block
  126910. **
  126911. ** When an appendable segment is allocated, it is estimated that the
  126912. ** maximum number of leaf blocks that may be required is the sum of the
  126913. ** number of leaf blocks consumed by the input segments, plus the number
  126914. ** of input segments, multiplied by two. This value is stored in stack
  126915. ** variable nLeafEst.
  126916. **
  126917. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  126918. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  126919. ** array of leaf nodes starts at the first block allocated. The array
  126920. ** of interior nodes that are parents of the leaf nodes start at block
  126921. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  126922. **
  126923. ** In the actual code below, the value "16" is replaced with the
  126924. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  126925. */
  126926. static int fts3IncrmergeWriter(
  126927. Fts3Table *p, /* Fts3 table handle */
  126928. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  126929. int iIdx, /* Index of new output segment */
  126930. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  126931. IncrmergeWriter *pWriter /* Populate this object */
  126932. ){
  126933. int rc; /* Return Code */
  126934. int i; /* Iterator variable */
  126935. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  126936. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  126937. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  126938. /* Calculate nLeafEst. */
  126939. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  126940. if( rc==SQLITE_OK ){
  126941. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  126942. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  126943. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  126944. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  126945. }
  126946. rc = sqlite3_reset(pLeafEst);
  126947. }
  126948. if( rc!=SQLITE_OK ) return rc;
  126949. /* Calculate the first block to use in the output segment */
  126950. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  126951. if( rc==SQLITE_OK ){
  126952. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  126953. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  126954. pWriter->iEnd = pWriter->iStart - 1;
  126955. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  126956. }
  126957. rc = sqlite3_reset(pFirstBlock);
  126958. }
  126959. if( rc!=SQLITE_OK ) return rc;
  126960. /* Insert the marker in the %_segments table to make sure nobody tries
  126961. ** to steal the space just allocated. This is also used to identify
  126962. ** appendable segments. */
  126963. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  126964. if( rc!=SQLITE_OK ) return rc;
  126965. pWriter->iAbsLevel = iAbsLevel;
  126966. pWriter->nLeafEst = nLeafEst;
  126967. pWriter->iIdx = iIdx;
  126968. /* Set up the array of NodeWriter objects */
  126969. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  126970. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  126971. }
  126972. return SQLITE_OK;
  126973. }
  126974. /*
  126975. ** Remove an entry from the %_segdir table. This involves running the
  126976. ** following two statements:
  126977. **
  126978. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  126979. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  126980. **
  126981. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  126982. ** statement ensures that the remaining segments have contiguously allocated
  126983. ** idx values.
  126984. */
  126985. static int fts3RemoveSegdirEntry(
  126986. Fts3Table *p, /* FTS3 table handle */
  126987. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  126988. int iIdx /* Index of %_segdir entry to delete */
  126989. ){
  126990. int rc; /* Return code */
  126991. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  126992. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  126993. if( rc==SQLITE_OK ){
  126994. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  126995. sqlite3_bind_int(pDelete, 2, iIdx);
  126996. sqlite3_step(pDelete);
  126997. rc = sqlite3_reset(pDelete);
  126998. }
  126999. return rc;
  127000. }
  127001. /*
  127002. ** One or more segments have just been removed from absolute level iAbsLevel.
  127003. ** Update the 'idx' values of the remaining segments in the level so that
  127004. ** the idx values are a contiguous sequence starting from 0.
  127005. */
  127006. static int fts3RepackSegdirLevel(
  127007. Fts3Table *p, /* FTS3 table handle */
  127008. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  127009. ){
  127010. int rc; /* Return code */
  127011. int *aIdx = 0; /* Array of remaining idx values */
  127012. int nIdx = 0; /* Valid entries in aIdx[] */
  127013. int nAlloc = 0; /* Allocated size of aIdx[] */
  127014. int i; /* Iterator variable */
  127015. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  127016. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  127017. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  127018. if( rc==SQLITE_OK ){
  127019. int rc2;
  127020. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  127021. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  127022. if( nIdx>=nAlloc ){
  127023. int *aNew;
  127024. nAlloc += 16;
  127025. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  127026. if( !aNew ){
  127027. rc = SQLITE_NOMEM;
  127028. break;
  127029. }
  127030. aIdx = aNew;
  127031. }
  127032. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  127033. }
  127034. rc2 = sqlite3_reset(pSelect);
  127035. if( rc==SQLITE_OK ) rc = rc2;
  127036. }
  127037. if( rc==SQLITE_OK ){
  127038. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  127039. }
  127040. if( rc==SQLITE_OK ){
  127041. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  127042. }
  127043. assert( p->bIgnoreSavepoint==0 );
  127044. p->bIgnoreSavepoint = 1;
  127045. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  127046. if( aIdx[i]!=i ){
  127047. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  127048. sqlite3_bind_int(pUpdate, 1, i);
  127049. sqlite3_step(pUpdate);
  127050. rc = sqlite3_reset(pUpdate);
  127051. }
  127052. }
  127053. p->bIgnoreSavepoint = 0;
  127054. sqlite3_free(aIdx);
  127055. return rc;
  127056. }
  127057. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  127058. pNode->a[0] = (char)iHeight;
  127059. if( iChild ){
  127060. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  127061. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  127062. }else{
  127063. assert( pNode->nAlloc>=1 );
  127064. pNode->n = 1;
  127065. }
  127066. }
  127067. /*
  127068. ** The first two arguments are a pointer to and the size of a segment b-tree
  127069. ** node. The node may be a leaf or an internal node.
  127070. **
  127071. ** This function creates a new node image in blob object *pNew by copying
  127072. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  127073. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  127074. */
  127075. static int fts3TruncateNode(
  127076. const char *aNode, /* Current node image */
  127077. int nNode, /* Size of aNode in bytes */
  127078. Blob *pNew, /* OUT: Write new node image here */
  127079. const char *zTerm, /* Omit all terms smaller than this */
  127080. int nTerm, /* Size of zTerm in bytes */
  127081. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  127082. ){
  127083. NodeReader reader; /* Reader object */
  127084. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  127085. int rc = SQLITE_OK; /* Return code */
  127086. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  127087. /* Allocate required output space */
  127088. blobGrowBuffer(pNew, nNode, &rc);
  127089. if( rc!=SQLITE_OK ) return rc;
  127090. pNew->n = 0;
  127091. /* Populate new node buffer */
  127092. for(rc = nodeReaderInit(&reader, aNode, nNode);
  127093. rc==SQLITE_OK && reader.aNode;
  127094. rc = nodeReaderNext(&reader)
  127095. ){
  127096. if( pNew->n==0 ){
  127097. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  127098. if( res<0 || (bLeaf==0 && res==0) ) continue;
  127099. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  127100. *piBlock = reader.iChild;
  127101. }
  127102. rc = fts3AppendToNode(
  127103. pNew, &prev, reader.term.a, reader.term.n,
  127104. reader.aDoclist, reader.nDoclist
  127105. );
  127106. if( rc!=SQLITE_OK ) break;
  127107. }
  127108. if( pNew->n==0 ){
  127109. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  127110. *piBlock = reader.iChild;
  127111. }
  127112. assert( pNew->n<=pNew->nAlloc );
  127113. nodeReaderRelease(&reader);
  127114. sqlite3_free(prev.a);
  127115. return rc;
  127116. }
  127117. /*
  127118. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  127119. ** level iAbsLevel. This may involve deleting entries from the %_segments
  127120. ** table, and modifying existing entries in both the %_segments and %_segdir
  127121. ** tables.
  127122. **
  127123. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  127124. ** SQLite error code otherwise.
  127125. */
  127126. static int fts3TruncateSegment(
  127127. Fts3Table *p, /* FTS3 table handle */
  127128. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  127129. int iIdx, /* Index within level of segment to modify */
  127130. const char *zTerm, /* Remove terms smaller than this */
  127131. int nTerm /* Number of bytes in buffer zTerm */
  127132. ){
  127133. int rc = SQLITE_OK; /* Return code */
  127134. Blob root = {0,0,0}; /* New root page image */
  127135. Blob block = {0,0,0}; /* Buffer used for any other block */
  127136. sqlite3_int64 iBlock = 0; /* Block id */
  127137. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  127138. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  127139. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  127140. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  127141. if( rc==SQLITE_OK ){
  127142. int rc2; /* sqlite3_reset() return code */
  127143. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  127144. sqlite3_bind_int(pFetch, 2, iIdx);
  127145. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  127146. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  127147. int nRoot = sqlite3_column_bytes(pFetch, 4);
  127148. iOldStart = sqlite3_column_int64(pFetch, 1);
  127149. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  127150. }
  127151. rc2 = sqlite3_reset(pFetch);
  127152. if( rc==SQLITE_OK ) rc = rc2;
  127153. }
  127154. while( rc==SQLITE_OK && iBlock ){
  127155. char *aBlock = 0;
  127156. int nBlock = 0;
  127157. iNewStart = iBlock;
  127158. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  127159. if( rc==SQLITE_OK ){
  127160. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  127161. }
  127162. if( rc==SQLITE_OK ){
  127163. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  127164. }
  127165. sqlite3_free(aBlock);
  127166. }
  127167. /* Variable iNewStart now contains the first valid leaf node. */
  127168. if( rc==SQLITE_OK && iNewStart ){
  127169. sqlite3_stmt *pDel = 0;
  127170. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  127171. if( rc==SQLITE_OK ){
  127172. sqlite3_bind_int64(pDel, 1, iOldStart);
  127173. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  127174. sqlite3_step(pDel);
  127175. rc = sqlite3_reset(pDel);
  127176. }
  127177. }
  127178. if( rc==SQLITE_OK ){
  127179. sqlite3_stmt *pChomp = 0;
  127180. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  127181. if( rc==SQLITE_OK ){
  127182. sqlite3_bind_int64(pChomp, 1, iNewStart);
  127183. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  127184. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  127185. sqlite3_bind_int(pChomp, 4, iIdx);
  127186. sqlite3_step(pChomp);
  127187. rc = sqlite3_reset(pChomp);
  127188. }
  127189. }
  127190. sqlite3_free(root.a);
  127191. sqlite3_free(block.a);
  127192. return rc;
  127193. }
  127194. /*
  127195. ** This function is called after an incrmental-merge operation has run to
  127196. ** merge (or partially merge) two or more segments from absolute level
  127197. ** iAbsLevel.
  127198. **
  127199. ** Each input segment is either removed from the db completely (if all of
  127200. ** its data was copied to the output segment by the incrmerge operation)
  127201. ** or modified in place so that it no longer contains those entries that
  127202. ** have been duplicated in the output segment.
  127203. */
  127204. static int fts3IncrmergeChomp(
  127205. Fts3Table *p, /* FTS table handle */
  127206. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  127207. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  127208. int *pnRem /* Number of segments not deleted */
  127209. ){
  127210. int i;
  127211. int nRem = 0;
  127212. int rc = SQLITE_OK;
  127213. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  127214. Fts3SegReader *pSeg = 0;
  127215. int j;
  127216. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  127217. ** somewhere in the pCsr->apSegment[] array. */
  127218. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  127219. pSeg = pCsr->apSegment[j];
  127220. if( pSeg->iIdx==i ) break;
  127221. }
  127222. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  127223. if( pSeg->aNode==0 ){
  127224. /* Seg-reader is at EOF. Remove the entire input segment. */
  127225. rc = fts3DeleteSegment(p, pSeg);
  127226. if( rc==SQLITE_OK ){
  127227. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  127228. }
  127229. *pnRem = 0;
  127230. }else{
  127231. /* The incremental merge did not copy all the data from this
  127232. ** segment to the upper level. The segment is modified in place
  127233. ** so that it contains no keys smaller than zTerm/nTerm. */
  127234. const char *zTerm = pSeg->zTerm;
  127235. int nTerm = pSeg->nTerm;
  127236. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  127237. nRem++;
  127238. }
  127239. }
  127240. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  127241. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  127242. }
  127243. *pnRem = nRem;
  127244. return rc;
  127245. }
  127246. /*
  127247. ** Store an incr-merge hint in the database.
  127248. */
  127249. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  127250. sqlite3_stmt *pReplace = 0;
  127251. int rc; /* Return code */
  127252. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  127253. if( rc==SQLITE_OK ){
  127254. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  127255. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  127256. sqlite3_step(pReplace);
  127257. rc = sqlite3_reset(pReplace);
  127258. }
  127259. return rc;
  127260. }
  127261. /*
  127262. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  127263. ** exists, is stored in the rowid==1 row of the %_stat table.
  127264. **
  127265. ** If successful, populate blob *pHint with the value read from the %_stat
  127266. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  127267. ** SQLite error code.
  127268. */
  127269. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  127270. sqlite3_stmt *pSelect = 0;
  127271. int rc;
  127272. pHint->n = 0;
  127273. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  127274. if( rc==SQLITE_OK ){
  127275. int rc2;
  127276. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  127277. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  127278. const char *aHint = sqlite3_column_blob(pSelect, 0);
  127279. int nHint = sqlite3_column_bytes(pSelect, 0);
  127280. if( aHint ){
  127281. blobGrowBuffer(pHint, nHint, &rc);
  127282. if( rc==SQLITE_OK ){
  127283. memcpy(pHint->a, aHint, nHint);
  127284. pHint->n = nHint;
  127285. }
  127286. }
  127287. }
  127288. rc2 = sqlite3_reset(pSelect);
  127289. if( rc==SQLITE_OK ) rc = rc2;
  127290. }
  127291. return rc;
  127292. }
  127293. /*
  127294. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  127295. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  127296. ** consists of two varints, the absolute level number of the input segments
  127297. ** and the number of input segments.
  127298. **
  127299. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  127300. ** set *pRc to an SQLite error code before returning.
  127301. */
  127302. static void fts3IncrmergeHintPush(
  127303. Blob *pHint, /* Hint blob to append to */
  127304. i64 iAbsLevel, /* First varint to store in hint */
  127305. int nInput, /* Second varint to store in hint */
  127306. int *pRc /* IN/OUT: Error code */
  127307. ){
  127308. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  127309. if( *pRc==SQLITE_OK ){
  127310. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  127311. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  127312. }
  127313. }
  127314. /*
  127315. ** Read the last entry (most recently pushed) from the hint blob *pHint
  127316. ** and then remove the entry. Write the two values read to *piAbsLevel and
  127317. ** *pnInput before returning.
  127318. **
  127319. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  127320. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  127321. */
  127322. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  127323. const int nHint = pHint->n;
  127324. int i;
  127325. i = pHint->n-2;
  127326. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  127327. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  127328. pHint->n = i;
  127329. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  127330. i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
  127331. if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
  127332. return SQLITE_OK;
  127333. }
  127334. /*
  127335. ** Attempt an incremental merge that writes nMerge leaf blocks.
  127336. **
  127337. ** Incremental merges happen nMin segments at a time. The two
  127338. ** segments to be merged are the nMin oldest segments (the ones with
  127339. ** the smallest indexes) in the highest level that contains at least
  127340. ** nMin segments. Multiple merges might occur in an attempt to write the
  127341. ** quota of nMerge leaf blocks.
  127342. */
  127343. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  127344. int rc; /* Return code */
  127345. int nRem = nMerge; /* Number of leaf pages yet to be written */
  127346. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  127347. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  127348. IncrmergeWriter *pWriter; /* Writer object */
  127349. int nSeg = 0; /* Number of input segments */
  127350. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  127351. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  127352. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  127353. /* Allocate space for the cursor, filter and writer objects */
  127354. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  127355. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  127356. if( !pWriter ) return SQLITE_NOMEM;
  127357. pFilter = (Fts3SegFilter *)&pWriter[1];
  127358. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  127359. rc = fts3IncrmergeHintLoad(p, &hint);
  127360. while( rc==SQLITE_OK && nRem>0 ){
  127361. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  127362. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  127363. int bUseHint = 0; /* True if attempting to append */
  127364. /* Search the %_segdir table for the absolute level with the smallest
  127365. ** relative level number that contains at least nMin segments, if any.
  127366. ** If one is found, set iAbsLevel to the absolute level number and
  127367. ** nSeg to nMin. If no level with at least nMin segments can be found,
  127368. ** set nSeg to -1.
  127369. */
  127370. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  127371. sqlite3_bind_int(pFindLevel, 1, nMin);
  127372. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  127373. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  127374. nSeg = nMin;
  127375. }else{
  127376. nSeg = -1;
  127377. }
  127378. rc = sqlite3_reset(pFindLevel);
  127379. /* If the hint read from the %_stat table is not empty, check if the
  127380. ** last entry in it specifies a relative level smaller than or equal
  127381. ** to the level identified by the block above (if any). If so, this
  127382. ** iteration of the loop will work on merging at the hinted level.
  127383. */
  127384. if( rc==SQLITE_OK && hint.n ){
  127385. int nHint = hint.n;
  127386. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  127387. int nHintSeg = 0; /* Hint number of segments */
  127388. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  127389. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  127390. iAbsLevel = iHintAbsLevel;
  127391. nSeg = nHintSeg;
  127392. bUseHint = 1;
  127393. bDirtyHint = 1;
  127394. }else{
  127395. /* This undoes the effect of the HintPop() above - so that no entry
  127396. ** is removed from the hint blob. */
  127397. hint.n = nHint;
  127398. }
  127399. }
  127400. /* If nSeg is less that zero, then there is no level with at least
  127401. ** nMin segments and no hint in the %_stat table. No work to do.
  127402. ** Exit early in this case. */
  127403. if( nSeg<0 ) break;
  127404. /* Open a cursor to iterate through the contents of the oldest nSeg
  127405. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  127406. ** the 'hint' parameters, it is possible that there are less than nSeg
  127407. ** segments available in level iAbsLevel. In this case, no work is
  127408. ** done on iAbsLevel - fall through to the next iteration of the loop
  127409. ** to start work on some other level. */
  127410. memset(pWriter, 0, nAlloc);
  127411. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  127412. if( rc==SQLITE_OK ){
  127413. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  127414. }
  127415. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  127416. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  127417. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  127418. ){
  127419. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  127420. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  127421. if( rc==SQLITE_OK ){
  127422. if( bUseHint && iIdx>0 ){
  127423. const char *zKey = pCsr->zTerm;
  127424. int nKey = pCsr->nTerm;
  127425. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  127426. }else{
  127427. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  127428. }
  127429. }
  127430. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  127431. fts3LogMerge(nSeg, iAbsLevel);
  127432. do {
  127433. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  127434. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  127435. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  127436. }while( rc==SQLITE_ROW );
  127437. /* Update or delete the input segments */
  127438. if( rc==SQLITE_OK ){
  127439. nRem -= (1 + pWriter->nWork);
  127440. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  127441. if( nSeg!=0 ){
  127442. bDirtyHint = 1;
  127443. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  127444. }
  127445. }
  127446. }
  127447. fts3IncrmergeRelease(p, pWriter, &rc);
  127448. }
  127449. sqlite3Fts3SegReaderFinish(pCsr);
  127450. }
  127451. /* Write the hint values into the %_stat table for the next incr-merger */
  127452. if( bDirtyHint && rc==SQLITE_OK ){
  127453. rc = fts3IncrmergeHintStore(p, &hint);
  127454. }
  127455. sqlite3_free(pWriter);
  127456. sqlite3_free(hint.a);
  127457. return rc;
  127458. }
  127459. /*
  127460. ** Convert the text beginning at *pz into an integer and return
  127461. ** its value. Advance *pz to point to the first character past
  127462. ** the integer.
  127463. */
  127464. static int fts3Getint(const char **pz){
  127465. const char *z = *pz;
  127466. int i = 0;
  127467. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  127468. *pz = z;
  127469. return i;
  127470. }
  127471. /*
  127472. ** Process statements of the form:
  127473. **
  127474. ** INSERT INTO table(table) VALUES('merge=A,B');
  127475. **
  127476. ** A and B are integers that decode to be the number of leaf pages
  127477. ** written for the merge, and the minimum number of segments on a level
  127478. ** before it will be selected for a merge, respectively.
  127479. */
  127480. static int fts3DoIncrmerge(
  127481. Fts3Table *p, /* FTS3 table handle */
  127482. const char *zParam /* Nul-terminated string containing "A,B" */
  127483. ){
  127484. int rc;
  127485. int nMin = (FTS3_MERGE_COUNT / 2);
  127486. int nMerge = 0;
  127487. const char *z = zParam;
  127488. /* Read the first integer value */
  127489. nMerge = fts3Getint(&z);
  127490. /* If the first integer value is followed by a ',', read the second
  127491. ** integer value. */
  127492. if( z[0]==',' && z[1]!='\0' ){
  127493. z++;
  127494. nMin = fts3Getint(&z);
  127495. }
  127496. if( z[0]!='\0' || nMin<2 ){
  127497. rc = SQLITE_ERROR;
  127498. }else{
  127499. rc = SQLITE_OK;
  127500. if( !p->bHasStat ){
  127501. assert( p->bFts4==0 );
  127502. sqlite3Fts3CreateStatTable(&rc, p);
  127503. }
  127504. if( rc==SQLITE_OK ){
  127505. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  127506. }
  127507. sqlite3Fts3SegmentsClose(p);
  127508. }
  127509. return rc;
  127510. }
  127511. /*
  127512. ** Process statements of the form:
  127513. **
  127514. ** INSERT INTO table(table) VALUES('automerge=X');
  127515. **
  127516. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  127517. ** turn it on. The setting is persistent.
  127518. */
  127519. static int fts3DoAutoincrmerge(
  127520. Fts3Table *p, /* FTS3 table handle */
  127521. const char *zParam /* Nul-terminated string containing boolean */
  127522. ){
  127523. int rc = SQLITE_OK;
  127524. sqlite3_stmt *pStmt = 0;
  127525. p->bAutoincrmerge = fts3Getint(&zParam)!=0;
  127526. if( !p->bHasStat ){
  127527. assert( p->bFts4==0 );
  127528. sqlite3Fts3CreateStatTable(&rc, p);
  127529. if( rc ) return rc;
  127530. }
  127531. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  127532. if( rc ) return rc;
  127533. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  127534. sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
  127535. sqlite3_step(pStmt);
  127536. rc = sqlite3_reset(pStmt);
  127537. return rc;
  127538. }
  127539. /*
  127540. ** Return a 64-bit checksum for the FTS index entry specified by the
  127541. ** arguments to this function.
  127542. */
  127543. static u64 fts3ChecksumEntry(
  127544. const char *zTerm, /* Pointer to buffer containing term */
  127545. int nTerm, /* Size of zTerm in bytes */
  127546. int iLangid, /* Language id for current row */
  127547. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  127548. i64 iDocid, /* Docid for current row. */
  127549. int iCol, /* Column number */
  127550. int iPos /* Position */
  127551. ){
  127552. int i;
  127553. u64 ret = (u64)iDocid;
  127554. ret += (ret<<3) + iLangid;
  127555. ret += (ret<<3) + iIndex;
  127556. ret += (ret<<3) + iCol;
  127557. ret += (ret<<3) + iPos;
  127558. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  127559. return ret;
  127560. }
  127561. /*
  127562. ** Return a checksum of all entries in the FTS index that correspond to
  127563. ** language id iLangid. The checksum is calculated by XORing the checksums
  127564. ** of each individual entry (see fts3ChecksumEntry()) together.
  127565. **
  127566. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  127567. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  127568. ** return value is undefined in this case.
  127569. */
  127570. static u64 fts3ChecksumIndex(
  127571. Fts3Table *p, /* FTS3 table handle */
  127572. int iLangid, /* Language id to return cksum for */
  127573. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  127574. int *pRc /* OUT: Return code */
  127575. ){
  127576. Fts3SegFilter filter;
  127577. Fts3MultiSegReader csr;
  127578. int rc;
  127579. u64 cksum = 0;
  127580. assert( *pRc==SQLITE_OK );
  127581. memset(&filter, 0, sizeof(filter));
  127582. memset(&csr, 0, sizeof(csr));
  127583. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  127584. filter.flags |= FTS3_SEGMENT_SCAN;
  127585. rc = sqlite3Fts3SegReaderCursor(
  127586. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  127587. );
  127588. if( rc==SQLITE_OK ){
  127589. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  127590. }
  127591. if( rc==SQLITE_OK ){
  127592. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  127593. char *pCsr = csr.aDoclist;
  127594. char *pEnd = &pCsr[csr.nDoclist];
  127595. i64 iDocid = 0;
  127596. i64 iCol = 0;
  127597. i64 iPos = 0;
  127598. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  127599. while( pCsr<pEnd ){
  127600. i64 iVal = 0;
  127601. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  127602. if( pCsr<pEnd ){
  127603. if( iVal==0 || iVal==1 ){
  127604. iCol = 0;
  127605. iPos = 0;
  127606. if( iVal ){
  127607. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  127608. }else{
  127609. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  127610. iDocid += iVal;
  127611. }
  127612. }else{
  127613. iPos += (iVal - 2);
  127614. cksum = cksum ^ fts3ChecksumEntry(
  127615. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  127616. (int)iCol, (int)iPos
  127617. );
  127618. }
  127619. }
  127620. }
  127621. }
  127622. }
  127623. sqlite3Fts3SegReaderFinish(&csr);
  127624. *pRc = rc;
  127625. return cksum;
  127626. }
  127627. /*
  127628. ** Check if the contents of the FTS index match the current contents of the
  127629. ** content table. If no error occurs and the contents do match, set *pbOk
  127630. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  127631. ** to false before returning.
  127632. **
  127633. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  127634. ** code. The final value of *pbOk is undefined in this case.
  127635. */
  127636. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  127637. int rc = SQLITE_OK; /* Return code */
  127638. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  127639. u64 cksum2 = 0; /* Checksum based on %_content contents */
  127640. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  127641. /* This block calculates the checksum according to the FTS index. */
  127642. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  127643. if( rc==SQLITE_OK ){
  127644. int rc2;
  127645. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  127646. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  127647. int iLangid = sqlite3_column_int(pAllLangid, 0);
  127648. int i;
  127649. for(i=0; i<p->nIndex; i++){
  127650. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  127651. }
  127652. }
  127653. rc2 = sqlite3_reset(pAllLangid);
  127654. if( rc==SQLITE_OK ) rc = rc2;
  127655. }
  127656. /* This block calculates the checksum according to the %_content table */
  127657. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  127658. if( rc==SQLITE_OK ){
  127659. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  127660. sqlite3_stmt *pStmt = 0;
  127661. char *zSql;
  127662. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  127663. if( !zSql ){
  127664. rc = SQLITE_NOMEM;
  127665. }else{
  127666. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  127667. sqlite3_free(zSql);
  127668. }
  127669. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  127670. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  127671. int iLang = langidFromSelect(p, pStmt);
  127672. int iCol;
  127673. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  127674. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  127675. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  127676. sqlite3_tokenizer_cursor *pT = 0;
  127677. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
  127678. while( rc==SQLITE_OK ){
  127679. char const *zToken; /* Buffer containing token */
  127680. int nToken = 0; /* Number of bytes in token */
  127681. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  127682. int iPos = 0; /* Position of token in zText */
  127683. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  127684. if( rc==SQLITE_OK ){
  127685. int i;
  127686. cksum2 = cksum2 ^ fts3ChecksumEntry(
  127687. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  127688. );
  127689. for(i=1; i<p->nIndex; i++){
  127690. if( p->aIndex[i].nPrefix<=nToken ){
  127691. cksum2 = cksum2 ^ fts3ChecksumEntry(
  127692. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  127693. );
  127694. }
  127695. }
  127696. }
  127697. }
  127698. if( pT ) pModule->xClose(pT);
  127699. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  127700. }
  127701. }
  127702. sqlite3_finalize(pStmt);
  127703. }
  127704. *pbOk = (cksum1==cksum2);
  127705. return rc;
  127706. }
  127707. /*
  127708. ** Run the integrity-check. If no error occurs and the current contents of
  127709. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  127710. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  127711. **
  127712. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  127713. ** error code.
  127714. **
  127715. ** The integrity-check works as follows. For each token and indexed token
  127716. ** prefix in the document set, a 64-bit checksum is calculated (by code
  127717. ** in fts3ChecksumEntry()) based on the following:
  127718. **
  127719. ** + The index number (0 for the main index, 1 for the first prefix
  127720. ** index etc.),
  127721. ** + The token (or token prefix) text itself,
  127722. ** + The language-id of the row it appears in,
  127723. ** + The docid of the row it appears in,
  127724. ** + The column it appears in, and
  127725. ** + The tokens position within that column.
  127726. **
  127727. ** The checksums for all entries in the index are XORed together to create
  127728. ** a single checksum for the entire index.
  127729. **
  127730. ** The integrity-check code calculates the same checksum in two ways:
  127731. **
  127732. ** 1. By scanning the contents of the FTS index, and
  127733. ** 2. By scanning and tokenizing the content table.
  127734. **
  127735. ** If the two checksums are identical, the integrity-check is deemed to have
  127736. ** passed.
  127737. */
  127738. static int fts3DoIntegrityCheck(
  127739. Fts3Table *p /* FTS3 table handle */
  127740. ){
  127741. int rc;
  127742. int bOk = 0;
  127743. rc = fts3IntegrityCheck(p, &bOk);
  127744. if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
  127745. return rc;
  127746. }
  127747. /*
  127748. ** Handle a 'special' INSERT of the form:
  127749. **
  127750. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  127751. **
  127752. ** Argument pVal contains the result of <expr>. Currently the only
  127753. ** meaningful value to insert is the text 'optimize'.
  127754. */
  127755. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  127756. int rc; /* Return Code */
  127757. const char *zVal = (const char *)sqlite3_value_text(pVal);
  127758. int nVal = sqlite3_value_bytes(pVal);
  127759. if( !zVal ){
  127760. return SQLITE_NOMEM;
  127761. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  127762. rc = fts3DoOptimize(p, 0);
  127763. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  127764. rc = fts3DoRebuild(p);
  127765. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  127766. rc = fts3DoIntegrityCheck(p);
  127767. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  127768. rc = fts3DoIncrmerge(p, &zVal[6]);
  127769. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  127770. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  127771. #ifdef SQLITE_TEST
  127772. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  127773. p->nNodeSize = atoi(&zVal[9]);
  127774. rc = SQLITE_OK;
  127775. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  127776. p->nMaxPendingData = atoi(&zVal[11]);
  127777. rc = SQLITE_OK;
  127778. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  127779. p->bNoIncrDoclist = atoi(&zVal[21]);
  127780. rc = SQLITE_OK;
  127781. #endif
  127782. }else{
  127783. rc = SQLITE_ERROR;
  127784. }
  127785. return rc;
  127786. }
  127787. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  127788. /*
  127789. ** Delete all cached deferred doclists. Deferred doclists are cached
  127790. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  127791. */
  127792. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  127793. Fts3DeferredToken *pDef;
  127794. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  127795. fts3PendingListDelete(pDef->pList);
  127796. pDef->pList = 0;
  127797. }
  127798. }
  127799. /*
  127800. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  127801. ** this list using sqlite3Fts3DeferToken().
  127802. */
  127803. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  127804. Fts3DeferredToken *pDef;
  127805. Fts3DeferredToken *pNext;
  127806. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  127807. pNext = pDef->pNext;
  127808. fts3PendingListDelete(pDef->pList);
  127809. sqlite3_free(pDef);
  127810. }
  127811. pCsr->pDeferred = 0;
  127812. }
  127813. /*
  127814. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  127815. ** based on the row that pCsr currently points to.
  127816. **
  127817. ** A deferred-doclist is like any other doclist with position information
  127818. ** included, except that it only contains entries for a single row of the
  127819. ** table, not for all rows.
  127820. */
  127821. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  127822. int rc = SQLITE_OK; /* Return code */
  127823. if( pCsr->pDeferred ){
  127824. int i; /* Used to iterate through table columns */
  127825. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  127826. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  127827. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  127828. sqlite3_tokenizer *pT = p->pTokenizer;
  127829. sqlite3_tokenizer_module const *pModule = pT->pModule;
  127830. assert( pCsr->isRequireSeek==0 );
  127831. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  127832. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  127833. if( p->abNotindexed[i]==0 ){
  127834. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  127835. sqlite3_tokenizer_cursor *pTC = 0;
  127836. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  127837. while( rc==SQLITE_OK ){
  127838. char const *zToken; /* Buffer containing token */
  127839. int nToken = 0; /* Number of bytes in token */
  127840. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  127841. int iPos = 0; /* Position of token in zText */
  127842. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  127843. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  127844. Fts3PhraseToken *pPT = pDef->pToken;
  127845. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  127846. && (pPT->bFirst==0 || iPos==0)
  127847. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  127848. && (0==memcmp(zToken, pPT->z, pPT->n))
  127849. ){
  127850. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  127851. }
  127852. }
  127853. }
  127854. if( pTC ) pModule->xClose(pTC);
  127855. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  127856. }
  127857. }
  127858. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  127859. if( pDef->pList ){
  127860. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  127861. }
  127862. }
  127863. }
  127864. return rc;
  127865. }
  127866. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  127867. Fts3DeferredToken *p,
  127868. char **ppData,
  127869. int *pnData
  127870. ){
  127871. char *pRet;
  127872. int nSkip;
  127873. sqlite3_int64 dummy;
  127874. *ppData = 0;
  127875. *pnData = 0;
  127876. if( p->pList==0 ){
  127877. return SQLITE_OK;
  127878. }
  127879. pRet = (char *)sqlite3_malloc(p->pList->nData);
  127880. if( !pRet ) return SQLITE_NOMEM;
  127881. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  127882. *pnData = p->pList->nData - nSkip;
  127883. *ppData = pRet;
  127884. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  127885. return SQLITE_OK;
  127886. }
  127887. /*
  127888. ** Add an entry for token pToken to the pCsr->pDeferred list.
  127889. */
  127890. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  127891. Fts3Cursor *pCsr, /* Fts3 table cursor */
  127892. Fts3PhraseToken *pToken, /* Token to defer */
  127893. int iCol /* Column that token must appear in (or -1) */
  127894. ){
  127895. Fts3DeferredToken *pDeferred;
  127896. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  127897. if( !pDeferred ){
  127898. return SQLITE_NOMEM;
  127899. }
  127900. memset(pDeferred, 0, sizeof(*pDeferred));
  127901. pDeferred->pToken = pToken;
  127902. pDeferred->pNext = pCsr->pDeferred;
  127903. pDeferred->iCol = iCol;
  127904. pCsr->pDeferred = pDeferred;
  127905. assert( pToken->pDeferred==0 );
  127906. pToken->pDeferred = pDeferred;
  127907. return SQLITE_OK;
  127908. }
  127909. #endif
  127910. /*
  127911. ** SQLite value pRowid contains the rowid of a row that may or may not be
  127912. ** present in the FTS3 table. If it is, delete it and adjust the contents
  127913. ** of subsiduary data structures accordingly.
  127914. */
  127915. static int fts3DeleteByRowid(
  127916. Fts3Table *p,
  127917. sqlite3_value *pRowid,
  127918. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  127919. u32 *aSzDel
  127920. ){
  127921. int rc = SQLITE_OK; /* Return code */
  127922. int bFound = 0; /* True if *pRowid really is in the table */
  127923. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  127924. if( bFound && rc==SQLITE_OK ){
  127925. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  127926. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  127927. if( rc==SQLITE_OK ){
  127928. if( isEmpty ){
  127929. /* Deleting this row means the whole table is empty. In this case
  127930. ** delete the contents of all three tables and throw away any
  127931. ** data in the pendingTerms hash table. */
  127932. rc = fts3DeleteAll(p, 1);
  127933. *pnChng = 0;
  127934. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  127935. }else{
  127936. *pnChng = *pnChng - 1;
  127937. if( p->zContentTbl==0 ){
  127938. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  127939. }
  127940. if( p->bHasDocsize ){
  127941. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  127942. }
  127943. }
  127944. }
  127945. }
  127946. return rc;
  127947. }
  127948. /*
  127949. ** This function does the work for the xUpdate method of FTS3 virtual
  127950. ** tables. The schema of the virtual table being:
  127951. **
  127952. ** CREATE TABLE <table name>(
  127953. ** <user columns>,
  127954. ** <table name> HIDDEN,
  127955. ** docid HIDDEN,
  127956. ** <langid> HIDDEN
  127957. ** );
  127958. **
  127959. **
  127960. */
  127961. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  127962. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  127963. int nArg, /* Size of argument array */
  127964. sqlite3_value **apVal, /* Array of arguments */
  127965. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  127966. ){
  127967. Fts3Table *p = (Fts3Table *)pVtab;
  127968. int rc = SQLITE_OK; /* Return Code */
  127969. int isRemove = 0; /* True for an UPDATE or DELETE */
  127970. u32 *aSzIns = 0; /* Sizes of inserted documents */
  127971. u32 *aSzDel = 0; /* Sizes of deleted documents */
  127972. int nChng = 0; /* Net change in number of documents */
  127973. int bInsertDone = 0;
  127974. assert( p->pSegments==0 );
  127975. assert(
  127976. nArg==1 /* DELETE operations */
  127977. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  127978. );
  127979. /* Check for a "special" INSERT operation. One of the form:
  127980. **
  127981. ** INSERT INTO xyz(xyz) VALUES('command');
  127982. */
  127983. if( nArg>1
  127984. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  127985. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  127986. ){
  127987. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  127988. goto update_out;
  127989. }
  127990. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  127991. rc = SQLITE_CONSTRAINT;
  127992. goto update_out;
  127993. }
  127994. /* Allocate space to hold the change in document sizes */
  127995. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  127996. if( aSzDel==0 ){
  127997. rc = SQLITE_NOMEM;
  127998. goto update_out;
  127999. }
  128000. aSzIns = &aSzDel[p->nColumn+1];
  128001. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  128002. rc = fts3Writelock(p);
  128003. if( rc!=SQLITE_OK ) goto update_out;
  128004. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  128005. ** value, then this operation requires constraint handling.
  128006. **
  128007. ** If the on-conflict mode is REPLACE, this means that the existing row
  128008. ** should be deleted from the database before inserting the new row. Or,
  128009. ** if the on-conflict mode is other than REPLACE, then this method must
  128010. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  128011. ** modify the database file.
  128012. */
  128013. if( nArg>1 && p->zContentTbl==0 ){
  128014. /* Find the value object that holds the new rowid value. */
  128015. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  128016. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  128017. pNewRowid = apVal[1];
  128018. }
  128019. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  128020. sqlite3_value_type(apVal[0])==SQLITE_NULL
  128021. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  128022. )){
  128023. /* The new rowid is not NULL (in this case the rowid will be
  128024. ** automatically assigned and there is no chance of a conflict), and
  128025. ** the statement is either an INSERT or an UPDATE that modifies the
  128026. ** rowid column. So if the conflict mode is REPLACE, then delete any
  128027. ** existing row with rowid=pNewRowid.
  128028. **
  128029. ** Or, if the conflict mode is not REPLACE, insert the new record into
  128030. ** the %_content table. If we hit the duplicate rowid constraint (or any
  128031. ** other error) while doing so, return immediately.
  128032. **
  128033. ** This branch may also run if pNewRowid contains a value that cannot
  128034. ** be losslessly converted to an integer. In this case, the eventual
  128035. ** call to fts3InsertData() (either just below or further on in this
  128036. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  128037. ** invoked, it will delete zero rows (since no row will have
  128038. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  128039. */
  128040. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  128041. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  128042. }else{
  128043. rc = fts3InsertData(p, apVal, pRowid);
  128044. bInsertDone = 1;
  128045. }
  128046. }
  128047. }
  128048. if( rc!=SQLITE_OK ){
  128049. goto update_out;
  128050. }
  128051. /* If this is a DELETE or UPDATE operation, remove the old record. */
  128052. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  128053. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  128054. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  128055. isRemove = 1;
  128056. }
  128057. /* If this is an INSERT or UPDATE operation, insert the new record. */
  128058. if( nArg>1 && rc==SQLITE_OK ){
  128059. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  128060. if( bInsertDone==0 ){
  128061. rc = fts3InsertData(p, apVal, pRowid);
  128062. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  128063. rc = FTS_CORRUPT_VTAB;
  128064. }
  128065. }
  128066. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  128067. rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
  128068. }
  128069. if( rc==SQLITE_OK ){
  128070. assert( p->iPrevDocid==*pRowid );
  128071. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  128072. }
  128073. if( p->bHasDocsize ){
  128074. fts3InsertDocsize(&rc, p, aSzIns);
  128075. }
  128076. nChng++;
  128077. }
  128078. if( p->bFts4 ){
  128079. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  128080. }
  128081. update_out:
  128082. sqlite3_free(aSzDel);
  128083. sqlite3Fts3SegmentsClose(p);
  128084. return rc;
  128085. }
  128086. /*
  128087. ** Flush any data in the pending-terms hash table to disk. If successful,
  128088. ** merge all segments in the database (including the new segment, if
  128089. ** there was any data to flush) into a single segment.
  128090. */
  128091. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  128092. int rc;
  128093. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  128094. if( rc==SQLITE_OK ){
  128095. rc = fts3DoOptimize(p, 1);
  128096. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  128097. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  128098. if( rc2!=SQLITE_OK ) rc = rc2;
  128099. }else{
  128100. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  128101. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  128102. }
  128103. }
  128104. sqlite3Fts3SegmentsClose(p);
  128105. return rc;
  128106. }
  128107. #endif
  128108. /************** End of fts3_write.c ******************************************/
  128109. /************** Begin file fts3_snippet.c ************************************/
  128110. /*
  128111. ** 2009 Oct 23
  128112. **
  128113. ** The author disclaims copyright to this source code. In place of
  128114. ** a legal notice, here is a blessing:
  128115. **
  128116. ** May you do good and not evil.
  128117. ** May you find forgiveness for yourself and forgive others.
  128118. ** May you share freely, never taking more than you give.
  128119. **
  128120. ******************************************************************************
  128121. */
  128122. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  128123. /* #include <string.h> */
  128124. /* #include <assert.h> */
  128125. /*
  128126. ** Characters that may appear in the second argument to matchinfo().
  128127. */
  128128. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  128129. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  128130. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  128131. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  128132. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  128133. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  128134. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  128135. /*
  128136. ** The default value for the second argument to matchinfo().
  128137. */
  128138. #define FTS3_MATCHINFO_DEFAULT "pcx"
  128139. /*
  128140. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  128141. ** Fts3Expr.aDoclist[]/nDoclist.
  128142. */
  128143. typedef struct LoadDoclistCtx LoadDoclistCtx;
  128144. struct LoadDoclistCtx {
  128145. Fts3Cursor *pCsr; /* FTS3 Cursor */
  128146. int nPhrase; /* Number of phrases seen so far */
  128147. int nToken; /* Number of tokens seen so far */
  128148. };
  128149. /*
  128150. ** The following types are used as part of the implementation of the
  128151. ** fts3BestSnippet() routine.
  128152. */
  128153. typedef struct SnippetIter SnippetIter;
  128154. typedef struct SnippetPhrase SnippetPhrase;
  128155. typedef struct SnippetFragment SnippetFragment;
  128156. struct SnippetIter {
  128157. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  128158. int iCol; /* Extract snippet from this column */
  128159. int nSnippet; /* Requested snippet length (in tokens) */
  128160. int nPhrase; /* Number of phrases in query */
  128161. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  128162. int iCurrent; /* First token of current snippet */
  128163. };
  128164. struct SnippetPhrase {
  128165. int nToken; /* Number of tokens in phrase */
  128166. char *pList; /* Pointer to start of phrase position list */
  128167. int iHead; /* Next value in position list */
  128168. char *pHead; /* Position list data following iHead */
  128169. int iTail; /* Next value in trailing position list */
  128170. char *pTail; /* Position list data following iTail */
  128171. };
  128172. struct SnippetFragment {
  128173. int iCol; /* Column snippet is extracted from */
  128174. int iPos; /* Index of first token in snippet */
  128175. u64 covered; /* Mask of query phrases covered */
  128176. u64 hlmask; /* Mask of snippet terms to highlight */
  128177. };
  128178. /*
  128179. ** This type is used as an fts3ExprIterate() context object while
  128180. ** accumulating the data returned by the matchinfo() function.
  128181. */
  128182. typedef struct MatchInfo MatchInfo;
  128183. struct MatchInfo {
  128184. Fts3Cursor *pCursor; /* FTS3 Cursor */
  128185. int nCol; /* Number of columns in table */
  128186. int nPhrase; /* Number of matchable phrases in query */
  128187. sqlite3_int64 nDoc; /* Number of docs in database */
  128188. u32 *aMatchinfo; /* Pre-allocated buffer */
  128189. };
  128190. /*
  128191. ** The snippet() and offsets() functions both return text values. An instance
  128192. ** of the following structure is used to accumulate those values while the
  128193. ** functions are running. See fts3StringAppend() for details.
  128194. */
  128195. typedef struct StrBuffer StrBuffer;
  128196. struct StrBuffer {
  128197. char *z; /* Pointer to buffer containing string */
  128198. int n; /* Length of z in bytes (excl. nul-term) */
  128199. int nAlloc; /* Allocated size of buffer z in bytes */
  128200. };
  128201. /*
  128202. ** This function is used to help iterate through a position-list. A position
  128203. ** list is a list of unique integers, sorted from smallest to largest. Each
  128204. ** element of the list is represented by an FTS3 varint that takes the value
  128205. ** of the difference between the current element and the previous one plus
  128206. ** two. For example, to store the position-list:
  128207. **
  128208. ** 4 9 113
  128209. **
  128210. ** the three varints:
  128211. **
  128212. ** 6 7 106
  128213. **
  128214. ** are encoded.
  128215. **
  128216. ** When this function is called, *pp points to the start of an element of
  128217. ** the list. *piPos contains the value of the previous entry in the list.
  128218. ** After it returns, *piPos contains the value of the next element of the
  128219. ** list and *pp is advanced to the following varint.
  128220. */
  128221. static void fts3GetDeltaPosition(char **pp, int *piPos){
  128222. int iVal;
  128223. *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
  128224. *piPos += (iVal-2);
  128225. }
  128226. /*
  128227. ** Helper function for fts3ExprIterate() (see below).
  128228. */
  128229. static int fts3ExprIterate2(
  128230. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  128231. int *piPhrase, /* Pointer to phrase counter */
  128232. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  128233. void *pCtx /* Second argument to pass to callback */
  128234. ){
  128235. int rc; /* Return code */
  128236. int eType = pExpr->eType; /* Type of expression node pExpr */
  128237. if( eType!=FTSQUERY_PHRASE ){
  128238. assert( pExpr->pLeft && pExpr->pRight );
  128239. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  128240. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  128241. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  128242. }
  128243. }else{
  128244. rc = x(pExpr, *piPhrase, pCtx);
  128245. (*piPhrase)++;
  128246. }
  128247. return rc;
  128248. }
  128249. /*
  128250. ** Iterate through all phrase nodes in an FTS3 query, except those that
  128251. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  128252. ** For each phrase node found, the supplied callback function is invoked.
  128253. **
  128254. ** If the callback function returns anything other than SQLITE_OK,
  128255. ** the iteration is abandoned and the error code returned immediately.
  128256. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  128257. ** all eligible phrase nodes.
  128258. */
  128259. static int fts3ExprIterate(
  128260. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  128261. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  128262. void *pCtx /* Second argument to pass to callback */
  128263. ){
  128264. int iPhrase = 0; /* Variable used as the phrase counter */
  128265. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  128266. }
  128267. /*
  128268. ** This is an fts3ExprIterate() callback used while loading the doclists
  128269. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  128270. ** fts3ExprLoadDoclists().
  128271. */
  128272. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  128273. int rc = SQLITE_OK;
  128274. Fts3Phrase *pPhrase = pExpr->pPhrase;
  128275. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  128276. UNUSED_PARAMETER(iPhrase);
  128277. p->nPhrase++;
  128278. p->nToken += pPhrase->nToken;
  128279. return rc;
  128280. }
  128281. /*
  128282. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  128283. ** pCsr.
  128284. **
  128285. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  128286. ** phrases in the expression (all phrases except those directly or
  128287. ** indirectly descended from the right-hand-side of a NOT operator). If
  128288. ** pnToken is not NULL, then it is set to the number of tokens in all
  128289. ** matchable phrases of the expression.
  128290. */
  128291. static int fts3ExprLoadDoclists(
  128292. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  128293. int *pnPhrase, /* OUT: Number of phrases in query */
  128294. int *pnToken /* OUT: Number of tokens in query */
  128295. ){
  128296. int rc; /* Return Code */
  128297. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  128298. sCtx.pCsr = pCsr;
  128299. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  128300. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  128301. if( pnToken ) *pnToken = sCtx.nToken;
  128302. return rc;
  128303. }
  128304. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  128305. (*(int *)ctx)++;
  128306. UNUSED_PARAMETER(pExpr);
  128307. UNUSED_PARAMETER(iPhrase);
  128308. return SQLITE_OK;
  128309. }
  128310. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  128311. int nPhrase = 0;
  128312. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  128313. return nPhrase;
  128314. }
  128315. /*
  128316. ** Advance the position list iterator specified by the first two
  128317. ** arguments so that it points to the first element with a value greater
  128318. ** than or equal to parameter iNext.
  128319. */
  128320. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  128321. char *pIter = *ppIter;
  128322. if( pIter ){
  128323. int iIter = *piIter;
  128324. while( iIter<iNext ){
  128325. if( 0==(*pIter & 0xFE) ){
  128326. iIter = -1;
  128327. pIter = 0;
  128328. break;
  128329. }
  128330. fts3GetDeltaPosition(&pIter, &iIter);
  128331. }
  128332. *piIter = iIter;
  128333. *ppIter = pIter;
  128334. }
  128335. }
  128336. /*
  128337. ** Advance the snippet iterator to the next candidate snippet.
  128338. */
  128339. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  128340. int i; /* Loop counter */
  128341. if( pIter->iCurrent<0 ){
  128342. /* The SnippetIter object has just been initialized. The first snippet
  128343. ** candidate always starts at offset 0 (even if this candidate has a
  128344. ** score of 0.0).
  128345. */
  128346. pIter->iCurrent = 0;
  128347. /* Advance the 'head' iterator of each phrase to the first offset that
  128348. ** is greater than or equal to (iNext+nSnippet).
  128349. */
  128350. for(i=0; i<pIter->nPhrase; i++){
  128351. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  128352. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  128353. }
  128354. }else{
  128355. int iStart;
  128356. int iEnd = 0x7FFFFFFF;
  128357. for(i=0; i<pIter->nPhrase; i++){
  128358. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  128359. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  128360. iEnd = pPhrase->iHead;
  128361. }
  128362. }
  128363. if( iEnd==0x7FFFFFFF ){
  128364. return 1;
  128365. }
  128366. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  128367. for(i=0; i<pIter->nPhrase; i++){
  128368. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  128369. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  128370. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  128371. }
  128372. }
  128373. return 0;
  128374. }
  128375. /*
  128376. ** Retrieve information about the current candidate snippet of snippet
  128377. ** iterator pIter.
  128378. */
  128379. static void fts3SnippetDetails(
  128380. SnippetIter *pIter, /* Snippet iterator */
  128381. u64 mCovered, /* Bitmask of phrases already covered */
  128382. int *piToken, /* OUT: First token of proposed snippet */
  128383. int *piScore, /* OUT: "Score" for this snippet */
  128384. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  128385. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  128386. ){
  128387. int iStart = pIter->iCurrent; /* First token of snippet */
  128388. int iScore = 0; /* Score of this snippet */
  128389. int i; /* Loop counter */
  128390. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  128391. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  128392. for(i=0; i<pIter->nPhrase; i++){
  128393. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  128394. if( pPhrase->pTail ){
  128395. char *pCsr = pPhrase->pTail;
  128396. int iCsr = pPhrase->iTail;
  128397. while( iCsr<(iStart+pIter->nSnippet) ){
  128398. int j;
  128399. u64 mPhrase = (u64)1 << i;
  128400. u64 mPos = (u64)1 << (iCsr - iStart);
  128401. assert( iCsr>=iStart );
  128402. if( (mCover|mCovered)&mPhrase ){
  128403. iScore++;
  128404. }else{
  128405. iScore += 1000;
  128406. }
  128407. mCover |= mPhrase;
  128408. for(j=0; j<pPhrase->nToken; j++){
  128409. mHighlight |= (mPos>>j);
  128410. }
  128411. if( 0==(*pCsr & 0x0FE) ) break;
  128412. fts3GetDeltaPosition(&pCsr, &iCsr);
  128413. }
  128414. }
  128415. }
  128416. /* Set the output variables before returning. */
  128417. *piToken = iStart;
  128418. *piScore = iScore;
  128419. *pmCover = mCover;
  128420. *pmHighlight = mHighlight;
  128421. }
  128422. /*
  128423. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  128424. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  128425. */
  128426. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  128427. SnippetIter *p = (SnippetIter *)ctx;
  128428. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  128429. char *pCsr;
  128430. int rc;
  128431. pPhrase->nToken = pExpr->pPhrase->nToken;
  128432. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  128433. assert( rc==SQLITE_OK || pCsr==0 );
  128434. if( pCsr ){
  128435. int iFirst = 0;
  128436. pPhrase->pList = pCsr;
  128437. fts3GetDeltaPosition(&pCsr, &iFirst);
  128438. assert( iFirst>=0 );
  128439. pPhrase->pHead = pCsr;
  128440. pPhrase->pTail = pCsr;
  128441. pPhrase->iHead = iFirst;
  128442. pPhrase->iTail = iFirst;
  128443. }else{
  128444. assert( rc!=SQLITE_OK || (
  128445. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  128446. ));
  128447. }
  128448. return rc;
  128449. }
  128450. /*
  128451. ** Select the fragment of text consisting of nFragment contiguous tokens
  128452. ** from column iCol that represent the "best" snippet. The best snippet
  128453. ** is the snippet with the highest score, where scores are calculated
  128454. ** by adding:
  128455. **
  128456. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  128457. **
  128458. ** (b) +1000 points for the first occurrence of each matchable phrase in
  128459. ** the snippet for which the corresponding mCovered bit is not set.
  128460. **
  128461. ** The selected snippet parameters are stored in structure *pFragment before
  128462. ** returning. The score of the selected snippet is stored in *piScore
  128463. ** before returning.
  128464. */
  128465. static int fts3BestSnippet(
  128466. int nSnippet, /* Desired snippet length */
  128467. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  128468. int iCol, /* Index of column to create snippet from */
  128469. u64 mCovered, /* Mask of phrases already covered */
  128470. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  128471. SnippetFragment *pFragment, /* OUT: Best snippet found */
  128472. int *piScore /* OUT: Score of snippet pFragment */
  128473. ){
  128474. int rc; /* Return Code */
  128475. int nList; /* Number of phrases in expression */
  128476. SnippetIter sIter; /* Iterates through snippet candidates */
  128477. int nByte; /* Number of bytes of space to allocate */
  128478. int iBestScore = -1; /* Best snippet score found so far */
  128479. int i; /* Loop counter */
  128480. memset(&sIter, 0, sizeof(sIter));
  128481. /* Iterate through the phrases in the expression to count them. The same
  128482. ** callback makes sure the doclists are loaded for each phrase.
  128483. */
  128484. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  128485. if( rc!=SQLITE_OK ){
  128486. return rc;
  128487. }
  128488. /* Now that it is known how many phrases there are, allocate and zero
  128489. ** the required space using malloc().
  128490. */
  128491. nByte = sizeof(SnippetPhrase) * nList;
  128492. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  128493. if( !sIter.aPhrase ){
  128494. return SQLITE_NOMEM;
  128495. }
  128496. memset(sIter.aPhrase, 0, nByte);
  128497. /* Initialize the contents of the SnippetIter object. Then iterate through
  128498. ** the set of phrases in the expression to populate the aPhrase[] array.
  128499. */
  128500. sIter.pCsr = pCsr;
  128501. sIter.iCol = iCol;
  128502. sIter.nSnippet = nSnippet;
  128503. sIter.nPhrase = nList;
  128504. sIter.iCurrent = -1;
  128505. (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
  128506. /* Set the *pmSeen output variable. */
  128507. for(i=0; i<nList; i++){
  128508. if( sIter.aPhrase[i].pHead ){
  128509. *pmSeen |= (u64)1 << i;
  128510. }
  128511. }
  128512. /* Loop through all candidate snippets. Store the best snippet in
  128513. ** *pFragment. Store its associated 'score' in iBestScore.
  128514. */
  128515. pFragment->iCol = iCol;
  128516. while( !fts3SnippetNextCandidate(&sIter) ){
  128517. int iPos;
  128518. int iScore;
  128519. u64 mCover;
  128520. u64 mHighlight;
  128521. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
  128522. assert( iScore>=0 );
  128523. if( iScore>iBestScore ){
  128524. pFragment->iPos = iPos;
  128525. pFragment->hlmask = mHighlight;
  128526. pFragment->covered = mCover;
  128527. iBestScore = iScore;
  128528. }
  128529. }
  128530. sqlite3_free(sIter.aPhrase);
  128531. *piScore = iBestScore;
  128532. return SQLITE_OK;
  128533. }
  128534. /*
  128535. ** Append a string to the string-buffer passed as the first argument.
  128536. **
  128537. ** If nAppend is negative, then the length of the string zAppend is
  128538. ** determined using strlen().
  128539. */
  128540. static int fts3StringAppend(
  128541. StrBuffer *pStr, /* Buffer to append to */
  128542. const char *zAppend, /* Pointer to data to append to buffer */
  128543. int nAppend /* Size of zAppend in bytes (or -1) */
  128544. ){
  128545. if( nAppend<0 ){
  128546. nAppend = (int)strlen(zAppend);
  128547. }
  128548. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  128549. ** to grow the buffer until so that it is big enough to accomadate the
  128550. ** appended data.
  128551. */
  128552. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  128553. int nAlloc = pStr->nAlloc+nAppend+100;
  128554. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  128555. if( !zNew ){
  128556. return SQLITE_NOMEM;
  128557. }
  128558. pStr->z = zNew;
  128559. pStr->nAlloc = nAlloc;
  128560. }
  128561. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  128562. /* Append the data to the string buffer. */
  128563. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  128564. pStr->n += nAppend;
  128565. pStr->z[pStr->n] = '\0';
  128566. return SQLITE_OK;
  128567. }
  128568. /*
  128569. ** The fts3BestSnippet() function often selects snippets that end with a
  128570. ** query term. That is, the final term of the snippet is always a term
  128571. ** that requires highlighting. For example, if 'X' is a highlighted term
  128572. ** and '.' is a non-highlighted term, BestSnippet() may select:
  128573. **
  128574. ** ........X.....X
  128575. **
  128576. ** This function "shifts" the beginning of the snippet forward in the
  128577. ** document so that there are approximately the same number of
  128578. ** non-highlighted terms to the right of the final highlighted term as there
  128579. ** are to the left of the first highlighted term. For example, to this:
  128580. **
  128581. ** ....X.....X....
  128582. **
  128583. ** This is done as part of extracting the snippet text, not when selecting
  128584. ** the snippet. Snippet selection is done based on doclists only, so there
  128585. ** is no way for fts3BestSnippet() to know whether or not the document
  128586. ** actually contains terms that follow the final highlighted term.
  128587. */
  128588. static int fts3SnippetShift(
  128589. Fts3Table *pTab, /* FTS3 table snippet comes from */
  128590. int iLangid, /* Language id to use in tokenizing */
  128591. int nSnippet, /* Number of tokens desired for snippet */
  128592. const char *zDoc, /* Document text to extract snippet from */
  128593. int nDoc, /* Size of buffer zDoc in bytes */
  128594. int *piPos, /* IN/OUT: First token of snippet */
  128595. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  128596. ){
  128597. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  128598. if( hlmask ){
  128599. int nLeft; /* Tokens to the left of first highlight */
  128600. int nRight; /* Tokens to the right of last highlight */
  128601. int nDesired; /* Ideal number of tokens to shift forward */
  128602. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  128603. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  128604. nDesired = (nLeft-nRight)/2;
  128605. /* Ideally, the start of the snippet should be pushed forward in the
  128606. ** document nDesired tokens. This block checks if there are actually
  128607. ** nDesired tokens to the right of the snippet. If so, *piPos and
  128608. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  128609. ** right. Otherwise, the snippet is shifted by the number of tokens
  128610. ** available.
  128611. */
  128612. if( nDesired>0 ){
  128613. int nShift; /* Number of tokens to shift snippet by */
  128614. int iCurrent = 0; /* Token counter */
  128615. int rc; /* Return Code */
  128616. sqlite3_tokenizer_module *pMod;
  128617. sqlite3_tokenizer_cursor *pC;
  128618. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  128619. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  128620. ** or more tokens in zDoc/nDoc.
  128621. */
  128622. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  128623. if( rc!=SQLITE_OK ){
  128624. return rc;
  128625. }
  128626. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  128627. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  128628. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  128629. }
  128630. pMod->xClose(pC);
  128631. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  128632. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  128633. assert( nShift<=nDesired );
  128634. if( nShift>0 ){
  128635. *piPos += nShift;
  128636. *pHlmask = hlmask >> nShift;
  128637. }
  128638. }
  128639. }
  128640. return SQLITE_OK;
  128641. }
  128642. /*
  128643. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  128644. ** append it to string buffer pOut.
  128645. */
  128646. static int fts3SnippetText(
  128647. Fts3Cursor *pCsr, /* FTS3 Cursor */
  128648. SnippetFragment *pFragment, /* Snippet to extract */
  128649. int iFragment, /* Fragment number */
  128650. int isLast, /* True for final fragment in snippet */
  128651. int nSnippet, /* Number of tokens in extracted snippet */
  128652. const char *zOpen, /* String inserted before highlighted term */
  128653. const char *zClose, /* String inserted after highlighted term */
  128654. const char *zEllipsis, /* String inserted between snippets */
  128655. StrBuffer *pOut /* Write output here */
  128656. ){
  128657. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  128658. int rc; /* Return code */
  128659. const char *zDoc; /* Document text to extract snippet from */
  128660. int nDoc; /* Size of zDoc in bytes */
  128661. int iCurrent = 0; /* Current token number of document */
  128662. int iEnd = 0; /* Byte offset of end of current token */
  128663. int isShiftDone = 0; /* True after snippet is shifted */
  128664. int iPos = pFragment->iPos; /* First token of snippet */
  128665. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  128666. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  128667. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  128668. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  128669. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  128670. if( zDoc==0 ){
  128671. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  128672. return SQLITE_NOMEM;
  128673. }
  128674. return SQLITE_OK;
  128675. }
  128676. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  128677. /* Open a token cursor on the document. */
  128678. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  128679. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  128680. if( rc!=SQLITE_OK ){
  128681. return rc;
  128682. }
  128683. while( rc==SQLITE_OK ){
  128684. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  128685. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  128686. int iBegin = 0; /* Offset in zDoc of start of token */
  128687. int iFin = 0; /* Offset in zDoc of end of token */
  128688. int isHighlight = 0; /* True for highlighted terms */
  128689. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  128690. ** in the FTS code the variable that the third argument to xNext points to
  128691. ** is initialized to zero before the first (*but not necessarily
  128692. ** subsequent*) call to xNext(). This is done for a particular application
  128693. ** that needs to know whether or not the tokenizer is being used for
  128694. ** snippet generation or for some other purpose.
  128695. **
  128696. ** Extreme care is required when writing code to depend on this
  128697. ** initialization. It is not a documented part of the tokenizer interface.
  128698. ** If a tokenizer is used directly by any code outside of FTS, this
  128699. ** convention might not be respected. */
  128700. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  128701. if( rc!=SQLITE_OK ){
  128702. if( rc==SQLITE_DONE ){
  128703. /* Special case - the last token of the snippet is also the last token
  128704. ** of the column. Append any punctuation that occurred between the end
  128705. ** of the previous token and the end of the document to the output.
  128706. ** Then break out of the loop. */
  128707. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  128708. }
  128709. break;
  128710. }
  128711. if( iCurrent<iPos ){ continue; }
  128712. if( !isShiftDone ){
  128713. int n = nDoc - iBegin;
  128714. rc = fts3SnippetShift(
  128715. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  128716. );
  128717. isShiftDone = 1;
  128718. /* Now that the shift has been done, check if the initial "..." are
  128719. ** required. They are required if (a) this is not the first fragment,
  128720. ** or (b) this fragment does not begin at position 0 of its column.
  128721. */
  128722. if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
  128723. rc = fts3StringAppend(pOut, zEllipsis, -1);
  128724. }
  128725. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  128726. }
  128727. if( iCurrent>=(iPos+nSnippet) ){
  128728. if( isLast ){
  128729. rc = fts3StringAppend(pOut, zEllipsis, -1);
  128730. }
  128731. break;
  128732. }
  128733. /* Set isHighlight to true if this term should be highlighted. */
  128734. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  128735. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  128736. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  128737. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  128738. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  128739. iEnd = iFin;
  128740. }
  128741. pMod->xClose(pC);
  128742. return rc;
  128743. }
  128744. /*
  128745. ** This function is used to count the entries in a column-list (a
  128746. ** delta-encoded list of term offsets within a single column of a single
  128747. ** row). When this function is called, *ppCollist should point to the
  128748. ** beginning of the first varint in the column-list (the varint that
  128749. ** contains the position of the first matching term in the column data).
  128750. ** Before returning, *ppCollist is set to point to the first byte after
  128751. ** the last varint in the column-list (either the 0x00 signifying the end
  128752. ** of the position-list, or the 0x01 that precedes the column number of
  128753. ** the next column in the position-list).
  128754. **
  128755. ** The number of elements in the column-list is returned.
  128756. */
  128757. static int fts3ColumnlistCount(char **ppCollist){
  128758. char *pEnd = *ppCollist;
  128759. char c = 0;
  128760. int nEntry = 0;
  128761. /* A column-list is terminated by either a 0x01 or 0x00. */
  128762. while( 0xFE & (*pEnd | c) ){
  128763. c = *pEnd++ & 0x80;
  128764. if( !c ) nEntry++;
  128765. }
  128766. *ppCollist = pEnd;
  128767. return nEntry;
  128768. }
  128769. /*
  128770. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  128771. ** for a single query.
  128772. **
  128773. ** fts3ExprIterate() callback to load the 'global' elements of a
  128774. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  128775. ** of the matchinfo array that are constant for all rows returned by the
  128776. ** current query.
  128777. **
  128778. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  128779. ** function populates Matchinfo.aMatchinfo[] as follows:
  128780. **
  128781. ** for(iCol=0; iCol<nCol; iCol++){
  128782. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  128783. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  128784. ** }
  128785. **
  128786. ** where X is the number of matches for phrase iPhrase is column iCol of all
  128787. ** rows of the table. Y is the number of rows for which column iCol contains
  128788. ** at least one instance of phrase iPhrase.
  128789. **
  128790. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  128791. ** Y values are set to nDoc, where nDoc is the number of documents in the
  128792. ** file system. This is done because the full-text index doclist is required
  128793. ** to calculate these values properly, and the full-text index doclist is
  128794. ** not available for deferred tokens.
  128795. */
  128796. static int fts3ExprGlobalHitsCb(
  128797. Fts3Expr *pExpr, /* Phrase expression node */
  128798. int iPhrase, /* Phrase number (numbered from zero) */
  128799. void *pCtx /* Pointer to MatchInfo structure */
  128800. ){
  128801. MatchInfo *p = (MatchInfo *)pCtx;
  128802. return sqlite3Fts3EvalPhraseStats(
  128803. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  128804. );
  128805. }
  128806. /*
  128807. ** fts3ExprIterate() callback used to collect the "local" part of the
  128808. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  128809. ** array that are different for each row returned by the query.
  128810. */
  128811. static int fts3ExprLocalHitsCb(
  128812. Fts3Expr *pExpr, /* Phrase expression node */
  128813. int iPhrase, /* Phrase number */
  128814. void *pCtx /* Pointer to MatchInfo structure */
  128815. ){
  128816. int rc = SQLITE_OK;
  128817. MatchInfo *p = (MatchInfo *)pCtx;
  128818. int iStart = iPhrase * p->nCol * 3;
  128819. int i;
  128820. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  128821. char *pCsr;
  128822. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  128823. if( pCsr ){
  128824. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  128825. }else{
  128826. p->aMatchinfo[iStart+i*3] = 0;
  128827. }
  128828. }
  128829. return rc;
  128830. }
  128831. static int fts3MatchinfoCheck(
  128832. Fts3Table *pTab,
  128833. char cArg,
  128834. char **pzErr
  128835. ){
  128836. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  128837. || (cArg==FTS3_MATCHINFO_NCOL)
  128838. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  128839. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  128840. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  128841. || (cArg==FTS3_MATCHINFO_LCS)
  128842. || (cArg==FTS3_MATCHINFO_HITS)
  128843. ){
  128844. return SQLITE_OK;
  128845. }
  128846. *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
  128847. return SQLITE_ERROR;
  128848. }
  128849. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  128850. int nVal; /* Number of integers output by cArg */
  128851. switch( cArg ){
  128852. case FTS3_MATCHINFO_NDOC:
  128853. case FTS3_MATCHINFO_NPHRASE:
  128854. case FTS3_MATCHINFO_NCOL:
  128855. nVal = 1;
  128856. break;
  128857. case FTS3_MATCHINFO_AVGLENGTH:
  128858. case FTS3_MATCHINFO_LENGTH:
  128859. case FTS3_MATCHINFO_LCS:
  128860. nVal = pInfo->nCol;
  128861. break;
  128862. default:
  128863. assert( cArg==FTS3_MATCHINFO_HITS );
  128864. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  128865. break;
  128866. }
  128867. return nVal;
  128868. }
  128869. static int fts3MatchinfoSelectDoctotal(
  128870. Fts3Table *pTab,
  128871. sqlite3_stmt **ppStmt,
  128872. sqlite3_int64 *pnDoc,
  128873. const char **paLen
  128874. ){
  128875. sqlite3_stmt *pStmt;
  128876. const char *a;
  128877. sqlite3_int64 nDoc;
  128878. if( !*ppStmt ){
  128879. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  128880. if( rc!=SQLITE_OK ) return rc;
  128881. }
  128882. pStmt = *ppStmt;
  128883. assert( sqlite3_data_count(pStmt)==1 );
  128884. a = sqlite3_column_blob(pStmt, 0);
  128885. a += sqlite3Fts3GetVarint(a, &nDoc);
  128886. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  128887. *pnDoc = (u32)nDoc;
  128888. if( paLen ) *paLen = a;
  128889. return SQLITE_OK;
  128890. }
  128891. /*
  128892. ** An instance of the following structure is used to store state while
  128893. ** iterating through a multi-column position-list corresponding to the
  128894. ** hits for a single phrase on a single row in order to calculate the
  128895. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  128896. */
  128897. typedef struct LcsIterator LcsIterator;
  128898. struct LcsIterator {
  128899. Fts3Expr *pExpr; /* Pointer to phrase expression */
  128900. int iPosOffset; /* Tokens count up to end of this phrase */
  128901. char *pRead; /* Cursor used to iterate through aDoclist */
  128902. int iPos; /* Current position */
  128903. };
  128904. /*
  128905. ** If LcsIterator.iCol is set to the following value, the iterator has
  128906. ** finished iterating through all offsets for all columns.
  128907. */
  128908. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  128909. static int fts3MatchinfoLcsCb(
  128910. Fts3Expr *pExpr, /* Phrase expression node */
  128911. int iPhrase, /* Phrase number (numbered from zero) */
  128912. void *pCtx /* Pointer to MatchInfo structure */
  128913. ){
  128914. LcsIterator *aIter = (LcsIterator *)pCtx;
  128915. aIter[iPhrase].pExpr = pExpr;
  128916. return SQLITE_OK;
  128917. }
  128918. /*
  128919. ** Advance the iterator passed as an argument to the next position. Return
  128920. ** 1 if the iterator is at EOF or if it now points to the start of the
  128921. ** position list for the next column.
  128922. */
  128923. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  128924. char *pRead = pIter->pRead;
  128925. sqlite3_int64 iRead;
  128926. int rc = 0;
  128927. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  128928. if( iRead==0 || iRead==1 ){
  128929. pRead = 0;
  128930. rc = 1;
  128931. }else{
  128932. pIter->iPos += (int)(iRead-2);
  128933. }
  128934. pIter->pRead = pRead;
  128935. return rc;
  128936. }
  128937. /*
  128938. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  128939. **
  128940. ** If the call is successful, the longest-common-substring lengths for each
  128941. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  128942. ** array before returning. SQLITE_OK is returned in this case.
  128943. **
  128944. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  128945. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  128946. ** undefined.
  128947. */
  128948. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  128949. LcsIterator *aIter;
  128950. int i;
  128951. int iCol;
  128952. int nToken = 0;
  128953. /* Allocate and populate the array of LcsIterator objects. The array
  128954. ** contains one element for each matchable phrase in the query.
  128955. **/
  128956. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  128957. if( !aIter ) return SQLITE_NOMEM;
  128958. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  128959. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  128960. for(i=0; i<pInfo->nPhrase; i++){
  128961. LcsIterator *pIter = &aIter[i];
  128962. nToken -= pIter->pExpr->pPhrase->nToken;
  128963. pIter->iPosOffset = nToken;
  128964. }
  128965. for(iCol=0; iCol<pInfo->nCol; iCol++){
  128966. int nLcs = 0; /* LCS value for this column */
  128967. int nLive = 0; /* Number of iterators in aIter not at EOF */
  128968. for(i=0; i<pInfo->nPhrase; i++){
  128969. int rc;
  128970. LcsIterator *pIt = &aIter[i];
  128971. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  128972. if( rc!=SQLITE_OK ) return rc;
  128973. if( pIt->pRead ){
  128974. pIt->iPos = pIt->iPosOffset;
  128975. fts3LcsIteratorAdvance(&aIter[i]);
  128976. nLive++;
  128977. }
  128978. }
  128979. while( nLive>0 ){
  128980. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  128981. int nThisLcs = 0; /* LCS for the current iterator positions */
  128982. for(i=0; i<pInfo->nPhrase; i++){
  128983. LcsIterator *pIter = &aIter[i];
  128984. if( pIter->pRead==0 ){
  128985. /* This iterator is already at EOF for this column. */
  128986. nThisLcs = 0;
  128987. }else{
  128988. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  128989. pAdv = pIter;
  128990. }
  128991. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  128992. nThisLcs++;
  128993. }else{
  128994. nThisLcs = 1;
  128995. }
  128996. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  128997. }
  128998. }
  128999. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  129000. }
  129001. pInfo->aMatchinfo[iCol] = nLcs;
  129002. }
  129003. sqlite3_free(aIter);
  129004. return SQLITE_OK;
  129005. }
  129006. /*
  129007. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  129008. ** be returned by the matchinfo() function. Argument zArg contains the
  129009. ** format string passed as the second argument to matchinfo (or the
  129010. ** default value "pcx" if no second argument was specified). The format
  129011. ** string has already been validated and the pInfo->aMatchinfo[] array
  129012. ** is guaranteed to be large enough for the output.
  129013. **
  129014. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  129015. ** If it is false, then assume that those fields that do not change between
  129016. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  129017. ** have already been populated.
  129018. **
  129019. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  129020. ** occurs. If a value other than SQLITE_OK is returned, the state the
  129021. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  129022. */
  129023. static int fts3MatchinfoValues(
  129024. Fts3Cursor *pCsr, /* FTS3 cursor object */
  129025. int bGlobal, /* True to grab the global stats */
  129026. MatchInfo *pInfo, /* Matchinfo context object */
  129027. const char *zArg /* Matchinfo format string */
  129028. ){
  129029. int rc = SQLITE_OK;
  129030. int i;
  129031. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  129032. sqlite3_stmt *pSelect = 0;
  129033. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  129034. switch( zArg[i] ){
  129035. case FTS3_MATCHINFO_NPHRASE:
  129036. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  129037. break;
  129038. case FTS3_MATCHINFO_NCOL:
  129039. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  129040. break;
  129041. case FTS3_MATCHINFO_NDOC:
  129042. if( bGlobal ){
  129043. sqlite3_int64 nDoc = 0;
  129044. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  129045. pInfo->aMatchinfo[0] = (u32)nDoc;
  129046. }
  129047. break;
  129048. case FTS3_MATCHINFO_AVGLENGTH:
  129049. if( bGlobal ){
  129050. sqlite3_int64 nDoc; /* Number of rows in table */
  129051. const char *a; /* Aggregate column length array */
  129052. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  129053. if( rc==SQLITE_OK ){
  129054. int iCol;
  129055. for(iCol=0; iCol<pInfo->nCol; iCol++){
  129056. u32 iVal;
  129057. sqlite3_int64 nToken;
  129058. a += sqlite3Fts3GetVarint(a, &nToken);
  129059. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  129060. pInfo->aMatchinfo[iCol] = iVal;
  129061. }
  129062. }
  129063. }
  129064. break;
  129065. case FTS3_MATCHINFO_LENGTH: {
  129066. sqlite3_stmt *pSelectDocsize = 0;
  129067. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  129068. if( rc==SQLITE_OK ){
  129069. int iCol;
  129070. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  129071. for(iCol=0; iCol<pInfo->nCol; iCol++){
  129072. sqlite3_int64 nToken;
  129073. a += sqlite3Fts3GetVarint(a, &nToken);
  129074. pInfo->aMatchinfo[iCol] = (u32)nToken;
  129075. }
  129076. }
  129077. sqlite3_reset(pSelectDocsize);
  129078. break;
  129079. }
  129080. case FTS3_MATCHINFO_LCS:
  129081. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  129082. if( rc==SQLITE_OK ){
  129083. rc = fts3MatchinfoLcs(pCsr, pInfo);
  129084. }
  129085. break;
  129086. default: {
  129087. Fts3Expr *pExpr;
  129088. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  129089. pExpr = pCsr->pExpr;
  129090. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  129091. if( rc!=SQLITE_OK ) break;
  129092. if( bGlobal ){
  129093. if( pCsr->pDeferred ){
  129094. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  129095. if( rc!=SQLITE_OK ) break;
  129096. }
  129097. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  129098. if( rc!=SQLITE_OK ) break;
  129099. }
  129100. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  129101. break;
  129102. }
  129103. }
  129104. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  129105. }
  129106. sqlite3_reset(pSelect);
  129107. return rc;
  129108. }
  129109. /*
  129110. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  129111. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  129112. */
  129113. static int fts3GetMatchinfo(
  129114. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  129115. const char *zArg /* Second argument to matchinfo() function */
  129116. ){
  129117. MatchInfo sInfo;
  129118. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  129119. int rc = SQLITE_OK;
  129120. int bGlobal = 0; /* Collect 'global' stats as well as local */
  129121. memset(&sInfo, 0, sizeof(MatchInfo));
  129122. sInfo.pCursor = pCsr;
  129123. sInfo.nCol = pTab->nColumn;
  129124. /* If there is cached matchinfo() data, but the format string for the
  129125. ** cache does not match the format string for this request, discard
  129126. ** the cached data. */
  129127. if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
  129128. assert( pCsr->aMatchinfo );
  129129. sqlite3_free(pCsr->aMatchinfo);
  129130. pCsr->zMatchinfo = 0;
  129131. pCsr->aMatchinfo = 0;
  129132. }
  129133. /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
  129134. ** matchinfo function has been called for this query. In this case
  129135. ** allocate the array used to accumulate the matchinfo data and
  129136. ** initialize those elements that are constant for every row.
  129137. */
  129138. if( pCsr->aMatchinfo==0 ){
  129139. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  129140. int nArg; /* Bytes in zArg */
  129141. int i; /* Used to iterate through zArg */
  129142. /* Determine the number of phrases in the query */
  129143. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  129144. sInfo.nPhrase = pCsr->nPhrase;
  129145. /* Determine the number of integers in the buffer returned by this call. */
  129146. for(i=0; zArg[i]; i++){
  129147. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  129148. }
  129149. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  129150. nArg = (int)strlen(zArg);
  129151. pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
  129152. if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
  129153. pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
  129154. pCsr->nMatchinfo = nMatchinfo;
  129155. memcpy(pCsr->zMatchinfo, zArg, nArg+1);
  129156. memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
  129157. pCsr->isMatchinfoNeeded = 1;
  129158. bGlobal = 1;
  129159. }
  129160. sInfo.aMatchinfo = pCsr->aMatchinfo;
  129161. sInfo.nPhrase = pCsr->nPhrase;
  129162. if( pCsr->isMatchinfoNeeded ){
  129163. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  129164. pCsr->isMatchinfoNeeded = 0;
  129165. }
  129166. return rc;
  129167. }
  129168. /*
  129169. ** Implementation of snippet() function.
  129170. */
  129171. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  129172. sqlite3_context *pCtx, /* SQLite function call context */
  129173. Fts3Cursor *pCsr, /* Cursor object */
  129174. const char *zStart, /* Snippet start text - "<b>" */
  129175. const char *zEnd, /* Snippet end text - "</b>" */
  129176. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  129177. int iCol, /* Extract snippet from this column */
  129178. int nToken /* Approximate number of tokens in snippet */
  129179. ){
  129180. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  129181. int rc = SQLITE_OK;
  129182. int i;
  129183. StrBuffer res = {0, 0, 0};
  129184. /* The returned text includes up to four fragments of text extracted from
  129185. ** the data in the current row. The first iteration of the for(...) loop
  129186. ** below attempts to locate a single fragment of text nToken tokens in
  129187. ** size that contains at least one instance of all phrases in the query
  129188. ** expression that appear in the current row. If such a fragment of text
  129189. ** cannot be found, the second iteration of the loop attempts to locate
  129190. ** a pair of fragments, and so on.
  129191. */
  129192. int nSnippet = 0; /* Number of fragments in this snippet */
  129193. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  129194. int nFToken = -1; /* Number of tokens in each fragment */
  129195. if( !pCsr->pExpr ){
  129196. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  129197. return;
  129198. }
  129199. for(nSnippet=1; 1; nSnippet++){
  129200. int iSnip; /* Loop counter 0..nSnippet-1 */
  129201. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  129202. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  129203. if( nToken>=0 ){
  129204. nFToken = (nToken+nSnippet-1) / nSnippet;
  129205. }else{
  129206. nFToken = -1 * nToken;
  129207. }
  129208. for(iSnip=0; iSnip<nSnippet; iSnip++){
  129209. int iBestScore = -1; /* Best score of columns checked so far */
  129210. int iRead; /* Used to iterate through columns */
  129211. SnippetFragment *pFragment = &aSnippet[iSnip];
  129212. memset(pFragment, 0, sizeof(*pFragment));
  129213. /* Loop through all columns of the table being considered for snippets.
  129214. ** If the iCol argument to this function was negative, this means all
  129215. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  129216. */
  129217. for(iRead=0; iRead<pTab->nColumn; iRead++){
  129218. SnippetFragment sF = {0, 0, 0, 0};
  129219. int iS;
  129220. if( iCol>=0 && iRead!=iCol ) continue;
  129221. /* Find the best snippet of nFToken tokens in column iRead. */
  129222. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  129223. if( rc!=SQLITE_OK ){
  129224. goto snippet_out;
  129225. }
  129226. if( iS>iBestScore ){
  129227. *pFragment = sF;
  129228. iBestScore = iS;
  129229. }
  129230. }
  129231. mCovered |= pFragment->covered;
  129232. }
  129233. /* If all query phrases seen by fts3BestSnippet() are present in at least
  129234. ** one of the nSnippet snippet fragments, break out of the loop.
  129235. */
  129236. assert( (mCovered&mSeen)==mCovered );
  129237. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  129238. }
  129239. assert( nFToken>0 );
  129240. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  129241. rc = fts3SnippetText(pCsr, &aSnippet[i],
  129242. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  129243. );
  129244. }
  129245. snippet_out:
  129246. sqlite3Fts3SegmentsClose(pTab);
  129247. if( rc!=SQLITE_OK ){
  129248. sqlite3_result_error_code(pCtx, rc);
  129249. sqlite3_free(res.z);
  129250. }else{
  129251. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  129252. }
  129253. }
  129254. typedef struct TermOffset TermOffset;
  129255. typedef struct TermOffsetCtx TermOffsetCtx;
  129256. struct TermOffset {
  129257. char *pList; /* Position-list */
  129258. int iPos; /* Position just read from pList */
  129259. int iOff; /* Offset of this term from read positions */
  129260. };
  129261. struct TermOffsetCtx {
  129262. Fts3Cursor *pCsr;
  129263. int iCol; /* Column of table to populate aTerm for */
  129264. int iTerm;
  129265. sqlite3_int64 iDocid;
  129266. TermOffset *aTerm;
  129267. };
  129268. /*
  129269. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  129270. */
  129271. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  129272. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  129273. int nTerm; /* Number of tokens in phrase */
  129274. int iTerm; /* For looping through nTerm phrase terms */
  129275. char *pList; /* Pointer to position list for phrase */
  129276. int iPos = 0; /* First position in position-list */
  129277. int rc;
  129278. UNUSED_PARAMETER(iPhrase);
  129279. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  129280. nTerm = pExpr->pPhrase->nToken;
  129281. if( pList ){
  129282. fts3GetDeltaPosition(&pList, &iPos);
  129283. assert( iPos>=0 );
  129284. }
  129285. for(iTerm=0; iTerm<nTerm; iTerm++){
  129286. TermOffset *pT = &p->aTerm[p->iTerm++];
  129287. pT->iOff = nTerm-iTerm-1;
  129288. pT->pList = pList;
  129289. pT->iPos = iPos;
  129290. }
  129291. return rc;
  129292. }
  129293. /*
  129294. ** Implementation of offsets() function.
  129295. */
  129296. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  129297. sqlite3_context *pCtx, /* SQLite function call context */
  129298. Fts3Cursor *pCsr /* Cursor object */
  129299. ){
  129300. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  129301. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  129302. int rc; /* Return Code */
  129303. int nToken; /* Number of tokens in query */
  129304. int iCol; /* Column currently being processed */
  129305. StrBuffer res = {0, 0, 0}; /* Result string */
  129306. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  129307. if( !pCsr->pExpr ){
  129308. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  129309. return;
  129310. }
  129311. memset(&sCtx, 0, sizeof(sCtx));
  129312. assert( pCsr->isRequireSeek==0 );
  129313. /* Count the number of terms in the query */
  129314. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  129315. if( rc!=SQLITE_OK ) goto offsets_out;
  129316. /* Allocate the array of TermOffset iterators. */
  129317. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  129318. if( 0==sCtx.aTerm ){
  129319. rc = SQLITE_NOMEM;
  129320. goto offsets_out;
  129321. }
  129322. sCtx.iDocid = pCsr->iPrevId;
  129323. sCtx.pCsr = pCsr;
  129324. /* Loop through the table columns, appending offset information to
  129325. ** string-buffer res for each column.
  129326. */
  129327. for(iCol=0; iCol<pTab->nColumn; iCol++){
  129328. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  129329. const char *ZDUMMY; /* Dummy argument used with xNext() */
  129330. int NDUMMY = 0; /* Dummy argument used with xNext() */
  129331. int iStart = 0;
  129332. int iEnd = 0;
  129333. int iCurrent = 0;
  129334. const char *zDoc;
  129335. int nDoc;
  129336. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  129337. ** no way that this operation can fail, so the return code from
  129338. ** fts3ExprIterate() can be discarded.
  129339. */
  129340. sCtx.iCol = iCol;
  129341. sCtx.iTerm = 0;
  129342. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
  129343. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  129344. ** in column iCol, jump immediately to the next iteration of the loop.
  129345. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  129346. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  129347. ** to the caller.
  129348. */
  129349. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  129350. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  129351. if( zDoc==0 ){
  129352. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  129353. continue;
  129354. }
  129355. rc = SQLITE_NOMEM;
  129356. goto offsets_out;
  129357. }
  129358. /* Initialize a tokenizer iterator to iterate through column iCol. */
  129359. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  129360. zDoc, nDoc, &pC
  129361. );
  129362. if( rc!=SQLITE_OK ) goto offsets_out;
  129363. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  129364. while( rc==SQLITE_OK ){
  129365. int i; /* Used to loop through terms */
  129366. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  129367. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  129368. for(i=0; i<nToken; i++){
  129369. TermOffset *pT = &sCtx.aTerm[i];
  129370. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  129371. iMinPos = pT->iPos-pT->iOff;
  129372. pTerm = pT;
  129373. }
  129374. }
  129375. if( !pTerm ){
  129376. /* All offsets for this column have been gathered. */
  129377. rc = SQLITE_DONE;
  129378. }else{
  129379. assert( iCurrent<=iMinPos );
  129380. if( 0==(0xFE&*pTerm->pList) ){
  129381. pTerm->pList = 0;
  129382. }else{
  129383. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  129384. }
  129385. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  129386. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  129387. }
  129388. if( rc==SQLITE_OK ){
  129389. char aBuffer[64];
  129390. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  129391. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  129392. );
  129393. rc = fts3StringAppend(&res, aBuffer, -1);
  129394. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  129395. rc = FTS_CORRUPT_VTAB;
  129396. }
  129397. }
  129398. }
  129399. if( rc==SQLITE_DONE ){
  129400. rc = SQLITE_OK;
  129401. }
  129402. pMod->xClose(pC);
  129403. if( rc!=SQLITE_OK ) goto offsets_out;
  129404. }
  129405. offsets_out:
  129406. sqlite3_free(sCtx.aTerm);
  129407. assert( rc!=SQLITE_DONE );
  129408. sqlite3Fts3SegmentsClose(pTab);
  129409. if( rc!=SQLITE_OK ){
  129410. sqlite3_result_error_code(pCtx, rc);
  129411. sqlite3_free(res.z);
  129412. }else{
  129413. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  129414. }
  129415. return;
  129416. }
  129417. /*
  129418. ** Implementation of matchinfo() function.
  129419. */
  129420. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  129421. sqlite3_context *pContext, /* Function call context */
  129422. Fts3Cursor *pCsr, /* FTS3 table cursor */
  129423. const char *zArg /* Second arg to matchinfo() function */
  129424. ){
  129425. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  129426. int rc;
  129427. int i;
  129428. const char *zFormat;
  129429. if( zArg ){
  129430. for(i=0; zArg[i]; i++){
  129431. char *zErr = 0;
  129432. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  129433. sqlite3_result_error(pContext, zErr, -1);
  129434. sqlite3_free(zErr);
  129435. return;
  129436. }
  129437. }
  129438. zFormat = zArg;
  129439. }else{
  129440. zFormat = FTS3_MATCHINFO_DEFAULT;
  129441. }
  129442. if( !pCsr->pExpr ){
  129443. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  129444. return;
  129445. }
  129446. /* Retrieve matchinfo() data. */
  129447. rc = fts3GetMatchinfo(pCsr, zFormat);
  129448. sqlite3Fts3SegmentsClose(pTab);
  129449. if( rc!=SQLITE_OK ){
  129450. sqlite3_result_error_code(pContext, rc);
  129451. }else{
  129452. int n = pCsr->nMatchinfo * sizeof(u32);
  129453. sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
  129454. }
  129455. }
  129456. #endif
  129457. /************** End of fts3_snippet.c ****************************************/
  129458. /************** Begin file fts3_unicode.c ************************************/
  129459. /*
  129460. ** 2012 May 24
  129461. **
  129462. ** The author disclaims copyright to this source code. In place of
  129463. ** a legal notice, here is a blessing:
  129464. **
  129465. ** May you do good and not evil.
  129466. ** May you find forgiveness for yourself and forgive others.
  129467. ** May you share freely, never taking more than you give.
  129468. **
  129469. ******************************************************************************
  129470. **
  129471. ** Implementation of the "unicode" full-text-search tokenizer.
  129472. */
  129473. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  129474. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  129475. /* #include <assert.h> */
  129476. /* #include <stdlib.h> */
  129477. /* #include <stdio.h> */
  129478. /* #include <string.h> */
  129479. /*
  129480. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  129481. ** from the sqlite3 source file utf.c. If this file is compiled as part
  129482. ** of the amalgamation, they are not required.
  129483. */
  129484. #ifndef SQLITE_AMALGAMATION
  129485. static const unsigned char sqlite3Utf8Trans1[] = {
  129486. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  129487. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  129488. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  129489. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  129490. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  129491. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  129492. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  129493. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  129494. };
  129495. #define READ_UTF8(zIn, zTerm, c) \
  129496. c = *(zIn++); \
  129497. if( c>=0xc0 ){ \
  129498. c = sqlite3Utf8Trans1[c-0xc0]; \
  129499. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  129500. c = (c<<6) + (0x3f & *(zIn++)); \
  129501. } \
  129502. if( c<0x80 \
  129503. || (c&0xFFFFF800)==0xD800 \
  129504. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  129505. }
  129506. #define WRITE_UTF8(zOut, c) { \
  129507. if( c<0x00080 ){ \
  129508. *zOut++ = (u8)(c&0xFF); \
  129509. } \
  129510. else if( c<0x00800 ){ \
  129511. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  129512. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  129513. } \
  129514. else if( c<0x10000 ){ \
  129515. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  129516. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  129517. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  129518. }else{ \
  129519. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  129520. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  129521. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  129522. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  129523. } \
  129524. }
  129525. #endif /* ifndef SQLITE_AMALGAMATION */
  129526. typedef struct unicode_tokenizer unicode_tokenizer;
  129527. typedef struct unicode_cursor unicode_cursor;
  129528. struct unicode_tokenizer {
  129529. sqlite3_tokenizer base;
  129530. int bRemoveDiacritic;
  129531. int nException;
  129532. int *aiException;
  129533. };
  129534. struct unicode_cursor {
  129535. sqlite3_tokenizer_cursor base;
  129536. const unsigned char *aInput; /* Input text being tokenized */
  129537. int nInput; /* Size of aInput[] in bytes */
  129538. int iOff; /* Current offset within aInput[] */
  129539. int iToken; /* Index of next token to be returned */
  129540. char *zToken; /* storage for current token */
  129541. int nAlloc; /* space allocated at zToken */
  129542. };
  129543. /*
  129544. ** Destroy a tokenizer allocated by unicodeCreate().
  129545. */
  129546. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  129547. if( pTokenizer ){
  129548. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  129549. sqlite3_free(p->aiException);
  129550. sqlite3_free(p);
  129551. }
  129552. return SQLITE_OK;
  129553. }
  129554. /*
  129555. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  129556. ** statement has specified that the tokenizer for this table shall consider
  129557. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  129558. ** token characters (if bAlnum==1).
  129559. **
  129560. ** For each codepoint in the zIn/nIn string, this function checks if the
  129561. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  129562. ** If so, no action is taken. Otherwise, the codepoint is added to the
  129563. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  129564. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  129565. ** codepoints in the aiException[] array.
  129566. **
  129567. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  129568. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  129569. ** It is not possible to change the behavior of the tokenizer with respect
  129570. ** to these codepoints.
  129571. */
  129572. static int unicodeAddExceptions(
  129573. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  129574. int bAlnum, /* Replace Isalnum() return value with this */
  129575. const char *zIn, /* Array of characters to make exceptions */
  129576. int nIn /* Length of z in bytes */
  129577. ){
  129578. const unsigned char *z = (const unsigned char *)zIn;
  129579. const unsigned char *zTerm = &z[nIn];
  129580. int iCode;
  129581. int nEntry = 0;
  129582. assert( bAlnum==0 || bAlnum==1 );
  129583. while( z<zTerm ){
  129584. READ_UTF8(z, zTerm, iCode);
  129585. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  129586. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  129587. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  129588. ){
  129589. nEntry++;
  129590. }
  129591. }
  129592. if( nEntry ){
  129593. int *aNew; /* New aiException[] array */
  129594. int nNew; /* Number of valid entries in array aNew[] */
  129595. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  129596. if( aNew==0 ) return SQLITE_NOMEM;
  129597. nNew = p->nException;
  129598. z = (const unsigned char *)zIn;
  129599. while( z<zTerm ){
  129600. READ_UTF8(z, zTerm, iCode);
  129601. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  129602. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  129603. ){
  129604. int i, j;
  129605. for(i=0; i<nNew && aNew[i]<iCode; i++);
  129606. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  129607. aNew[i] = iCode;
  129608. nNew++;
  129609. }
  129610. }
  129611. p->aiException = aNew;
  129612. p->nException = nNew;
  129613. }
  129614. return SQLITE_OK;
  129615. }
  129616. /*
  129617. ** Return true if the p->aiException[] array contains the value iCode.
  129618. */
  129619. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  129620. if( p->nException>0 ){
  129621. int *a = p->aiException;
  129622. int iLo = 0;
  129623. int iHi = p->nException-1;
  129624. while( iHi>=iLo ){
  129625. int iTest = (iHi + iLo) / 2;
  129626. if( iCode==a[iTest] ){
  129627. return 1;
  129628. }else if( iCode>a[iTest] ){
  129629. iLo = iTest+1;
  129630. }else{
  129631. iHi = iTest-1;
  129632. }
  129633. }
  129634. }
  129635. return 0;
  129636. }
  129637. /*
  129638. ** Return true if, for the purposes of tokenization, codepoint iCode is
  129639. ** considered a token character (not a separator).
  129640. */
  129641. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  129642. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  129643. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  129644. }
  129645. /*
  129646. ** Create a new tokenizer instance.
  129647. */
  129648. static int unicodeCreate(
  129649. int nArg, /* Size of array argv[] */
  129650. const char * const *azArg, /* Tokenizer creation arguments */
  129651. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  129652. ){
  129653. unicode_tokenizer *pNew; /* New tokenizer object */
  129654. int i;
  129655. int rc = SQLITE_OK;
  129656. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  129657. if( pNew==NULL ) return SQLITE_NOMEM;
  129658. memset(pNew, 0, sizeof(unicode_tokenizer));
  129659. pNew->bRemoveDiacritic = 1;
  129660. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  129661. const char *z = azArg[i];
  129662. int n = strlen(z);
  129663. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  129664. pNew->bRemoveDiacritic = 1;
  129665. }
  129666. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  129667. pNew->bRemoveDiacritic = 0;
  129668. }
  129669. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  129670. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  129671. }
  129672. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  129673. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  129674. }
  129675. else{
  129676. /* Unrecognized argument */
  129677. rc = SQLITE_ERROR;
  129678. }
  129679. }
  129680. if( rc!=SQLITE_OK ){
  129681. unicodeDestroy((sqlite3_tokenizer *)pNew);
  129682. pNew = 0;
  129683. }
  129684. *pp = (sqlite3_tokenizer *)pNew;
  129685. return rc;
  129686. }
  129687. /*
  129688. ** Prepare to begin tokenizing a particular string. The input
  129689. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  129690. ** used to incrementally tokenize this string is returned in
  129691. ** *ppCursor.
  129692. */
  129693. static int unicodeOpen(
  129694. sqlite3_tokenizer *p, /* The tokenizer */
  129695. const char *aInput, /* Input string */
  129696. int nInput, /* Size of string aInput in bytes */
  129697. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  129698. ){
  129699. unicode_cursor *pCsr;
  129700. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  129701. if( pCsr==0 ){
  129702. return SQLITE_NOMEM;
  129703. }
  129704. memset(pCsr, 0, sizeof(unicode_cursor));
  129705. pCsr->aInput = (const unsigned char *)aInput;
  129706. if( aInput==0 ){
  129707. pCsr->nInput = 0;
  129708. }else if( nInput<0 ){
  129709. pCsr->nInput = (int)strlen(aInput);
  129710. }else{
  129711. pCsr->nInput = nInput;
  129712. }
  129713. *pp = &pCsr->base;
  129714. UNUSED_PARAMETER(p);
  129715. return SQLITE_OK;
  129716. }
  129717. /*
  129718. ** Close a tokenization cursor previously opened by a call to
  129719. ** simpleOpen() above.
  129720. */
  129721. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  129722. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  129723. sqlite3_free(pCsr->zToken);
  129724. sqlite3_free(pCsr);
  129725. return SQLITE_OK;
  129726. }
  129727. /*
  129728. ** Extract the next token from a tokenization cursor. The cursor must
  129729. ** have been opened by a prior call to simpleOpen().
  129730. */
  129731. static int unicodeNext(
  129732. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  129733. const char **paToken, /* OUT: Token text */
  129734. int *pnToken, /* OUT: Number of bytes at *paToken */
  129735. int *piStart, /* OUT: Starting offset of token */
  129736. int *piEnd, /* OUT: Ending offset of token */
  129737. int *piPos /* OUT: Position integer of token */
  129738. ){
  129739. unicode_cursor *pCsr = (unicode_cursor *)pC;
  129740. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  129741. int iCode;
  129742. char *zOut;
  129743. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  129744. const unsigned char *zStart = z;
  129745. const unsigned char *zEnd;
  129746. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  129747. /* Scan past any delimiter characters before the start of the next token.
  129748. ** Return SQLITE_DONE early if this takes us all the way to the end of
  129749. ** the input. */
  129750. while( z<zTerm ){
  129751. READ_UTF8(z, zTerm, iCode);
  129752. if( unicodeIsAlnum(p, iCode) ) break;
  129753. zStart = z;
  129754. }
  129755. if( zStart>=zTerm ) return SQLITE_DONE;
  129756. zOut = pCsr->zToken;
  129757. do {
  129758. int iOut;
  129759. /* Grow the output buffer if required. */
  129760. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  129761. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  129762. if( !zNew ) return SQLITE_NOMEM;
  129763. zOut = &zNew[zOut - pCsr->zToken];
  129764. pCsr->zToken = zNew;
  129765. pCsr->nAlloc += 64;
  129766. }
  129767. /* Write the folded case of the last character read to the output */
  129768. zEnd = z;
  129769. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  129770. if( iOut ){
  129771. WRITE_UTF8(zOut, iOut);
  129772. }
  129773. /* If the cursor is not at EOF, read the next character */
  129774. if( z>=zTerm ) break;
  129775. READ_UTF8(z, zTerm, iCode);
  129776. }while( unicodeIsAlnum(p, iCode)
  129777. || sqlite3FtsUnicodeIsdiacritic(iCode)
  129778. );
  129779. /* Set the output variables and return. */
  129780. pCsr->iOff = (z - pCsr->aInput);
  129781. *paToken = pCsr->zToken;
  129782. *pnToken = zOut - pCsr->zToken;
  129783. *piStart = (zStart - pCsr->aInput);
  129784. *piEnd = (zEnd - pCsr->aInput);
  129785. *piPos = pCsr->iToken++;
  129786. return SQLITE_OK;
  129787. }
  129788. /*
  129789. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  129790. ** structure for the unicode tokenizer.
  129791. */
  129792. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  129793. static const sqlite3_tokenizer_module module = {
  129794. 0,
  129795. unicodeCreate,
  129796. unicodeDestroy,
  129797. unicodeOpen,
  129798. unicodeClose,
  129799. unicodeNext,
  129800. 0,
  129801. };
  129802. *ppModule = &module;
  129803. }
  129804. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  129805. #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
  129806. /************** End of fts3_unicode.c ****************************************/
  129807. /************** Begin file fts3_unicode2.c ***********************************/
  129808. /*
  129809. ** 2012 May 25
  129810. **
  129811. ** The author disclaims copyright to this source code. In place of
  129812. ** a legal notice, here is a blessing:
  129813. **
  129814. ** May you do good and not evil.
  129815. ** May you find forgiveness for yourself and forgive others.
  129816. ** May you share freely, never taking more than you give.
  129817. **
  129818. ******************************************************************************
  129819. */
  129820. /*
  129821. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  129822. */
  129823. #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
  129824. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  129825. /* #include <assert.h> */
  129826. /*
  129827. ** Return true if the argument corresponds to a unicode codepoint
  129828. ** classified as either a letter or a number. Otherwise false.
  129829. **
  129830. ** The results are undefined if the value passed to this function
  129831. ** is less than zero.
  129832. */
  129833. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  129834. /* Each unsigned integer in the following array corresponds to a contiguous
  129835. ** range of unicode codepoints that are not either letters or numbers (i.e.
  129836. ** codepoints for which this function should return 0).
  129837. **
  129838. ** The most significant 22 bits in each 32-bit value contain the first
  129839. ** codepoint in the range. The least significant 10 bits are used to store
  129840. ** the size of the range (always at least 1). In other words, the value
  129841. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  129842. ** C. It is not possible to represent a range larger than 1023 codepoints
  129843. ** using this format.
  129844. */
  129845. const static unsigned int aEntry[] = {
  129846. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  129847. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  129848. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  129849. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  129850. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  129851. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  129852. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  129853. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  129854. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  129855. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  129856. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  129857. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  129858. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  129859. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  129860. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  129861. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  129862. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  129863. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  129864. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  129865. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  129866. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  129867. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  129868. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  129869. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  129870. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  129871. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  129872. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  129873. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  129874. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  129875. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  129876. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  129877. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  129878. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  129879. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  129880. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  129881. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  129882. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  129883. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  129884. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  129885. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  129886. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  129887. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  129888. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  129889. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  129890. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  129891. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  129892. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  129893. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  129894. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  129895. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  129896. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  129897. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  129898. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  129899. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  129900. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  129901. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  129902. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  129903. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  129904. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  129905. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  129906. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  129907. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  129908. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  129909. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  129910. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  129911. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  129912. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  129913. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  129914. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  129915. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  129916. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  129917. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  129918. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  129919. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  129920. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  129921. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  129922. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  129923. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  129924. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  129925. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  129926. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  129927. 0x380400F0,
  129928. };
  129929. static const unsigned int aAscii[4] = {
  129930. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  129931. };
  129932. if( c<128 ){
  129933. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  129934. }else if( c<(1<<22) ){
  129935. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  129936. int iRes;
  129937. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  129938. int iLo = 0;
  129939. while( iHi>=iLo ){
  129940. int iTest = (iHi + iLo) / 2;
  129941. if( key >= aEntry[iTest] ){
  129942. iRes = iTest;
  129943. iLo = iTest+1;
  129944. }else{
  129945. iHi = iTest-1;
  129946. }
  129947. }
  129948. assert( aEntry[0]<key );
  129949. assert( key>=aEntry[iRes] );
  129950. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  129951. }
  129952. return 1;
  129953. }
  129954. /*
  129955. ** If the argument is a codepoint corresponding to a lowercase letter
  129956. ** in the ASCII range with a diacritic added, return the codepoint
  129957. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  129958. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  129959. ** E"). The resuls of passing a codepoint that corresponds to an
  129960. ** uppercase letter are undefined.
  129961. */
  129962. static int remove_diacritic(int c){
  129963. unsigned short aDia[] = {
  129964. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  129965. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  129966. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  129967. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  129968. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  129969. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  129970. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  129971. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  129972. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  129973. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  129974. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  129975. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  129976. 62924, 63050, 63082, 63274, 63390,
  129977. };
  129978. char aChar[] = {
  129979. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  129980. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  129981. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  129982. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  129983. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  129984. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  129985. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  129986. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  129987. 'e', 'i', 'o', 'u', 'y',
  129988. };
  129989. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  129990. int iRes = 0;
  129991. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  129992. int iLo = 0;
  129993. while( iHi>=iLo ){
  129994. int iTest = (iHi + iLo) / 2;
  129995. if( key >= aDia[iTest] ){
  129996. iRes = iTest;
  129997. iLo = iTest+1;
  129998. }else{
  129999. iHi = iTest-1;
  130000. }
  130001. }
  130002. assert( key>=aDia[iRes] );
  130003. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  130004. };
  130005. /*
  130006. ** Return true if the argument interpreted as a unicode codepoint
  130007. ** is a diacritical modifier character.
  130008. */
  130009. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  130010. unsigned int mask0 = 0x08029FDF;
  130011. unsigned int mask1 = 0x000361F8;
  130012. if( c<768 || c>817 ) return 0;
  130013. return (c < 768+32) ?
  130014. (mask0 & (1 << (c-768))) :
  130015. (mask1 & (1 << (c-768-32)));
  130016. }
  130017. /*
  130018. ** Interpret the argument as a unicode codepoint. If the codepoint
  130019. ** is an upper case character that has a lower case equivalent,
  130020. ** return the codepoint corresponding to the lower case version.
  130021. ** Otherwise, return a copy of the argument.
  130022. **
  130023. ** The results are undefined if the value passed to this function
  130024. ** is less than zero.
  130025. */
  130026. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  130027. /* Each entry in the following array defines a rule for folding a range
  130028. ** of codepoints to lower case. The rule applies to a range of nRange
  130029. ** codepoints starting at codepoint iCode.
  130030. **
  130031. ** If the least significant bit in flags is clear, then the rule applies
  130032. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  130033. ** need to be folded). Or, if it is set, then the rule only applies to
  130034. ** every second codepoint in the range, starting with codepoint C.
  130035. **
  130036. ** The 7 most significant bits in flags are an index into the aiOff[]
  130037. ** array. If a specific codepoint C does require folding, then its lower
  130038. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  130039. **
  130040. ** The contents of this array are generated by parsing the CaseFolding.txt
  130041. ** file distributed as part of the "Unicode Character Database". See
  130042. ** http://www.unicode.org for details.
  130043. */
  130044. static const struct TableEntry {
  130045. unsigned short iCode;
  130046. unsigned char flags;
  130047. unsigned char nRange;
  130048. } aEntry[] = {
  130049. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  130050. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  130051. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  130052. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  130053. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  130054. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  130055. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  130056. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  130057. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  130058. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  130059. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  130060. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  130061. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  130062. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  130063. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  130064. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  130065. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  130066. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  130067. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  130068. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  130069. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  130070. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  130071. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  130072. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  130073. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  130074. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  130075. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  130076. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  130077. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  130078. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  130079. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  130080. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  130081. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  130082. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  130083. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  130084. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  130085. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  130086. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  130087. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  130088. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  130089. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  130090. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  130091. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  130092. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  130093. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  130094. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  130095. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  130096. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  130097. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  130098. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  130099. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  130100. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  130101. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  130102. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  130103. {65313, 14, 26},
  130104. };
  130105. static const unsigned short aiOff[] = {
  130106. 1, 2, 8, 15, 16, 26, 28, 32,
  130107. 37, 38, 40, 48, 63, 64, 69, 71,
  130108. 79, 80, 116, 202, 203, 205, 206, 207,
  130109. 209, 210, 211, 213, 214, 217, 218, 219,
  130110. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  130111. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  130112. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  130113. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  130114. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  130115. 65514, 65521, 65527, 65528, 65529,
  130116. };
  130117. int ret = c;
  130118. assert( c>=0 );
  130119. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  130120. if( c<128 ){
  130121. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  130122. }else if( c<65536 ){
  130123. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  130124. int iLo = 0;
  130125. int iRes = -1;
  130126. while( iHi>=iLo ){
  130127. int iTest = (iHi + iLo) / 2;
  130128. int cmp = (c - aEntry[iTest].iCode);
  130129. if( cmp>=0 ){
  130130. iRes = iTest;
  130131. iLo = iTest+1;
  130132. }else{
  130133. iHi = iTest-1;
  130134. }
  130135. }
  130136. assert( iRes<0 || c>=aEntry[iRes].iCode );
  130137. if( iRes>=0 ){
  130138. const struct TableEntry *p = &aEntry[iRes];
  130139. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  130140. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  130141. assert( ret>0 );
  130142. }
  130143. }
  130144. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  130145. }
  130146. else if( c>=66560 && c<66600 ){
  130147. ret = c + 40;
  130148. }
  130149. return ret;
  130150. }
  130151. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  130152. #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
  130153. /************** End of fts3_unicode2.c ***************************************/
  130154. /************** Begin file rtree.c *******************************************/
  130155. /*
  130156. ** 2001 September 15
  130157. **
  130158. ** The author disclaims copyright to this source code. In place of
  130159. ** a legal notice, here is a blessing:
  130160. **
  130161. ** May you do good and not evil.
  130162. ** May you find forgiveness for yourself and forgive others.
  130163. ** May you share freely, never taking more than you give.
  130164. **
  130165. *************************************************************************
  130166. ** This file contains code for implementations of the r-tree and r*-tree
  130167. ** algorithms packaged as an SQLite virtual table module.
  130168. */
  130169. /*
  130170. ** Database Format of R-Tree Tables
  130171. ** --------------------------------
  130172. **
  130173. ** The data structure for a single virtual r-tree table is stored in three
  130174. ** native SQLite tables declared as follows. In each case, the '%' character
  130175. ** in the table name is replaced with the user-supplied name of the r-tree
  130176. ** table.
  130177. **
  130178. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  130179. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  130180. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  130181. **
  130182. ** The data for each node of the r-tree structure is stored in the %_node
  130183. ** table. For each node that is not the root node of the r-tree, there is
  130184. ** an entry in the %_parent table associating the node with its parent.
  130185. ** And for each row of data in the table, there is an entry in the %_rowid
  130186. ** table that maps from the entries rowid to the id of the node that it
  130187. ** is stored on.
  130188. **
  130189. ** The root node of an r-tree always exists, even if the r-tree table is
  130190. ** empty. The nodeno of the root node is always 1. All other nodes in the
  130191. ** table must be the same size as the root node. The content of each node
  130192. ** is formatted as follows:
  130193. **
  130194. ** 1. If the node is the root node (node 1), then the first 2 bytes
  130195. ** of the node contain the tree depth as a big-endian integer.
  130196. ** For non-root nodes, the first 2 bytes are left unused.
  130197. **
  130198. ** 2. The next 2 bytes contain the number of entries currently
  130199. ** stored in the node.
  130200. **
  130201. ** 3. The remainder of the node contains the node entries. Each entry
  130202. ** consists of a single 8-byte integer followed by an even number
  130203. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  130204. ** of a record. For internal nodes it is the node number of a
  130205. ** child page.
  130206. */
  130207. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  130208. /*
  130209. ** This file contains an implementation of a couple of different variants
  130210. ** of the r-tree algorithm. See the README file for further details. The
  130211. ** same data-structure is used for all, but the algorithms for insert and
  130212. ** delete operations vary. The variants used are selected at compile time
  130213. ** by defining the following symbols:
  130214. */
  130215. /* Either, both or none of the following may be set to activate
  130216. ** r*tree variant algorithms.
  130217. */
  130218. #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
  130219. #define VARIANT_RSTARTREE_REINSERT 1
  130220. /*
  130221. ** Exactly one of the following must be set to 1.
  130222. */
  130223. #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
  130224. #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
  130225. #define VARIANT_RSTARTREE_SPLIT 1
  130226. #define VARIANT_GUTTMAN_SPLIT \
  130227. (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
  130228. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  130229. #define PickNext QuadraticPickNext
  130230. #define PickSeeds QuadraticPickSeeds
  130231. #define AssignCells splitNodeGuttman
  130232. #endif
  130233. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  130234. #define PickNext LinearPickNext
  130235. #define PickSeeds LinearPickSeeds
  130236. #define AssignCells splitNodeGuttman
  130237. #endif
  130238. #if VARIANT_RSTARTREE_SPLIT
  130239. #define AssignCells splitNodeStartree
  130240. #endif
  130241. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  130242. # define NDEBUG 1
  130243. #endif
  130244. #ifndef SQLITE_CORE
  130245. SQLITE_EXTENSION_INIT1
  130246. #else
  130247. #endif
  130248. /* #include <string.h> */
  130249. /* #include <assert.h> */
  130250. #ifndef SQLITE_AMALGAMATION
  130251. #include "sqlite3rtree.h"
  130252. typedef sqlite3_int64 i64;
  130253. typedef unsigned char u8;
  130254. typedef unsigned int u32;
  130255. #endif
  130256. /* The following macro is used to suppress compiler warnings.
  130257. */
  130258. #ifndef UNUSED_PARAMETER
  130259. # define UNUSED_PARAMETER(x) (void)(x)
  130260. #endif
  130261. typedef struct Rtree Rtree;
  130262. typedef struct RtreeCursor RtreeCursor;
  130263. typedef struct RtreeNode RtreeNode;
  130264. typedef struct RtreeCell RtreeCell;
  130265. typedef struct RtreeConstraint RtreeConstraint;
  130266. typedef struct RtreeMatchArg RtreeMatchArg;
  130267. typedef struct RtreeGeomCallback RtreeGeomCallback;
  130268. typedef union RtreeCoord RtreeCoord;
  130269. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  130270. #define RTREE_MAX_DIMENSIONS 5
  130271. /* Size of hash table Rtree.aHash. This hash table is not expected to
  130272. ** ever contain very many entries, so a fixed number of buckets is
  130273. ** used.
  130274. */
  130275. #define HASHSIZE 128
  130276. /*
  130277. ** An rtree virtual-table object.
  130278. */
  130279. struct Rtree {
  130280. sqlite3_vtab base;
  130281. sqlite3 *db; /* Host database connection */
  130282. int iNodeSize; /* Size in bytes of each node in the node table */
  130283. int nDim; /* Number of dimensions */
  130284. int nBytesPerCell; /* Bytes consumed per cell */
  130285. int iDepth; /* Current depth of the r-tree structure */
  130286. char *zDb; /* Name of database containing r-tree table */
  130287. char *zName; /* Name of r-tree table */
  130288. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  130289. int nBusy; /* Current number of users of this structure */
  130290. /* List of nodes removed during a CondenseTree operation. List is
  130291. ** linked together via the pointer normally used for hash chains -
  130292. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  130293. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  130294. */
  130295. RtreeNode *pDeleted;
  130296. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  130297. /* Statements to read/write/delete a record from xxx_node */
  130298. sqlite3_stmt *pReadNode;
  130299. sqlite3_stmt *pWriteNode;
  130300. sqlite3_stmt *pDeleteNode;
  130301. /* Statements to read/write/delete a record from xxx_rowid */
  130302. sqlite3_stmt *pReadRowid;
  130303. sqlite3_stmt *pWriteRowid;
  130304. sqlite3_stmt *pDeleteRowid;
  130305. /* Statements to read/write/delete a record from xxx_parent */
  130306. sqlite3_stmt *pReadParent;
  130307. sqlite3_stmt *pWriteParent;
  130308. sqlite3_stmt *pDeleteParent;
  130309. int eCoordType;
  130310. };
  130311. /* Possible values for eCoordType: */
  130312. #define RTREE_COORD_REAL32 0
  130313. #define RTREE_COORD_INT32 1
  130314. /*
  130315. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  130316. ** only deal with integer coordinates. No floating point operations
  130317. ** will be done.
  130318. */
  130319. #ifdef SQLITE_RTREE_INT_ONLY
  130320. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  130321. typedef int RtreeValue; /* Low accuracy coordinate */
  130322. #else
  130323. typedef double RtreeDValue; /* High accuracy coordinate */
  130324. typedef float RtreeValue; /* Low accuracy coordinate */
  130325. #endif
  130326. /*
  130327. ** The minimum number of cells allowed for a node is a third of the
  130328. ** maximum. In Gutman's notation:
  130329. **
  130330. ** m = M/3
  130331. **
  130332. ** If an R*-tree "Reinsert" operation is required, the same number of
  130333. ** cells are removed from the overfull node and reinserted into the tree.
  130334. */
  130335. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  130336. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  130337. #define RTREE_MAXCELLS 51
  130338. /*
  130339. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  130340. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  130341. ** Therefore all non-root nodes must contain at least 3 entries. Since
  130342. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  130343. ** 40 or less.
  130344. */
  130345. #define RTREE_MAX_DEPTH 40
  130346. /*
  130347. ** An rtree cursor object.
  130348. */
  130349. struct RtreeCursor {
  130350. sqlite3_vtab_cursor base;
  130351. RtreeNode *pNode; /* Node cursor is currently pointing at */
  130352. int iCell; /* Index of current cell in pNode */
  130353. int iStrategy; /* Copy of idxNum search parameter */
  130354. int nConstraint; /* Number of entries in aConstraint */
  130355. RtreeConstraint *aConstraint; /* Search constraints. */
  130356. };
  130357. union RtreeCoord {
  130358. RtreeValue f;
  130359. int i;
  130360. };
  130361. /*
  130362. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  130363. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  130364. ** variable pRtree points to the Rtree structure associated with the
  130365. ** RtreeCoord.
  130366. */
  130367. #ifdef SQLITE_RTREE_INT_ONLY
  130368. # define DCOORD(coord) ((RtreeDValue)coord.i)
  130369. #else
  130370. # define DCOORD(coord) ( \
  130371. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  130372. ((double)coord.f) : \
  130373. ((double)coord.i) \
  130374. )
  130375. #endif
  130376. /*
  130377. ** A search constraint.
  130378. */
  130379. struct RtreeConstraint {
  130380. int iCoord; /* Index of constrained coordinate */
  130381. int op; /* Constraining operation */
  130382. RtreeDValue rValue; /* Constraint value. */
  130383. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  130384. sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
  130385. };
  130386. /* Possible values for RtreeConstraint.op */
  130387. #define RTREE_EQ 0x41
  130388. #define RTREE_LE 0x42
  130389. #define RTREE_LT 0x43
  130390. #define RTREE_GE 0x44
  130391. #define RTREE_GT 0x45
  130392. #define RTREE_MATCH 0x46
  130393. /*
  130394. ** An rtree structure node.
  130395. */
  130396. struct RtreeNode {
  130397. RtreeNode *pParent; /* Parent node */
  130398. i64 iNode;
  130399. int nRef;
  130400. int isDirty;
  130401. u8 *zData;
  130402. RtreeNode *pNext; /* Next node in this hash chain */
  130403. };
  130404. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  130405. /*
  130406. ** Structure to store a deserialized rtree record.
  130407. */
  130408. struct RtreeCell {
  130409. i64 iRowid;
  130410. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
  130411. };
  130412. /*
  130413. ** Value for the first field of every RtreeMatchArg object. The MATCH
  130414. ** operator tests that the first field of a blob operand matches this
  130415. ** value to avoid operating on invalid blobs (which could cause a segfault).
  130416. */
  130417. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  130418. /*
  130419. ** An instance of this structure must be supplied as a blob argument to
  130420. ** the right-hand-side of an SQL MATCH operator used to constrain an
  130421. ** r-tree query.
  130422. */
  130423. struct RtreeMatchArg {
  130424. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  130425. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
  130426. void *pContext;
  130427. int nParam;
  130428. RtreeDValue aParam[1];
  130429. };
  130430. /*
  130431. ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
  130432. ** a single instance of the following structure is allocated. It is used
  130433. ** as the context for the user-function created by by s_r_g_c(). The object
  130434. ** is eventually deleted by the destructor mechanism provided by
  130435. ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
  130436. ** the geometry callback function).
  130437. */
  130438. struct RtreeGeomCallback {
  130439. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  130440. void *pContext;
  130441. };
  130442. #ifndef MAX
  130443. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  130444. #endif
  130445. #ifndef MIN
  130446. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  130447. #endif
  130448. /*
  130449. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  130450. ** 64 bit integer. The deserialized value is returned.
  130451. */
  130452. static int readInt16(u8 *p){
  130453. return (p[0]<<8) + p[1];
  130454. }
  130455. static void readCoord(u8 *p, RtreeCoord *pCoord){
  130456. u32 i = (
  130457. (((u32)p[0]) << 24) +
  130458. (((u32)p[1]) << 16) +
  130459. (((u32)p[2]) << 8) +
  130460. (((u32)p[3]) << 0)
  130461. );
  130462. *(u32 *)pCoord = i;
  130463. }
  130464. static i64 readInt64(u8 *p){
  130465. return (
  130466. (((i64)p[0]) << 56) +
  130467. (((i64)p[1]) << 48) +
  130468. (((i64)p[2]) << 40) +
  130469. (((i64)p[3]) << 32) +
  130470. (((i64)p[4]) << 24) +
  130471. (((i64)p[5]) << 16) +
  130472. (((i64)p[6]) << 8) +
  130473. (((i64)p[7]) << 0)
  130474. );
  130475. }
  130476. /*
  130477. ** Functions to serialize a 16 bit integer, 32 bit real number and
  130478. ** 64 bit integer. The value returned is the number of bytes written
  130479. ** to the argument buffer (always 2, 4 and 8 respectively).
  130480. */
  130481. static int writeInt16(u8 *p, int i){
  130482. p[0] = (i>> 8)&0xFF;
  130483. p[1] = (i>> 0)&0xFF;
  130484. return 2;
  130485. }
  130486. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  130487. u32 i;
  130488. assert( sizeof(RtreeCoord)==4 );
  130489. assert( sizeof(u32)==4 );
  130490. i = *(u32 *)pCoord;
  130491. p[0] = (i>>24)&0xFF;
  130492. p[1] = (i>>16)&0xFF;
  130493. p[2] = (i>> 8)&0xFF;
  130494. p[3] = (i>> 0)&0xFF;
  130495. return 4;
  130496. }
  130497. static int writeInt64(u8 *p, i64 i){
  130498. p[0] = (i>>56)&0xFF;
  130499. p[1] = (i>>48)&0xFF;
  130500. p[2] = (i>>40)&0xFF;
  130501. p[3] = (i>>32)&0xFF;
  130502. p[4] = (i>>24)&0xFF;
  130503. p[5] = (i>>16)&0xFF;
  130504. p[6] = (i>> 8)&0xFF;
  130505. p[7] = (i>> 0)&0xFF;
  130506. return 8;
  130507. }
  130508. /*
  130509. ** Increment the reference count of node p.
  130510. */
  130511. static void nodeReference(RtreeNode *p){
  130512. if( p ){
  130513. p->nRef++;
  130514. }
  130515. }
  130516. /*
  130517. ** Clear the content of node p (set all bytes to 0x00).
  130518. */
  130519. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  130520. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  130521. p->isDirty = 1;
  130522. }
  130523. /*
  130524. ** Given a node number iNode, return the corresponding key to use
  130525. ** in the Rtree.aHash table.
  130526. */
  130527. static int nodeHash(i64 iNode){
  130528. return (
  130529. (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
  130530. (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
  130531. ) % HASHSIZE;
  130532. }
  130533. /*
  130534. ** Search the node hash table for node iNode. If found, return a pointer
  130535. ** to it. Otherwise, return 0.
  130536. */
  130537. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  130538. RtreeNode *p;
  130539. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  130540. return p;
  130541. }
  130542. /*
  130543. ** Add node pNode to the node hash table.
  130544. */
  130545. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  130546. int iHash;
  130547. assert( pNode->pNext==0 );
  130548. iHash = nodeHash(pNode->iNode);
  130549. pNode->pNext = pRtree->aHash[iHash];
  130550. pRtree->aHash[iHash] = pNode;
  130551. }
  130552. /*
  130553. ** Remove node pNode from the node hash table.
  130554. */
  130555. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  130556. RtreeNode **pp;
  130557. if( pNode->iNode!=0 ){
  130558. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  130559. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  130560. *pp = pNode->pNext;
  130561. pNode->pNext = 0;
  130562. }
  130563. }
  130564. /*
  130565. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  130566. ** indicating that node has not yet been assigned a node number. It is
  130567. ** assigned a node number when nodeWrite() is called to write the
  130568. ** node contents out to the database.
  130569. */
  130570. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  130571. RtreeNode *pNode;
  130572. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  130573. if( pNode ){
  130574. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  130575. pNode->zData = (u8 *)&pNode[1];
  130576. pNode->nRef = 1;
  130577. pNode->pParent = pParent;
  130578. pNode->isDirty = 1;
  130579. nodeReference(pParent);
  130580. }
  130581. return pNode;
  130582. }
  130583. /*
  130584. ** Obtain a reference to an r-tree node.
  130585. */
  130586. static int
  130587. nodeAcquire(
  130588. Rtree *pRtree, /* R-tree structure */
  130589. i64 iNode, /* Node number to load */
  130590. RtreeNode *pParent, /* Either the parent node or NULL */
  130591. RtreeNode **ppNode /* OUT: Acquired node */
  130592. ){
  130593. int rc;
  130594. int rc2 = SQLITE_OK;
  130595. RtreeNode *pNode;
  130596. /* Check if the requested node is already in the hash table. If so,
  130597. ** increase its reference count and return it.
  130598. */
  130599. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  130600. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  130601. if( pParent && !pNode->pParent ){
  130602. nodeReference(pParent);
  130603. pNode->pParent = pParent;
  130604. }
  130605. pNode->nRef++;
  130606. *ppNode = pNode;
  130607. return SQLITE_OK;
  130608. }
  130609. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  130610. rc = sqlite3_step(pRtree->pReadNode);
  130611. if( rc==SQLITE_ROW ){
  130612. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  130613. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  130614. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  130615. if( !pNode ){
  130616. rc2 = SQLITE_NOMEM;
  130617. }else{
  130618. pNode->pParent = pParent;
  130619. pNode->zData = (u8 *)&pNode[1];
  130620. pNode->nRef = 1;
  130621. pNode->iNode = iNode;
  130622. pNode->isDirty = 0;
  130623. pNode->pNext = 0;
  130624. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  130625. nodeReference(pParent);
  130626. }
  130627. }
  130628. }
  130629. rc = sqlite3_reset(pRtree->pReadNode);
  130630. if( rc==SQLITE_OK ) rc = rc2;
  130631. /* If the root node was just loaded, set pRtree->iDepth to the height
  130632. ** of the r-tree structure. A height of zero means all data is stored on
  130633. ** the root node. A height of one means the children of the root node
  130634. ** are the leaves, and so on. If the depth as specified on the root node
  130635. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  130636. */
  130637. if( pNode && iNode==1 ){
  130638. pRtree->iDepth = readInt16(pNode->zData);
  130639. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  130640. rc = SQLITE_CORRUPT_VTAB;
  130641. }
  130642. }
  130643. /* If no error has occurred so far, check if the "number of entries"
  130644. ** field on the node is too large. If so, set the return code to
  130645. ** SQLITE_CORRUPT_VTAB.
  130646. */
  130647. if( pNode && rc==SQLITE_OK ){
  130648. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  130649. rc = SQLITE_CORRUPT_VTAB;
  130650. }
  130651. }
  130652. if( rc==SQLITE_OK ){
  130653. if( pNode!=0 ){
  130654. nodeHashInsert(pRtree, pNode);
  130655. }else{
  130656. rc = SQLITE_CORRUPT_VTAB;
  130657. }
  130658. *ppNode = pNode;
  130659. }else{
  130660. sqlite3_free(pNode);
  130661. *ppNode = 0;
  130662. }
  130663. return rc;
  130664. }
  130665. /*
  130666. ** Overwrite cell iCell of node pNode with the contents of pCell.
  130667. */
  130668. static void nodeOverwriteCell(
  130669. Rtree *pRtree,
  130670. RtreeNode *pNode,
  130671. RtreeCell *pCell,
  130672. int iCell
  130673. ){
  130674. int ii;
  130675. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  130676. p += writeInt64(p, pCell->iRowid);
  130677. for(ii=0; ii<(pRtree->nDim*2); ii++){
  130678. p += writeCoord(p, &pCell->aCoord[ii]);
  130679. }
  130680. pNode->isDirty = 1;
  130681. }
  130682. /*
  130683. ** Remove cell the cell with index iCell from node pNode.
  130684. */
  130685. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  130686. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  130687. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  130688. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  130689. memmove(pDst, pSrc, nByte);
  130690. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  130691. pNode->isDirty = 1;
  130692. }
  130693. /*
  130694. ** Insert the contents of cell pCell into node pNode. If the insert
  130695. ** is successful, return SQLITE_OK.
  130696. **
  130697. ** If there is not enough free space in pNode, return SQLITE_FULL.
  130698. */
  130699. static int
  130700. nodeInsertCell(
  130701. Rtree *pRtree,
  130702. RtreeNode *pNode,
  130703. RtreeCell *pCell
  130704. ){
  130705. int nCell; /* Current number of cells in pNode */
  130706. int nMaxCell; /* Maximum number of cells for pNode */
  130707. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  130708. nCell = NCELL(pNode);
  130709. assert( nCell<=nMaxCell );
  130710. if( nCell<nMaxCell ){
  130711. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  130712. writeInt16(&pNode->zData[2], nCell+1);
  130713. pNode->isDirty = 1;
  130714. }
  130715. return (nCell==nMaxCell);
  130716. }
  130717. /*
  130718. ** If the node is dirty, write it out to the database.
  130719. */
  130720. static int
  130721. nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  130722. int rc = SQLITE_OK;
  130723. if( pNode->isDirty ){
  130724. sqlite3_stmt *p = pRtree->pWriteNode;
  130725. if( pNode->iNode ){
  130726. sqlite3_bind_int64(p, 1, pNode->iNode);
  130727. }else{
  130728. sqlite3_bind_null(p, 1);
  130729. }
  130730. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  130731. sqlite3_step(p);
  130732. pNode->isDirty = 0;
  130733. rc = sqlite3_reset(p);
  130734. if( pNode->iNode==0 && rc==SQLITE_OK ){
  130735. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  130736. nodeHashInsert(pRtree, pNode);
  130737. }
  130738. }
  130739. return rc;
  130740. }
  130741. /*
  130742. ** Release a reference to a node. If the node is dirty and the reference
  130743. ** count drops to zero, the node data is written to the database.
  130744. */
  130745. static int
  130746. nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  130747. int rc = SQLITE_OK;
  130748. if( pNode ){
  130749. assert( pNode->nRef>0 );
  130750. pNode->nRef--;
  130751. if( pNode->nRef==0 ){
  130752. if( pNode->iNode==1 ){
  130753. pRtree->iDepth = -1;
  130754. }
  130755. if( pNode->pParent ){
  130756. rc = nodeRelease(pRtree, pNode->pParent);
  130757. }
  130758. if( rc==SQLITE_OK ){
  130759. rc = nodeWrite(pRtree, pNode);
  130760. }
  130761. nodeHashDelete(pRtree, pNode);
  130762. sqlite3_free(pNode);
  130763. }
  130764. }
  130765. return rc;
  130766. }
  130767. /*
  130768. ** Return the 64-bit integer value associated with cell iCell of
  130769. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  130770. ** an internal node, then the 64-bit integer is a child page number.
  130771. */
  130772. static i64 nodeGetRowid(
  130773. Rtree *pRtree,
  130774. RtreeNode *pNode,
  130775. int iCell
  130776. ){
  130777. assert( iCell<NCELL(pNode) );
  130778. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  130779. }
  130780. /*
  130781. ** Return coordinate iCoord from cell iCell in node pNode.
  130782. */
  130783. static void nodeGetCoord(
  130784. Rtree *pRtree,
  130785. RtreeNode *pNode,
  130786. int iCell,
  130787. int iCoord,
  130788. RtreeCoord *pCoord /* Space to write result to */
  130789. ){
  130790. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  130791. }
  130792. /*
  130793. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  130794. ** to by pCell with the results.
  130795. */
  130796. static void nodeGetCell(
  130797. Rtree *pRtree,
  130798. RtreeNode *pNode,
  130799. int iCell,
  130800. RtreeCell *pCell
  130801. ){
  130802. int ii;
  130803. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  130804. for(ii=0; ii<pRtree->nDim*2; ii++){
  130805. nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
  130806. }
  130807. }
  130808. /* Forward declaration for the function that does the work of
  130809. ** the virtual table module xCreate() and xConnect() methods.
  130810. */
  130811. static int rtreeInit(
  130812. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  130813. );
  130814. /*
  130815. ** Rtree virtual table module xCreate method.
  130816. */
  130817. static int rtreeCreate(
  130818. sqlite3 *db,
  130819. void *pAux,
  130820. int argc, const char *const*argv,
  130821. sqlite3_vtab **ppVtab,
  130822. char **pzErr
  130823. ){
  130824. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  130825. }
  130826. /*
  130827. ** Rtree virtual table module xConnect method.
  130828. */
  130829. static int rtreeConnect(
  130830. sqlite3 *db,
  130831. void *pAux,
  130832. int argc, const char *const*argv,
  130833. sqlite3_vtab **ppVtab,
  130834. char **pzErr
  130835. ){
  130836. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  130837. }
  130838. /*
  130839. ** Increment the r-tree reference count.
  130840. */
  130841. static void rtreeReference(Rtree *pRtree){
  130842. pRtree->nBusy++;
  130843. }
  130844. /*
  130845. ** Decrement the r-tree reference count. When the reference count reaches
  130846. ** zero the structure is deleted.
  130847. */
  130848. static void rtreeRelease(Rtree *pRtree){
  130849. pRtree->nBusy--;
  130850. if( pRtree->nBusy==0 ){
  130851. sqlite3_finalize(pRtree->pReadNode);
  130852. sqlite3_finalize(pRtree->pWriteNode);
  130853. sqlite3_finalize(pRtree->pDeleteNode);
  130854. sqlite3_finalize(pRtree->pReadRowid);
  130855. sqlite3_finalize(pRtree->pWriteRowid);
  130856. sqlite3_finalize(pRtree->pDeleteRowid);
  130857. sqlite3_finalize(pRtree->pReadParent);
  130858. sqlite3_finalize(pRtree->pWriteParent);
  130859. sqlite3_finalize(pRtree->pDeleteParent);
  130860. sqlite3_free(pRtree);
  130861. }
  130862. }
  130863. /*
  130864. ** Rtree virtual table module xDisconnect method.
  130865. */
  130866. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  130867. rtreeRelease((Rtree *)pVtab);
  130868. return SQLITE_OK;
  130869. }
  130870. /*
  130871. ** Rtree virtual table module xDestroy method.
  130872. */
  130873. static int rtreeDestroy(sqlite3_vtab *pVtab){
  130874. Rtree *pRtree = (Rtree *)pVtab;
  130875. int rc;
  130876. char *zCreate = sqlite3_mprintf(
  130877. "DROP TABLE '%q'.'%q_node';"
  130878. "DROP TABLE '%q'.'%q_rowid';"
  130879. "DROP TABLE '%q'.'%q_parent';",
  130880. pRtree->zDb, pRtree->zName,
  130881. pRtree->zDb, pRtree->zName,
  130882. pRtree->zDb, pRtree->zName
  130883. );
  130884. if( !zCreate ){
  130885. rc = SQLITE_NOMEM;
  130886. }else{
  130887. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  130888. sqlite3_free(zCreate);
  130889. }
  130890. if( rc==SQLITE_OK ){
  130891. rtreeRelease(pRtree);
  130892. }
  130893. return rc;
  130894. }
  130895. /*
  130896. ** Rtree virtual table module xOpen method.
  130897. */
  130898. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  130899. int rc = SQLITE_NOMEM;
  130900. RtreeCursor *pCsr;
  130901. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  130902. if( pCsr ){
  130903. memset(pCsr, 0, sizeof(RtreeCursor));
  130904. pCsr->base.pVtab = pVTab;
  130905. rc = SQLITE_OK;
  130906. }
  130907. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  130908. return rc;
  130909. }
  130910. /*
  130911. ** Free the RtreeCursor.aConstraint[] array and its contents.
  130912. */
  130913. static void freeCursorConstraints(RtreeCursor *pCsr){
  130914. if( pCsr->aConstraint ){
  130915. int i; /* Used to iterate through constraint array */
  130916. for(i=0; i<pCsr->nConstraint; i++){
  130917. sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
  130918. if( pGeom ){
  130919. if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
  130920. sqlite3_free(pGeom);
  130921. }
  130922. }
  130923. sqlite3_free(pCsr->aConstraint);
  130924. pCsr->aConstraint = 0;
  130925. }
  130926. }
  130927. /*
  130928. ** Rtree virtual table module xClose method.
  130929. */
  130930. static int rtreeClose(sqlite3_vtab_cursor *cur){
  130931. Rtree *pRtree = (Rtree *)(cur->pVtab);
  130932. int rc;
  130933. RtreeCursor *pCsr = (RtreeCursor *)cur;
  130934. freeCursorConstraints(pCsr);
  130935. rc = nodeRelease(pRtree, pCsr->pNode);
  130936. sqlite3_free(pCsr);
  130937. return rc;
  130938. }
  130939. /*
  130940. ** Rtree virtual table module xEof method.
  130941. **
  130942. ** Return non-zero if the cursor does not currently point to a valid
  130943. ** record (i.e if the scan has finished), or zero otherwise.
  130944. */
  130945. static int rtreeEof(sqlite3_vtab_cursor *cur){
  130946. RtreeCursor *pCsr = (RtreeCursor *)cur;
  130947. return (pCsr->pNode==0);
  130948. }
  130949. /*
  130950. ** The r-tree constraint passed as the second argument to this function is
  130951. ** guaranteed to be a MATCH constraint.
  130952. */
  130953. static int testRtreeGeom(
  130954. Rtree *pRtree, /* R-Tree object */
  130955. RtreeConstraint *pConstraint, /* MATCH constraint to test */
  130956. RtreeCell *pCell, /* Cell to test */
  130957. int *pbRes /* OUT: Test result */
  130958. ){
  130959. int i;
  130960. RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
  130961. int nCoord = pRtree->nDim*2;
  130962. assert( pConstraint->op==RTREE_MATCH );
  130963. assert( pConstraint->pGeom );
  130964. for(i=0; i<nCoord; i++){
  130965. aCoord[i] = DCOORD(pCell->aCoord[i]);
  130966. }
  130967. return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
  130968. }
  130969. /*
  130970. ** Cursor pCursor currently points to a cell in a non-leaf page.
  130971. ** Set *pbEof to true if the sub-tree headed by the cell is filtered
  130972. ** (excluded) by the constraints in the pCursor->aConstraint[]
  130973. ** array, or false otherwise.
  130974. **
  130975. ** Return SQLITE_OK if successful or an SQLite error code if an error
  130976. ** occurs within a geometry callback.
  130977. */
  130978. static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  130979. RtreeCell cell;
  130980. int ii;
  130981. int bRes = 0;
  130982. int rc = SQLITE_OK;
  130983. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  130984. for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
  130985. RtreeConstraint *p = &pCursor->aConstraint[ii];
  130986. RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
  130987. RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
  130988. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  130989. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  130990. );
  130991. switch( p->op ){
  130992. case RTREE_LE: case RTREE_LT:
  130993. bRes = p->rValue<cell_min;
  130994. break;
  130995. case RTREE_GE: case RTREE_GT:
  130996. bRes = p->rValue>cell_max;
  130997. break;
  130998. case RTREE_EQ:
  130999. bRes = (p->rValue>cell_max || p->rValue<cell_min);
  131000. break;
  131001. default: {
  131002. assert( p->op==RTREE_MATCH );
  131003. rc = testRtreeGeom(pRtree, p, &cell, &bRes);
  131004. bRes = !bRes;
  131005. break;
  131006. }
  131007. }
  131008. }
  131009. *pbEof = bRes;
  131010. return rc;
  131011. }
  131012. /*
  131013. ** Test if the cell that cursor pCursor currently points to
  131014. ** would be filtered (excluded) by the constraints in the
  131015. ** pCursor->aConstraint[] array. If so, set *pbEof to true before
  131016. ** returning. If the cell is not filtered (excluded) by the constraints,
  131017. ** set pbEof to zero.
  131018. **
  131019. ** Return SQLITE_OK if successful or an SQLite error code if an error
  131020. ** occurs within a geometry callback.
  131021. **
  131022. ** This function assumes that the cell is part of a leaf node.
  131023. */
  131024. static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  131025. RtreeCell cell;
  131026. int ii;
  131027. *pbEof = 0;
  131028. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  131029. for(ii=0; ii<pCursor->nConstraint; ii++){
  131030. RtreeConstraint *p = &pCursor->aConstraint[ii];
  131031. RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
  131032. int res;
  131033. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  131034. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  131035. );
  131036. switch( p->op ){
  131037. case RTREE_LE: res = (coord<=p->rValue); break;
  131038. case RTREE_LT: res = (coord<p->rValue); break;
  131039. case RTREE_GE: res = (coord>=p->rValue); break;
  131040. case RTREE_GT: res = (coord>p->rValue); break;
  131041. case RTREE_EQ: res = (coord==p->rValue); break;
  131042. default: {
  131043. int rc;
  131044. assert( p->op==RTREE_MATCH );
  131045. rc = testRtreeGeom(pRtree, p, &cell, &res);
  131046. if( rc!=SQLITE_OK ){
  131047. return rc;
  131048. }
  131049. break;
  131050. }
  131051. }
  131052. if( !res ){
  131053. *pbEof = 1;
  131054. return SQLITE_OK;
  131055. }
  131056. }
  131057. return SQLITE_OK;
  131058. }
  131059. /*
  131060. ** Cursor pCursor currently points at a node that heads a sub-tree of
  131061. ** height iHeight (if iHeight==0, then the node is a leaf). Descend
  131062. ** to point to the left-most cell of the sub-tree that matches the
  131063. ** configured constraints.
  131064. */
  131065. static int descendToCell(
  131066. Rtree *pRtree,
  131067. RtreeCursor *pCursor,
  131068. int iHeight,
  131069. int *pEof /* OUT: Set to true if cannot descend */
  131070. ){
  131071. int isEof;
  131072. int rc;
  131073. int ii;
  131074. RtreeNode *pChild;
  131075. sqlite3_int64 iRowid;
  131076. RtreeNode *pSavedNode = pCursor->pNode;
  131077. int iSavedCell = pCursor->iCell;
  131078. assert( iHeight>=0 );
  131079. if( iHeight==0 ){
  131080. rc = testRtreeEntry(pRtree, pCursor, &isEof);
  131081. }else{
  131082. rc = testRtreeCell(pRtree, pCursor, &isEof);
  131083. }
  131084. if( rc!=SQLITE_OK || isEof || iHeight==0 ){
  131085. goto descend_to_cell_out;
  131086. }
  131087. iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
  131088. rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
  131089. if( rc!=SQLITE_OK ){
  131090. goto descend_to_cell_out;
  131091. }
  131092. nodeRelease(pRtree, pCursor->pNode);
  131093. pCursor->pNode = pChild;
  131094. isEof = 1;
  131095. for(ii=0; isEof && ii<NCELL(pChild); ii++){
  131096. pCursor->iCell = ii;
  131097. rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
  131098. if( rc!=SQLITE_OK ){
  131099. goto descend_to_cell_out;
  131100. }
  131101. }
  131102. if( isEof ){
  131103. assert( pCursor->pNode==pChild );
  131104. nodeReference(pSavedNode);
  131105. nodeRelease(pRtree, pChild);
  131106. pCursor->pNode = pSavedNode;
  131107. pCursor->iCell = iSavedCell;
  131108. }
  131109. descend_to_cell_out:
  131110. *pEof = isEof;
  131111. return rc;
  131112. }
  131113. /*
  131114. ** One of the cells in node pNode is guaranteed to have a 64-bit
  131115. ** integer value equal to iRowid. Return the index of this cell.
  131116. */
  131117. static int nodeRowidIndex(
  131118. Rtree *pRtree,
  131119. RtreeNode *pNode,
  131120. i64 iRowid,
  131121. int *piIndex
  131122. ){
  131123. int ii;
  131124. int nCell = NCELL(pNode);
  131125. for(ii=0; ii<nCell; ii++){
  131126. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  131127. *piIndex = ii;
  131128. return SQLITE_OK;
  131129. }
  131130. }
  131131. return SQLITE_CORRUPT_VTAB;
  131132. }
  131133. /*
  131134. ** Return the index of the cell containing a pointer to node pNode
  131135. ** in its parent. If pNode is the root node, return -1.
  131136. */
  131137. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  131138. RtreeNode *pParent = pNode->pParent;
  131139. if( pParent ){
  131140. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  131141. }
  131142. *piIndex = -1;
  131143. return SQLITE_OK;
  131144. }
  131145. /*
  131146. ** Rtree virtual table module xNext method.
  131147. */
  131148. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  131149. Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
  131150. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  131151. int rc = SQLITE_OK;
  131152. /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
  131153. ** already at EOF. It is against the rules to call the xNext() method of
  131154. ** a cursor that has already reached EOF.
  131155. */
  131156. assert( pCsr->pNode );
  131157. if( pCsr->iStrategy==1 ){
  131158. /* This "scan" is a direct lookup by rowid. There is no next entry. */
  131159. nodeRelease(pRtree, pCsr->pNode);
  131160. pCsr->pNode = 0;
  131161. }else{
  131162. /* Move to the next entry that matches the configured constraints. */
  131163. int iHeight = 0;
  131164. while( pCsr->pNode ){
  131165. RtreeNode *pNode = pCsr->pNode;
  131166. int nCell = NCELL(pNode);
  131167. for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
  131168. int isEof;
  131169. rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
  131170. if( rc!=SQLITE_OK || !isEof ){
  131171. return rc;
  131172. }
  131173. }
  131174. pCsr->pNode = pNode->pParent;
  131175. rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
  131176. if( rc!=SQLITE_OK ){
  131177. return rc;
  131178. }
  131179. nodeReference(pCsr->pNode);
  131180. nodeRelease(pRtree, pNode);
  131181. iHeight++;
  131182. }
  131183. }
  131184. return rc;
  131185. }
  131186. /*
  131187. ** Rtree virtual table module xRowid method.
  131188. */
  131189. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  131190. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  131191. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  131192. assert(pCsr->pNode);
  131193. *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  131194. return SQLITE_OK;
  131195. }
  131196. /*
  131197. ** Rtree virtual table module xColumn method.
  131198. */
  131199. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  131200. Rtree *pRtree = (Rtree *)cur->pVtab;
  131201. RtreeCursor *pCsr = (RtreeCursor *)cur;
  131202. if( i==0 ){
  131203. i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  131204. sqlite3_result_int64(ctx, iRowid);
  131205. }else{
  131206. RtreeCoord c;
  131207. nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
  131208. #ifndef SQLITE_RTREE_INT_ONLY
  131209. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  131210. sqlite3_result_double(ctx, c.f);
  131211. }else
  131212. #endif
  131213. {
  131214. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  131215. sqlite3_result_int(ctx, c.i);
  131216. }
  131217. }
  131218. return SQLITE_OK;
  131219. }
  131220. /*
  131221. ** Use nodeAcquire() to obtain the leaf node containing the record with
  131222. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  131223. ** return SQLITE_OK. If there is no such record in the table, set
  131224. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  131225. ** to zero and return an SQLite error code.
  131226. */
  131227. static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
  131228. int rc;
  131229. *ppLeaf = 0;
  131230. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  131231. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  131232. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  131233. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  131234. sqlite3_reset(pRtree->pReadRowid);
  131235. }else{
  131236. rc = sqlite3_reset(pRtree->pReadRowid);
  131237. }
  131238. return rc;
  131239. }
  131240. /*
  131241. ** This function is called to configure the RtreeConstraint object passed
  131242. ** as the second argument for a MATCH constraint. The value passed as the
  131243. ** first argument to this function is the right-hand operand to the MATCH
  131244. ** operator.
  131245. */
  131246. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  131247. RtreeMatchArg *p;
  131248. sqlite3_rtree_geometry *pGeom;
  131249. int nBlob;
  131250. /* Check that value is actually a blob. */
  131251. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  131252. /* Check that the blob is roughly the right size. */
  131253. nBlob = sqlite3_value_bytes(pValue);
  131254. if( nBlob<(int)sizeof(RtreeMatchArg)
  131255. || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
  131256. ){
  131257. return SQLITE_ERROR;
  131258. }
  131259. pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
  131260. sizeof(sqlite3_rtree_geometry) + nBlob
  131261. );
  131262. if( !pGeom ) return SQLITE_NOMEM;
  131263. memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
  131264. p = (RtreeMatchArg *)&pGeom[1];
  131265. memcpy(p, sqlite3_value_blob(pValue), nBlob);
  131266. if( p->magic!=RTREE_GEOMETRY_MAGIC
  131267. || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
  131268. ){
  131269. sqlite3_free(pGeom);
  131270. return SQLITE_ERROR;
  131271. }
  131272. pGeom->pContext = p->pContext;
  131273. pGeom->nParam = p->nParam;
  131274. pGeom->aParam = p->aParam;
  131275. pCons->xGeom = p->xGeom;
  131276. pCons->pGeom = pGeom;
  131277. return SQLITE_OK;
  131278. }
  131279. /*
  131280. ** Rtree virtual table module xFilter method.
  131281. */
  131282. static int rtreeFilter(
  131283. sqlite3_vtab_cursor *pVtabCursor,
  131284. int idxNum, const char *idxStr,
  131285. int argc, sqlite3_value **argv
  131286. ){
  131287. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  131288. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  131289. RtreeNode *pRoot = 0;
  131290. int ii;
  131291. int rc = SQLITE_OK;
  131292. rtreeReference(pRtree);
  131293. freeCursorConstraints(pCsr);
  131294. pCsr->iStrategy = idxNum;
  131295. if( idxNum==1 ){
  131296. /* Special case - lookup by rowid. */
  131297. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  131298. i64 iRowid = sqlite3_value_int64(argv[0]);
  131299. rc = findLeafNode(pRtree, iRowid, &pLeaf);
  131300. pCsr->pNode = pLeaf;
  131301. if( pLeaf ){
  131302. assert( rc==SQLITE_OK );
  131303. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
  131304. }
  131305. }else{
  131306. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  131307. ** with the configured constraints.
  131308. */
  131309. if( argc>0 ){
  131310. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  131311. pCsr->nConstraint = argc;
  131312. if( !pCsr->aConstraint ){
  131313. rc = SQLITE_NOMEM;
  131314. }else{
  131315. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  131316. assert( (idxStr==0 && argc==0)
  131317. || (idxStr && (int)strlen(idxStr)==argc*2) );
  131318. for(ii=0; ii<argc; ii++){
  131319. RtreeConstraint *p = &pCsr->aConstraint[ii];
  131320. p->op = idxStr[ii*2];
  131321. p->iCoord = idxStr[ii*2+1]-'a';
  131322. if( p->op==RTREE_MATCH ){
  131323. /* A MATCH operator. The right-hand-side must be a blob that
  131324. ** can be cast into an RtreeMatchArg object. One created using
  131325. ** an sqlite3_rtree_geometry_callback() SQL user function.
  131326. */
  131327. rc = deserializeGeometry(argv[ii], p);
  131328. if( rc!=SQLITE_OK ){
  131329. break;
  131330. }
  131331. }else{
  131332. #ifdef SQLITE_RTREE_INT_ONLY
  131333. p->rValue = sqlite3_value_int64(argv[ii]);
  131334. #else
  131335. p->rValue = sqlite3_value_double(argv[ii]);
  131336. #endif
  131337. }
  131338. }
  131339. }
  131340. }
  131341. if( rc==SQLITE_OK ){
  131342. pCsr->pNode = 0;
  131343. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  131344. }
  131345. if( rc==SQLITE_OK ){
  131346. int isEof = 1;
  131347. int nCell = NCELL(pRoot);
  131348. pCsr->pNode = pRoot;
  131349. for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
  131350. assert( pCsr->pNode==pRoot );
  131351. rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
  131352. if( !isEof ){
  131353. break;
  131354. }
  131355. }
  131356. if( rc==SQLITE_OK && isEof ){
  131357. assert( pCsr->pNode==pRoot );
  131358. nodeRelease(pRtree, pRoot);
  131359. pCsr->pNode = 0;
  131360. }
  131361. assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
  131362. }
  131363. }
  131364. rtreeRelease(pRtree);
  131365. return rc;
  131366. }
  131367. /*
  131368. ** Rtree virtual table module xBestIndex method. There are three
  131369. ** table scan strategies to choose from (in order from most to
  131370. ** least desirable):
  131371. **
  131372. ** idxNum idxStr Strategy
  131373. ** ------------------------------------------------
  131374. ** 1 Unused Direct lookup by rowid.
  131375. ** 2 See below R-tree query or full-table scan.
  131376. ** ------------------------------------------------
  131377. **
  131378. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  131379. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  131380. ** constraint used. The first two bytes of idxStr correspond to
  131381. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  131382. ** (argvIndex==1) etc.
  131383. **
  131384. ** The first of each pair of bytes in idxStr identifies the constraint
  131385. ** operator as follows:
  131386. **
  131387. ** Operator Byte Value
  131388. ** ----------------------
  131389. ** = 0x41 ('A')
  131390. ** <= 0x42 ('B')
  131391. ** < 0x43 ('C')
  131392. ** >= 0x44 ('D')
  131393. ** > 0x45 ('E')
  131394. ** MATCH 0x46 ('F')
  131395. ** ----------------------
  131396. **
  131397. ** The second of each pair of bytes identifies the coordinate column
  131398. ** to which the constraint applies. The leftmost coordinate column
  131399. ** is 'a', the second from the left 'b' etc.
  131400. */
  131401. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  131402. int rc = SQLITE_OK;
  131403. int ii;
  131404. int iIdx = 0;
  131405. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  131406. memset(zIdxStr, 0, sizeof(zIdxStr));
  131407. UNUSED_PARAMETER(tab);
  131408. assert( pIdxInfo->idxStr==0 );
  131409. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  131410. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  131411. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  131412. /* We have an equality constraint on the rowid. Use strategy 1. */
  131413. int jj;
  131414. for(jj=0; jj<ii; jj++){
  131415. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  131416. pIdxInfo->aConstraintUsage[jj].omit = 0;
  131417. }
  131418. pIdxInfo->idxNum = 1;
  131419. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  131420. pIdxInfo->aConstraintUsage[jj].omit = 1;
  131421. /* This strategy involves a two rowid lookups on an B-Tree structures
  131422. ** and then a linear search of an R-Tree node. This should be
  131423. ** considered almost as quick as a direct rowid lookup (for which
  131424. ** sqlite uses an internal cost of 0.0).
  131425. */
  131426. pIdxInfo->estimatedCost = 10.0;
  131427. return SQLITE_OK;
  131428. }
  131429. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  131430. u8 op;
  131431. switch( p->op ){
  131432. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  131433. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  131434. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  131435. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  131436. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  131437. default:
  131438. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  131439. op = RTREE_MATCH;
  131440. break;
  131441. }
  131442. zIdxStr[iIdx++] = op;
  131443. zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
  131444. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  131445. pIdxInfo->aConstraintUsage[ii].omit = 1;
  131446. }
  131447. }
  131448. pIdxInfo->idxNum = 2;
  131449. pIdxInfo->needToFreeIdxStr = 1;
  131450. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  131451. return SQLITE_NOMEM;
  131452. }
  131453. assert( iIdx>=0 );
  131454. pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
  131455. return rc;
  131456. }
  131457. /*
  131458. ** Return the N-dimensional volumn of the cell stored in *p.
  131459. */
  131460. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  131461. RtreeDValue area = (RtreeDValue)1;
  131462. int ii;
  131463. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  131464. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  131465. }
  131466. return area;
  131467. }
  131468. /*
  131469. ** Return the margin length of cell p. The margin length is the sum
  131470. ** of the objects size in each dimension.
  131471. */
  131472. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  131473. RtreeDValue margin = (RtreeDValue)0;
  131474. int ii;
  131475. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  131476. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  131477. }
  131478. return margin;
  131479. }
  131480. /*
  131481. ** Store the union of cells p1 and p2 in p1.
  131482. */
  131483. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  131484. int ii;
  131485. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  131486. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  131487. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  131488. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  131489. }
  131490. }else{
  131491. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  131492. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  131493. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  131494. }
  131495. }
  131496. }
  131497. /*
  131498. ** Return true if the area covered by p2 is a subset of the area covered
  131499. ** by p1. False otherwise.
  131500. */
  131501. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  131502. int ii;
  131503. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  131504. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  131505. RtreeCoord *a1 = &p1->aCoord[ii];
  131506. RtreeCoord *a2 = &p2->aCoord[ii];
  131507. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  131508. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  131509. ){
  131510. return 0;
  131511. }
  131512. }
  131513. return 1;
  131514. }
  131515. /*
  131516. ** Return the amount cell p would grow by if it were unioned with pCell.
  131517. */
  131518. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  131519. RtreeDValue area;
  131520. RtreeCell cell;
  131521. memcpy(&cell, p, sizeof(RtreeCell));
  131522. area = cellArea(pRtree, &cell);
  131523. cellUnion(pRtree, &cell, pCell);
  131524. return (cellArea(pRtree, &cell)-area);
  131525. }
  131526. #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
  131527. static RtreeDValue cellOverlap(
  131528. Rtree *pRtree,
  131529. RtreeCell *p,
  131530. RtreeCell *aCell,
  131531. int nCell,
  131532. int iExclude
  131533. ){
  131534. int ii;
  131535. RtreeDValue overlap = 0.0;
  131536. for(ii=0; ii<nCell; ii++){
  131537. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  131538. if( ii!=iExclude )
  131539. #else
  131540. assert( iExclude==-1 );
  131541. UNUSED_PARAMETER(iExclude);
  131542. #endif
  131543. {
  131544. int jj;
  131545. RtreeDValue o = (RtreeDValue)1;
  131546. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  131547. RtreeDValue x1, x2;
  131548. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  131549. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  131550. if( x2<x1 ){
  131551. o = 0.0;
  131552. break;
  131553. }else{
  131554. o = o * (x2-x1);
  131555. }
  131556. }
  131557. overlap += o;
  131558. }
  131559. }
  131560. return overlap;
  131561. }
  131562. #endif
  131563. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  131564. static RtreeDValue cellOverlapEnlargement(
  131565. Rtree *pRtree,
  131566. RtreeCell *p,
  131567. RtreeCell *pInsert,
  131568. RtreeCell *aCell,
  131569. int nCell,
  131570. int iExclude
  131571. ){
  131572. RtreeDValue before, after;
  131573. before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  131574. cellUnion(pRtree, p, pInsert);
  131575. after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  131576. return (after-before);
  131577. }
  131578. #endif
  131579. /*
  131580. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  131581. ** ChooseSubTree in r*tree terminology.
  131582. */
  131583. static int ChooseLeaf(
  131584. Rtree *pRtree, /* Rtree table */
  131585. RtreeCell *pCell, /* Cell to insert into rtree */
  131586. int iHeight, /* Height of sub-tree rooted at pCell */
  131587. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  131588. ){
  131589. int rc;
  131590. int ii;
  131591. RtreeNode *pNode;
  131592. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  131593. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  131594. int iCell;
  131595. sqlite3_int64 iBest = 0;
  131596. RtreeDValue fMinGrowth = 0.0;
  131597. RtreeDValue fMinArea = 0.0;
  131598. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  131599. RtreeDValue fMinOverlap = 0.0;
  131600. RtreeDValue overlap;
  131601. #endif
  131602. int nCell = NCELL(pNode);
  131603. RtreeCell cell;
  131604. RtreeNode *pChild;
  131605. RtreeCell *aCell = 0;
  131606. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  131607. if( ii==(pRtree->iDepth-1) ){
  131608. int jj;
  131609. aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
  131610. if( !aCell ){
  131611. rc = SQLITE_NOMEM;
  131612. nodeRelease(pRtree, pNode);
  131613. pNode = 0;
  131614. continue;
  131615. }
  131616. for(jj=0; jj<nCell; jj++){
  131617. nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
  131618. }
  131619. }
  131620. #endif
  131621. /* Select the child node which will be enlarged the least if pCell
  131622. ** is inserted into it. Resolve ties by choosing the entry with
  131623. ** the smallest area.
  131624. */
  131625. for(iCell=0; iCell<nCell; iCell++){
  131626. int bBest = 0;
  131627. RtreeDValue growth;
  131628. RtreeDValue area;
  131629. nodeGetCell(pRtree, pNode, iCell, &cell);
  131630. growth = cellGrowth(pRtree, &cell, pCell);
  131631. area = cellArea(pRtree, &cell);
  131632. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  131633. if( ii==(pRtree->iDepth-1) ){
  131634. overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
  131635. }else{
  131636. overlap = 0.0;
  131637. }
  131638. if( (iCell==0)
  131639. || (overlap<fMinOverlap)
  131640. || (overlap==fMinOverlap && growth<fMinGrowth)
  131641. || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
  131642. ){
  131643. bBest = 1;
  131644. fMinOverlap = overlap;
  131645. }
  131646. #else
  131647. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  131648. bBest = 1;
  131649. }
  131650. #endif
  131651. if( bBest ){
  131652. fMinGrowth = growth;
  131653. fMinArea = area;
  131654. iBest = cell.iRowid;
  131655. }
  131656. }
  131657. sqlite3_free(aCell);
  131658. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  131659. nodeRelease(pRtree, pNode);
  131660. pNode = pChild;
  131661. }
  131662. *ppLeaf = pNode;
  131663. return rc;
  131664. }
  131665. /*
  131666. ** A cell with the same content as pCell has just been inserted into
  131667. ** the node pNode. This function updates the bounding box cells in
  131668. ** all ancestor elements.
  131669. */
  131670. static int AdjustTree(
  131671. Rtree *pRtree, /* Rtree table */
  131672. RtreeNode *pNode, /* Adjust ancestry of this node. */
  131673. RtreeCell *pCell /* This cell was just inserted */
  131674. ){
  131675. RtreeNode *p = pNode;
  131676. while( p->pParent ){
  131677. RtreeNode *pParent = p->pParent;
  131678. RtreeCell cell;
  131679. int iCell;
  131680. if( nodeParentIndex(pRtree, p, &iCell) ){
  131681. return SQLITE_CORRUPT_VTAB;
  131682. }
  131683. nodeGetCell(pRtree, pParent, iCell, &cell);
  131684. if( !cellContains(pRtree, &cell, pCell) ){
  131685. cellUnion(pRtree, &cell, pCell);
  131686. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  131687. }
  131688. p = pParent;
  131689. }
  131690. return SQLITE_OK;
  131691. }
  131692. /*
  131693. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  131694. */
  131695. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  131696. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  131697. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  131698. sqlite3_step(pRtree->pWriteRowid);
  131699. return sqlite3_reset(pRtree->pWriteRowid);
  131700. }
  131701. /*
  131702. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  131703. */
  131704. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  131705. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  131706. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  131707. sqlite3_step(pRtree->pWriteParent);
  131708. return sqlite3_reset(pRtree->pWriteParent);
  131709. }
  131710. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  131711. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  131712. /*
  131713. ** Implementation of the linear variant of the PickNext() function from
  131714. ** Guttman[84].
  131715. */
  131716. static RtreeCell *LinearPickNext(
  131717. Rtree *pRtree,
  131718. RtreeCell *aCell,
  131719. int nCell,
  131720. RtreeCell *pLeftBox,
  131721. RtreeCell *pRightBox,
  131722. int *aiUsed
  131723. ){
  131724. int ii;
  131725. for(ii=0; aiUsed[ii]; ii++);
  131726. aiUsed[ii] = 1;
  131727. return &aCell[ii];
  131728. }
  131729. /*
  131730. ** Implementation of the linear variant of the PickSeeds() function from
  131731. ** Guttman[84].
  131732. */
  131733. static void LinearPickSeeds(
  131734. Rtree *pRtree,
  131735. RtreeCell *aCell,
  131736. int nCell,
  131737. int *piLeftSeed,
  131738. int *piRightSeed
  131739. ){
  131740. int i;
  131741. int iLeftSeed = 0;
  131742. int iRightSeed = 1;
  131743. RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
  131744. /* Pick two "seed" cells from the array of cells. The algorithm used
  131745. ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
  131746. ** indices of the two seed cells in the array are stored in local
  131747. ** variables iLeftSeek and iRightSeed.
  131748. */
  131749. for(i=0; i<pRtree->nDim; i++){
  131750. RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
  131751. RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
  131752. RtreeDValue x3 = x1;
  131753. RtreeDValue x4 = x2;
  131754. int jj;
  131755. int iCellLeft = 0;
  131756. int iCellRight = 0;
  131757. for(jj=1; jj<nCell; jj++){
  131758. RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
  131759. RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
  131760. if( left<x1 ) x1 = left;
  131761. if( right>x4 ) x4 = right;
  131762. if( left>x3 ){
  131763. x3 = left;
  131764. iCellRight = jj;
  131765. }
  131766. if( right<x2 ){
  131767. x2 = right;
  131768. iCellLeft = jj;
  131769. }
  131770. }
  131771. if( x4!=x1 ){
  131772. RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
  131773. if( normalwidth>maxNormalInnerWidth ){
  131774. iLeftSeed = iCellLeft;
  131775. iRightSeed = iCellRight;
  131776. }
  131777. }
  131778. }
  131779. *piLeftSeed = iLeftSeed;
  131780. *piRightSeed = iRightSeed;
  131781. }
  131782. #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
  131783. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  131784. /*
  131785. ** Implementation of the quadratic variant of the PickNext() function from
  131786. ** Guttman[84].
  131787. */
  131788. static RtreeCell *QuadraticPickNext(
  131789. Rtree *pRtree,
  131790. RtreeCell *aCell,
  131791. int nCell,
  131792. RtreeCell *pLeftBox,
  131793. RtreeCell *pRightBox,
  131794. int *aiUsed
  131795. ){
  131796. #define FABS(a) ((a)<0.0?-1.0*(a):(a))
  131797. int iSelect = -1;
  131798. RtreeDValue fDiff;
  131799. int ii;
  131800. for(ii=0; ii<nCell; ii++){
  131801. if( aiUsed[ii]==0 ){
  131802. RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  131803. RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  131804. RtreeDValue diff = FABS(right-left);
  131805. if( iSelect<0 || diff>fDiff ){
  131806. fDiff = diff;
  131807. iSelect = ii;
  131808. }
  131809. }
  131810. }
  131811. aiUsed[iSelect] = 1;
  131812. return &aCell[iSelect];
  131813. }
  131814. /*
  131815. ** Implementation of the quadratic variant of the PickSeeds() function from
  131816. ** Guttman[84].
  131817. */
  131818. static void QuadraticPickSeeds(
  131819. Rtree *pRtree,
  131820. RtreeCell *aCell,
  131821. int nCell,
  131822. int *piLeftSeed,
  131823. int *piRightSeed
  131824. ){
  131825. int ii;
  131826. int jj;
  131827. int iLeftSeed = 0;
  131828. int iRightSeed = 1;
  131829. RtreeDValue fWaste = 0.0;
  131830. for(ii=0; ii<nCell; ii++){
  131831. for(jj=ii+1; jj<nCell; jj++){
  131832. RtreeDValue right = cellArea(pRtree, &aCell[jj]);
  131833. RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
  131834. RtreeDValue waste = growth - right;
  131835. if( waste>fWaste ){
  131836. iLeftSeed = ii;
  131837. iRightSeed = jj;
  131838. fWaste = waste;
  131839. }
  131840. }
  131841. }
  131842. *piLeftSeed = iLeftSeed;
  131843. *piRightSeed = iRightSeed;
  131844. }
  131845. #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
  131846. /*
  131847. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  131848. ** nIdx. The aIdx array contains the set of integers from 0 to
  131849. ** (nIdx-1) in no particular order. This function sorts the values
  131850. ** in aIdx according to the indexed values in aDistance. For
  131851. ** example, assuming the inputs:
  131852. **
  131853. ** aIdx = { 0, 1, 2, 3 }
  131854. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  131855. **
  131856. ** this function sets the aIdx array to contain:
  131857. **
  131858. ** aIdx = { 0, 1, 2, 3 }
  131859. **
  131860. ** The aSpare array is used as temporary working space by the
  131861. ** sorting algorithm.
  131862. */
  131863. static void SortByDistance(
  131864. int *aIdx,
  131865. int nIdx,
  131866. RtreeDValue *aDistance,
  131867. int *aSpare
  131868. ){
  131869. if( nIdx>1 ){
  131870. int iLeft = 0;
  131871. int iRight = 0;
  131872. int nLeft = nIdx/2;
  131873. int nRight = nIdx-nLeft;
  131874. int *aLeft = aIdx;
  131875. int *aRight = &aIdx[nLeft];
  131876. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  131877. SortByDistance(aRight, nRight, aDistance, aSpare);
  131878. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  131879. aLeft = aSpare;
  131880. while( iLeft<nLeft || iRight<nRight ){
  131881. if( iLeft==nLeft ){
  131882. aIdx[iLeft+iRight] = aRight[iRight];
  131883. iRight++;
  131884. }else if( iRight==nRight ){
  131885. aIdx[iLeft+iRight] = aLeft[iLeft];
  131886. iLeft++;
  131887. }else{
  131888. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  131889. RtreeDValue fRight = aDistance[aRight[iRight]];
  131890. if( fLeft<fRight ){
  131891. aIdx[iLeft+iRight] = aLeft[iLeft];
  131892. iLeft++;
  131893. }else{
  131894. aIdx[iLeft+iRight] = aRight[iRight];
  131895. iRight++;
  131896. }
  131897. }
  131898. }
  131899. #if 0
  131900. /* Check that the sort worked */
  131901. {
  131902. int jj;
  131903. for(jj=1; jj<nIdx; jj++){
  131904. RtreeDValue left = aDistance[aIdx[jj-1]];
  131905. RtreeDValue right = aDistance[aIdx[jj]];
  131906. assert( left<=right );
  131907. }
  131908. }
  131909. #endif
  131910. }
  131911. }
  131912. /*
  131913. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  131914. ** nIdx. The aIdx array contains the set of integers from 0 to
  131915. ** (nIdx-1) in no particular order. This function sorts the values
  131916. ** in aIdx according to dimension iDim of the cells in aCell. The
  131917. ** minimum value of dimension iDim is considered first, the
  131918. ** maximum used to break ties.
  131919. **
  131920. ** The aSpare array is used as temporary working space by the
  131921. ** sorting algorithm.
  131922. */
  131923. static void SortByDimension(
  131924. Rtree *pRtree,
  131925. int *aIdx,
  131926. int nIdx,
  131927. int iDim,
  131928. RtreeCell *aCell,
  131929. int *aSpare
  131930. ){
  131931. if( nIdx>1 ){
  131932. int iLeft = 0;
  131933. int iRight = 0;
  131934. int nLeft = nIdx/2;
  131935. int nRight = nIdx-nLeft;
  131936. int *aLeft = aIdx;
  131937. int *aRight = &aIdx[nLeft];
  131938. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  131939. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  131940. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  131941. aLeft = aSpare;
  131942. while( iLeft<nLeft || iRight<nRight ){
  131943. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  131944. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  131945. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  131946. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  131947. if( (iLeft!=nLeft) && ((iRight==nRight)
  131948. || (xleft1<xright1)
  131949. || (xleft1==xright1 && xleft2<xright2)
  131950. )){
  131951. aIdx[iLeft+iRight] = aLeft[iLeft];
  131952. iLeft++;
  131953. }else{
  131954. aIdx[iLeft+iRight] = aRight[iRight];
  131955. iRight++;
  131956. }
  131957. }
  131958. #if 0
  131959. /* Check that the sort worked */
  131960. {
  131961. int jj;
  131962. for(jj=1; jj<nIdx; jj++){
  131963. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  131964. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  131965. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  131966. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  131967. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  131968. }
  131969. }
  131970. #endif
  131971. }
  131972. }
  131973. #if VARIANT_RSTARTREE_SPLIT
  131974. /*
  131975. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  131976. */
  131977. static int splitNodeStartree(
  131978. Rtree *pRtree,
  131979. RtreeCell *aCell,
  131980. int nCell,
  131981. RtreeNode *pLeft,
  131982. RtreeNode *pRight,
  131983. RtreeCell *pBboxLeft,
  131984. RtreeCell *pBboxRight
  131985. ){
  131986. int **aaSorted;
  131987. int *aSpare;
  131988. int ii;
  131989. int iBestDim = 0;
  131990. int iBestSplit = 0;
  131991. RtreeDValue fBestMargin = 0.0;
  131992. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  131993. aaSorted = (int **)sqlite3_malloc(nByte);
  131994. if( !aaSorted ){
  131995. return SQLITE_NOMEM;
  131996. }
  131997. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  131998. memset(aaSorted, 0, nByte);
  131999. for(ii=0; ii<pRtree->nDim; ii++){
  132000. int jj;
  132001. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  132002. for(jj=0; jj<nCell; jj++){
  132003. aaSorted[ii][jj] = jj;
  132004. }
  132005. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  132006. }
  132007. for(ii=0; ii<pRtree->nDim; ii++){
  132008. RtreeDValue margin = 0.0;
  132009. RtreeDValue fBestOverlap = 0.0;
  132010. RtreeDValue fBestArea = 0.0;
  132011. int iBestLeft = 0;
  132012. int nLeft;
  132013. for(
  132014. nLeft=RTREE_MINCELLS(pRtree);
  132015. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  132016. nLeft++
  132017. ){
  132018. RtreeCell left;
  132019. RtreeCell right;
  132020. int kk;
  132021. RtreeDValue overlap;
  132022. RtreeDValue area;
  132023. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  132024. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  132025. for(kk=1; kk<(nCell-1); kk++){
  132026. if( kk<nLeft ){
  132027. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  132028. }else{
  132029. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  132030. }
  132031. }
  132032. margin += cellMargin(pRtree, &left);
  132033. margin += cellMargin(pRtree, &right);
  132034. overlap = cellOverlap(pRtree, &left, &right, 1, -1);
  132035. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  132036. if( (nLeft==RTREE_MINCELLS(pRtree))
  132037. || (overlap<fBestOverlap)
  132038. || (overlap==fBestOverlap && area<fBestArea)
  132039. ){
  132040. iBestLeft = nLeft;
  132041. fBestOverlap = overlap;
  132042. fBestArea = area;
  132043. }
  132044. }
  132045. if( ii==0 || margin<fBestMargin ){
  132046. iBestDim = ii;
  132047. fBestMargin = margin;
  132048. iBestSplit = iBestLeft;
  132049. }
  132050. }
  132051. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  132052. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  132053. for(ii=0; ii<nCell; ii++){
  132054. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  132055. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  132056. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  132057. nodeInsertCell(pRtree, pTarget, pCell);
  132058. cellUnion(pRtree, pBbox, pCell);
  132059. }
  132060. sqlite3_free(aaSorted);
  132061. return SQLITE_OK;
  132062. }
  132063. #endif
  132064. #if VARIANT_GUTTMAN_SPLIT
  132065. /*
  132066. ** Implementation of the regular R-tree SplitNode from Guttman[1984].
  132067. */
  132068. static int splitNodeGuttman(
  132069. Rtree *pRtree,
  132070. RtreeCell *aCell,
  132071. int nCell,
  132072. RtreeNode *pLeft,
  132073. RtreeNode *pRight,
  132074. RtreeCell *pBboxLeft,
  132075. RtreeCell *pBboxRight
  132076. ){
  132077. int iLeftSeed = 0;
  132078. int iRightSeed = 1;
  132079. int *aiUsed;
  132080. int i;
  132081. aiUsed = sqlite3_malloc(sizeof(int)*nCell);
  132082. if( !aiUsed ){
  132083. return SQLITE_NOMEM;
  132084. }
  132085. memset(aiUsed, 0, sizeof(int)*nCell);
  132086. PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
  132087. memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
  132088. memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
  132089. nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
  132090. nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
  132091. aiUsed[iLeftSeed] = 1;
  132092. aiUsed[iRightSeed] = 1;
  132093. for(i=nCell-2; i>0; i--){
  132094. RtreeCell *pNext;
  132095. pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
  132096. RtreeDValue diff =
  132097. cellGrowth(pRtree, pBboxLeft, pNext) -
  132098. cellGrowth(pRtree, pBboxRight, pNext)
  132099. ;
  132100. if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
  132101. || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
  132102. ){
  132103. nodeInsertCell(pRtree, pRight, pNext);
  132104. cellUnion(pRtree, pBboxRight, pNext);
  132105. }else{
  132106. nodeInsertCell(pRtree, pLeft, pNext);
  132107. cellUnion(pRtree, pBboxLeft, pNext);
  132108. }
  132109. }
  132110. sqlite3_free(aiUsed);
  132111. return SQLITE_OK;
  132112. }
  132113. #endif
  132114. static int updateMapping(
  132115. Rtree *pRtree,
  132116. i64 iRowid,
  132117. RtreeNode *pNode,
  132118. int iHeight
  132119. ){
  132120. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  132121. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  132122. if( iHeight>0 ){
  132123. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  132124. if( pChild ){
  132125. nodeRelease(pRtree, pChild->pParent);
  132126. nodeReference(pNode);
  132127. pChild->pParent = pNode;
  132128. }
  132129. }
  132130. return xSetMapping(pRtree, iRowid, pNode->iNode);
  132131. }
  132132. static int SplitNode(
  132133. Rtree *pRtree,
  132134. RtreeNode *pNode,
  132135. RtreeCell *pCell,
  132136. int iHeight
  132137. ){
  132138. int i;
  132139. int newCellIsRight = 0;
  132140. int rc = SQLITE_OK;
  132141. int nCell = NCELL(pNode);
  132142. RtreeCell *aCell;
  132143. int *aiUsed;
  132144. RtreeNode *pLeft = 0;
  132145. RtreeNode *pRight = 0;
  132146. RtreeCell leftbbox;
  132147. RtreeCell rightbbox;
  132148. /* Allocate an array and populate it with a copy of pCell and
  132149. ** all cells from node pLeft. Then zero the original node.
  132150. */
  132151. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  132152. if( !aCell ){
  132153. rc = SQLITE_NOMEM;
  132154. goto splitnode_out;
  132155. }
  132156. aiUsed = (int *)&aCell[nCell+1];
  132157. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  132158. for(i=0; i<nCell; i++){
  132159. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  132160. }
  132161. nodeZero(pRtree, pNode);
  132162. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  132163. nCell++;
  132164. if( pNode->iNode==1 ){
  132165. pRight = nodeNew(pRtree, pNode);
  132166. pLeft = nodeNew(pRtree, pNode);
  132167. pRtree->iDepth++;
  132168. pNode->isDirty = 1;
  132169. writeInt16(pNode->zData, pRtree->iDepth);
  132170. }else{
  132171. pLeft = pNode;
  132172. pRight = nodeNew(pRtree, pLeft->pParent);
  132173. nodeReference(pLeft);
  132174. }
  132175. if( !pLeft || !pRight ){
  132176. rc = SQLITE_NOMEM;
  132177. goto splitnode_out;
  132178. }
  132179. memset(pLeft->zData, 0, pRtree->iNodeSize);
  132180. memset(pRight->zData, 0, pRtree->iNodeSize);
  132181. rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
  132182. if( rc!=SQLITE_OK ){
  132183. goto splitnode_out;
  132184. }
  132185. /* Ensure both child nodes have node numbers assigned to them by calling
  132186. ** nodeWrite(). Node pRight always needs a node number, as it was created
  132187. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  132188. ** In this case avoid the all to nodeWrite().
  132189. */
  132190. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  132191. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  132192. ){
  132193. goto splitnode_out;
  132194. }
  132195. rightbbox.iRowid = pRight->iNode;
  132196. leftbbox.iRowid = pLeft->iNode;
  132197. if( pNode->iNode==1 ){
  132198. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  132199. if( rc!=SQLITE_OK ){
  132200. goto splitnode_out;
  132201. }
  132202. }else{
  132203. RtreeNode *pParent = pLeft->pParent;
  132204. int iCell;
  132205. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  132206. if( rc==SQLITE_OK ){
  132207. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  132208. rc = AdjustTree(pRtree, pParent, &leftbbox);
  132209. }
  132210. if( rc!=SQLITE_OK ){
  132211. goto splitnode_out;
  132212. }
  132213. }
  132214. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  132215. goto splitnode_out;
  132216. }
  132217. for(i=0; i<NCELL(pRight); i++){
  132218. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  132219. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  132220. if( iRowid==pCell->iRowid ){
  132221. newCellIsRight = 1;
  132222. }
  132223. if( rc!=SQLITE_OK ){
  132224. goto splitnode_out;
  132225. }
  132226. }
  132227. if( pNode->iNode==1 ){
  132228. for(i=0; i<NCELL(pLeft); i++){
  132229. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  132230. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  132231. if( rc!=SQLITE_OK ){
  132232. goto splitnode_out;
  132233. }
  132234. }
  132235. }else if( newCellIsRight==0 ){
  132236. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  132237. }
  132238. if( rc==SQLITE_OK ){
  132239. rc = nodeRelease(pRtree, pRight);
  132240. pRight = 0;
  132241. }
  132242. if( rc==SQLITE_OK ){
  132243. rc = nodeRelease(pRtree, pLeft);
  132244. pLeft = 0;
  132245. }
  132246. splitnode_out:
  132247. nodeRelease(pRtree, pRight);
  132248. nodeRelease(pRtree, pLeft);
  132249. sqlite3_free(aCell);
  132250. return rc;
  132251. }
  132252. /*
  132253. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  132254. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  132255. ** the pLeaf->pParent chain all the way up to the root node.
  132256. **
  132257. ** This operation is required when a row is deleted (or updated - an update
  132258. ** is implemented as a delete followed by an insert). SQLite provides the
  132259. ** rowid of the row to delete, which can be used to find the leaf on which
  132260. ** the entry resides (argument pLeaf). Once the leaf is located, this
  132261. ** function is called to determine its ancestry.
  132262. */
  132263. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  132264. int rc = SQLITE_OK;
  132265. RtreeNode *pChild = pLeaf;
  132266. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  132267. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  132268. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  132269. rc = sqlite3_step(pRtree->pReadParent);
  132270. if( rc==SQLITE_ROW ){
  132271. RtreeNode *pTest; /* Used to test for reference loops */
  132272. i64 iNode; /* Node number of parent node */
  132273. /* Before setting pChild->pParent, test that we are not creating a
  132274. ** loop of references (as we would if, say, pChild==pParent). We don't
  132275. ** want to do this as it leads to a memory leak when trying to delete
  132276. ** the referenced counted node structures.
  132277. */
  132278. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  132279. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  132280. if( !pTest ){
  132281. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  132282. }
  132283. }
  132284. rc = sqlite3_reset(pRtree->pReadParent);
  132285. if( rc==SQLITE_OK ) rc = rc2;
  132286. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  132287. pChild = pChild->pParent;
  132288. }
  132289. return rc;
  132290. }
  132291. static int deleteCell(Rtree *, RtreeNode *, int, int);
  132292. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  132293. int rc;
  132294. int rc2;
  132295. RtreeNode *pParent = 0;
  132296. int iCell;
  132297. assert( pNode->nRef==1 );
  132298. /* Remove the entry in the parent cell. */
  132299. rc = nodeParentIndex(pRtree, pNode, &iCell);
  132300. if( rc==SQLITE_OK ){
  132301. pParent = pNode->pParent;
  132302. pNode->pParent = 0;
  132303. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  132304. }
  132305. rc2 = nodeRelease(pRtree, pParent);
  132306. if( rc==SQLITE_OK ){
  132307. rc = rc2;
  132308. }
  132309. if( rc!=SQLITE_OK ){
  132310. return rc;
  132311. }
  132312. /* Remove the xxx_node entry. */
  132313. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  132314. sqlite3_step(pRtree->pDeleteNode);
  132315. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  132316. return rc;
  132317. }
  132318. /* Remove the xxx_parent entry. */
  132319. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  132320. sqlite3_step(pRtree->pDeleteParent);
  132321. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  132322. return rc;
  132323. }
  132324. /* Remove the node from the in-memory hash table and link it into
  132325. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  132326. */
  132327. nodeHashDelete(pRtree, pNode);
  132328. pNode->iNode = iHeight;
  132329. pNode->pNext = pRtree->pDeleted;
  132330. pNode->nRef++;
  132331. pRtree->pDeleted = pNode;
  132332. return SQLITE_OK;
  132333. }
  132334. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  132335. RtreeNode *pParent = pNode->pParent;
  132336. int rc = SQLITE_OK;
  132337. if( pParent ){
  132338. int ii;
  132339. int nCell = NCELL(pNode);
  132340. RtreeCell box; /* Bounding box for pNode */
  132341. nodeGetCell(pRtree, pNode, 0, &box);
  132342. for(ii=1; ii<nCell; ii++){
  132343. RtreeCell cell;
  132344. nodeGetCell(pRtree, pNode, ii, &cell);
  132345. cellUnion(pRtree, &box, &cell);
  132346. }
  132347. box.iRowid = pNode->iNode;
  132348. rc = nodeParentIndex(pRtree, pNode, &ii);
  132349. if( rc==SQLITE_OK ){
  132350. nodeOverwriteCell(pRtree, pParent, &box, ii);
  132351. rc = fixBoundingBox(pRtree, pParent);
  132352. }
  132353. }
  132354. return rc;
  132355. }
  132356. /*
  132357. ** Delete the cell at index iCell of node pNode. After removing the
  132358. ** cell, adjust the r-tree data structure if required.
  132359. */
  132360. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  132361. RtreeNode *pParent;
  132362. int rc;
  132363. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  132364. return rc;
  132365. }
  132366. /* Remove the cell from the node. This call just moves bytes around
  132367. ** the in-memory node image, so it cannot fail.
  132368. */
  132369. nodeDeleteCell(pRtree, pNode, iCell);
  132370. /* If the node is not the tree root and now has less than the minimum
  132371. ** number of cells, remove it from the tree. Otherwise, update the
  132372. ** cell in the parent node so that it tightly contains the updated
  132373. ** node.
  132374. */
  132375. pParent = pNode->pParent;
  132376. assert( pParent || pNode->iNode==1 );
  132377. if( pParent ){
  132378. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  132379. rc = removeNode(pRtree, pNode, iHeight);
  132380. }else{
  132381. rc = fixBoundingBox(pRtree, pNode);
  132382. }
  132383. }
  132384. return rc;
  132385. }
  132386. static int Reinsert(
  132387. Rtree *pRtree,
  132388. RtreeNode *pNode,
  132389. RtreeCell *pCell,
  132390. int iHeight
  132391. ){
  132392. int *aOrder;
  132393. int *aSpare;
  132394. RtreeCell *aCell;
  132395. RtreeDValue *aDistance;
  132396. int nCell;
  132397. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  132398. int iDim;
  132399. int ii;
  132400. int rc = SQLITE_OK;
  132401. int n;
  132402. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  132403. nCell = NCELL(pNode)+1;
  132404. n = (nCell+1)&(~1);
  132405. /* Allocate the buffers used by this operation. The allocation is
  132406. ** relinquished before this function returns.
  132407. */
  132408. aCell = (RtreeCell *)sqlite3_malloc(n * (
  132409. sizeof(RtreeCell) + /* aCell array */
  132410. sizeof(int) + /* aOrder array */
  132411. sizeof(int) + /* aSpare array */
  132412. sizeof(RtreeDValue) /* aDistance array */
  132413. ));
  132414. if( !aCell ){
  132415. return SQLITE_NOMEM;
  132416. }
  132417. aOrder = (int *)&aCell[n];
  132418. aSpare = (int *)&aOrder[n];
  132419. aDistance = (RtreeDValue *)&aSpare[n];
  132420. for(ii=0; ii<nCell; ii++){
  132421. if( ii==(nCell-1) ){
  132422. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  132423. }else{
  132424. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  132425. }
  132426. aOrder[ii] = ii;
  132427. for(iDim=0; iDim<pRtree->nDim; iDim++){
  132428. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  132429. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  132430. }
  132431. }
  132432. for(iDim=0; iDim<pRtree->nDim; iDim++){
  132433. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  132434. }
  132435. for(ii=0; ii<nCell; ii++){
  132436. aDistance[ii] = 0.0;
  132437. for(iDim=0; iDim<pRtree->nDim; iDim++){
  132438. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  132439. DCOORD(aCell[ii].aCoord[iDim*2]));
  132440. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  132441. }
  132442. }
  132443. SortByDistance(aOrder, nCell, aDistance, aSpare);
  132444. nodeZero(pRtree, pNode);
  132445. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  132446. RtreeCell *p = &aCell[aOrder[ii]];
  132447. nodeInsertCell(pRtree, pNode, p);
  132448. if( p->iRowid==pCell->iRowid ){
  132449. if( iHeight==0 ){
  132450. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  132451. }else{
  132452. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  132453. }
  132454. }
  132455. }
  132456. if( rc==SQLITE_OK ){
  132457. rc = fixBoundingBox(pRtree, pNode);
  132458. }
  132459. for(; rc==SQLITE_OK && ii<nCell; ii++){
  132460. /* Find a node to store this cell in. pNode->iNode currently contains
  132461. ** the height of the sub-tree headed by the cell.
  132462. */
  132463. RtreeNode *pInsert;
  132464. RtreeCell *p = &aCell[aOrder[ii]];
  132465. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  132466. if( rc==SQLITE_OK ){
  132467. int rc2;
  132468. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  132469. rc2 = nodeRelease(pRtree, pInsert);
  132470. if( rc==SQLITE_OK ){
  132471. rc = rc2;
  132472. }
  132473. }
  132474. }
  132475. sqlite3_free(aCell);
  132476. return rc;
  132477. }
  132478. /*
  132479. ** Insert cell pCell into node pNode. Node pNode is the head of a
  132480. ** subtree iHeight high (leaf nodes have iHeight==0).
  132481. */
  132482. static int rtreeInsertCell(
  132483. Rtree *pRtree,
  132484. RtreeNode *pNode,
  132485. RtreeCell *pCell,
  132486. int iHeight
  132487. ){
  132488. int rc = SQLITE_OK;
  132489. if( iHeight>0 ){
  132490. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  132491. if( pChild ){
  132492. nodeRelease(pRtree, pChild->pParent);
  132493. nodeReference(pNode);
  132494. pChild->pParent = pNode;
  132495. }
  132496. }
  132497. if( nodeInsertCell(pRtree, pNode, pCell) ){
  132498. #if VARIANT_RSTARTREE_REINSERT
  132499. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  132500. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  132501. }else{
  132502. pRtree->iReinsertHeight = iHeight;
  132503. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  132504. }
  132505. #else
  132506. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  132507. #endif
  132508. }else{
  132509. rc = AdjustTree(pRtree, pNode, pCell);
  132510. if( rc==SQLITE_OK ){
  132511. if( iHeight==0 ){
  132512. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  132513. }else{
  132514. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  132515. }
  132516. }
  132517. }
  132518. return rc;
  132519. }
  132520. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  132521. int ii;
  132522. int rc = SQLITE_OK;
  132523. int nCell = NCELL(pNode);
  132524. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  132525. RtreeNode *pInsert;
  132526. RtreeCell cell;
  132527. nodeGetCell(pRtree, pNode, ii, &cell);
  132528. /* Find a node to store this cell in. pNode->iNode currently contains
  132529. ** the height of the sub-tree headed by the cell.
  132530. */
  132531. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  132532. if( rc==SQLITE_OK ){
  132533. int rc2;
  132534. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  132535. rc2 = nodeRelease(pRtree, pInsert);
  132536. if( rc==SQLITE_OK ){
  132537. rc = rc2;
  132538. }
  132539. }
  132540. }
  132541. return rc;
  132542. }
  132543. /*
  132544. ** Select a currently unused rowid for a new r-tree record.
  132545. */
  132546. static int newRowid(Rtree *pRtree, i64 *piRowid){
  132547. int rc;
  132548. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  132549. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  132550. sqlite3_step(pRtree->pWriteRowid);
  132551. rc = sqlite3_reset(pRtree->pWriteRowid);
  132552. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  132553. return rc;
  132554. }
  132555. /*
  132556. ** Remove the entry with rowid=iDelete from the r-tree structure.
  132557. */
  132558. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  132559. int rc; /* Return code */
  132560. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  132561. int iCell; /* Index of iDelete cell in pLeaf */
  132562. RtreeNode *pRoot; /* Root node of rtree structure */
  132563. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  132564. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  132565. /* Obtain a reference to the leaf node that contains the entry
  132566. ** about to be deleted.
  132567. */
  132568. if( rc==SQLITE_OK ){
  132569. rc = findLeafNode(pRtree, iDelete, &pLeaf);
  132570. }
  132571. /* Delete the cell in question from the leaf node. */
  132572. if( rc==SQLITE_OK ){
  132573. int rc2;
  132574. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  132575. if( rc==SQLITE_OK ){
  132576. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  132577. }
  132578. rc2 = nodeRelease(pRtree, pLeaf);
  132579. if( rc==SQLITE_OK ){
  132580. rc = rc2;
  132581. }
  132582. }
  132583. /* Delete the corresponding entry in the <rtree>_rowid table. */
  132584. if( rc==SQLITE_OK ){
  132585. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  132586. sqlite3_step(pRtree->pDeleteRowid);
  132587. rc = sqlite3_reset(pRtree->pDeleteRowid);
  132588. }
  132589. /* Check if the root node now has exactly one child. If so, remove
  132590. ** it, schedule the contents of the child for reinsertion and
  132591. ** reduce the tree height by one.
  132592. **
  132593. ** This is equivalent to copying the contents of the child into
  132594. ** the root node (the operation that Gutman's paper says to perform
  132595. ** in this scenario).
  132596. */
  132597. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  132598. int rc2;
  132599. RtreeNode *pChild;
  132600. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  132601. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  132602. if( rc==SQLITE_OK ){
  132603. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  132604. }
  132605. rc2 = nodeRelease(pRtree, pChild);
  132606. if( rc==SQLITE_OK ) rc = rc2;
  132607. if( rc==SQLITE_OK ){
  132608. pRtree->iDepth--;
  132609. writeInt16(pRoot->zData, pRtree->iDepth);
  132610. pRoot->isDirty = 1;
  132611. }
  132612. }
  132613. /* Re-insert the contents of any underfull nodes removed from the tree. */
  132614. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  132615. if( rc==SQLITE_OK ){
  132616. rc = reinsertNodeContent(pRtree, pLeaf);
  132617. }
  132618. pRtree->pDeleted = pLeaf->pNext;
  132619. sqlite3_free(pLeaf);
  132620. }
  132621. /* Release the reference to the root node. */
  132622. if( rc==SQLITE_OK ){
  132623. rc = nodeRelease(pRtree, pRoot);
  132624. }else{
  132625. nodeRelease(pRtree, pRoot);
  132626. }
  132627. return rc;
  132628. }
  132629. /*
  132630. ** Rounding constants for float->double conversion.
  132631. */
  132632. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  132633. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  132634. #if !defined(SQLITE_RTREE_INT_ONLY)
  132635. /*
  132636. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  132637. ** while taking care to round toward negative or positive, respectively.
  132638. */
  132639. static RtreeValue rtreeValueDown(sqlite3_value *v){
  132640. double d = sqlite3_value_double(v);
  132641. float f = (float)d;
  132642. if( f>d ){
  132643. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  132644. }
  132645. return f;
  132646. }
  132647. static RtreeValue rtreeValueUp(sqlite3_value *v){
  132648. double d = sqlite3_value_double(v);
  132649. float f = (float)d;
  132650. if( f<d ){
  132651. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  132652. }
  132653. return f;
  132654. }
  132655. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  132656. /*
  132657. ** The xUpdate method for rtree module virtual tables.
  132658. */
  132659. static int rtreeUpdate(
  132660. sqlite3_vtab *pVtab,
  132661. int nData,
  132662. sqlite3_value **azData,
  132663. sqlite_int64 *pRowid
  132664. ){
  132665. Rtree *pRtree = (Rtree *)pVtab;
  132666. int rc = SQLITE_OK;
  132667. RtreeCell cell; /* New cell to insert if nData>1 */
  132668. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  132669. rtreeReference(pRtree);
  132670. assert(nData>=1);
  132671. /* Constraint handling. A write operation on an r-tree table may return
  132672. ** SQLITE_CONSTRAINT for two reasons:
  132673. **
  132674. ** 1. A duplicate rowid value, or
  132675. ** 2. The supplied data violates the "x2>=x1" constraint.
  132676. **
  132677. ** In the first case, if the conflict-handling mode is REPLACE, then
  132678. ** the conflicting row can be removed before proceeding. In the second
  132679. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  132680. ** conflict-handling mode specified by the user.
  132681. */
  132682. if( nData>1 ){
  132683. int ii;
  132684. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  132685. assert( nData==(pRtree->nDim*2 + 3) );
  132686. #ifndef SQLITE_RTREE_INT_ONLY
  132687. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  132688. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  132689. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  132690. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  132691. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  132692. rc = SQLITE_CONSTRAINT;
  132693. goto constraint;
  132694. }
  132695. }
  132696. }else
  132697. #endif
  132698. {
  132699. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  132700. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  132701. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  132702. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  132703. rc = SQLITE_CONSTRAINT;
  132704. goto constraint;
  132705. }
  132706. }
  132707. }
  132708. /* If a rowid value was supplied, check if it is already present in
  132709. ** the table. If so, the constraint has failed. */
  132710. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  132711. cell.iRowid = sqlite3_value_int64(azData[2]);
  132712. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  132713. || sqlite3_value_int64(azData[0])!=cell.iRowid
  132714. ){
  132715. int steprc;
  132716. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  132717. steprc = sqlite3_step(pRtree->pReadRowid);
  132718. rc = sqlite3_reset(pRtree->pReadRowid);
  132719. if( SQLITE_ROW==steprc ){
  132720. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  132721. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  132722. }else{
  132723. rc = SQLITE_CONSTRAINT;
  132724. goto constraint;
  132725. }
  132726. }
  132727. }
  132728. bHaveRowid = 1;
  132729. }
  132730. }
  132731. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  132732. ** record to delete from the r-tree table. The following block does
  132733. ** just that.
  132734. */
  132735. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  132736. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  132737. }
  132738. /* If the azData[] array contains more than one element, elements
  132739. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  132740. ** the r-tree structure.
  132741. */
  132742. if( rc==SQLITE_OK && nData>1 ){
  132743. /* Insert the new record into the r-tree */
  132744. RtreeNode *pLeaf = 0;
  132745. /* Figure out the rowid of the new row. */
  132746. if( bHaveRowid==0 ){
  132747. rc = newRowid(pRtree, &cell.iRowid);
  132748. }
  132749. *pRowid = cell.iRowid;
  132750. if( rc==SQLITE_OK ){
  132751. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  132752. }
  132753. if( rc==SQLITE_OK ){
  132754. int rc2;
  132755. pRtree->iReinsertHeight = -1;
  132756. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  132757. rc2 = nodeRelease(pRtree, pLeaf);
  132758. if( rc==SQLITE_OK ){
  132759. rc = rc2;
  132760. }
  132761. }
  132762. }
  132763. constraint:
  132764. rtreeRelease(pRtree);
  132765. return rc;
  132766. }
  132767. /*
  132768. ** The xRename method for rtree module virtual tables.
  132769. */
  132770. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  132771. Rtree *pRtree = (Rtree *)pVtab;
  132772. int rc = SQLITE_NOMEM;
  132773. char *zSql = sqlite3_mprintf(
  132774. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  132775. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  132776. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  132777. , pRtree->zDb, pRtree->zName, zNewName
  132778. , pRtree->zDb, pRtree->zName, zNewName
  132779. , pRtree->zDb, pRtree->zName, zNewName
  132780. );
  132781. if( zSql ){
  132782. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  132783. sqlite3_free(zSql);
  132784. }
  132785. return rc;
  132786. }
  132787. static sqlite3_module rtreeModule = {
  132788. 0, /* iVersion */
  132789. rtreeCreate, /* xCreate - create a table */
  132790. rtreeConnect, /* xConnect - connect to an existing table */
  132791. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  132792. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  132793. rtreeDestroy, /* xDestroy - Drop a table */
  132794. rtreeOpen, /* xOpen - open a cursor */
  132795. rtreeClose, /* xClose - close a cursor */
  132796. rtreeFilter, /* xFilter - configure scan constraints */
  132797. rtreeNext, /* xNext - advance a cursor */
  132798. rtreeEof, /* xEof */
  132799. rtreeColumn, /* xColumn - read data */
  132800. rtreeRowid, /* xRowid - read data */
  132801. rtreeUpdate, /* xUpdate - write data */
  132802. 0, /* xBegin - begin transaction */
  132803. 0, /* xSync - sync transaction */
  132804. 0, /* xCommit - commit transaction */
  132805. 0, /* xRollback - rollback transaction */
  132806. 0, /* xFindFunction - function overloading */
  132807. rtreeRename, /* xRename - rename the table */
  132808. 0, /* xSavepoint */
  132809. 0, /* xRelease */
  132810. 0 /* xRollbackTo */
  132811. };
  132812. static int rtreeSqlInit(
  132813. Rtree *pRtree,
  132814. sqlite3 *db,
  132815. const char *zDb,
  132816. const char *zPrefix,
  132817. int isCreate
  132818. ){
  132819. int rc = SQLITE_OK;
  132820. #define N_STATEMENT 9
  132821. static const char *azSql[N_STATEMENT] = {
  132822. /* Read and write the xxx_node table */
  132823. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  132824. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  132825. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  132826. /* Read and write the xxx_rowid table */
  132827. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  132828. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  132829. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  132830. /* Read and write the xxx_parent table */
  132831. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  132832. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  132833. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  132834. };
  132835. sqlite3_stmt **appStmt[N_STATEMENT];
  132836. int i;
  132837. pRtree->db = db;
  132838. if( isCreate ){
  132839. char *zCreate = sqlite3_mprintf(
  132840. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  132841. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  132842. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
  132843. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  132844. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  132845. );
  132846. if( !zCreate ){
  132847. return SQLITE_NOMEM;
  132848. }
  132849. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  132850. sqlite3_free(zCreate);
  132851. if( rc!=SQLITE_OK ){
  132852. return rc;
  132853. }
  132854. }
  132855. appStmt[0] = &pRtree->pReadNode;
  132856. appStmt[1] = &pRtree->pWriteNode;
  132857. appStmt[2] = &pRtree->pDeleteNode;
  132858. appStmt[3] = &pRtree->pReadRowid;
  132859. appStmt[4] = &pRtree->pWriteRowid;
  132860. appStmt[5] = &pRtree->pDeleteRowid;
  132861. appStmt[6] = &pRtree->pReadParent;
  132862. appStmt[7] = &pRtree->pWriteParent;
  132863. appStmt[8] = &pRtree->pDeleteParent;
  132864. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  132865. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  132866. if( zSql ){
  132867. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  132868. }else{
  132869. rc = SQLITE_NOMEM;
  132870. }
  132871. sqlite3_free(zSql);
  132872. }
  132873. return rc;
  132874. }
  132875. /*
  132876. ** The second argument to this function contains the text of an SQL statement
  132877. ** that returns a single integer value. The statement is compiled and executed
  132878. ** using database connection db. If successful, the integer value returned
  132879. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  132880. ** code is returned and the value of *piVal after returning is not defined.
  132881. */
  132882. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  132883. int rc = SQLITE_NOMEM;
  132884. if( zSql ){
  132885. sqlite3_stmt *pStmt = 0;
  132886. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  132887. if( rc==SQLITE_OK ){
  132888. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  132889. *piVal = sqlite3_column_int(pStmt, 0);
  132890. }
  132891. rc = sqlite3_finalize(pStmt);
  132892. }
  132893. }
  132894. return rc;
  132895. }
  132896. /*
  132897. ** This function is called from within the xConnect() or xCreate() method to
  132898. ** determine the node-size used by the rtree table being created or connected
  132899. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  132900. ** Otherwise, an SQLite error code is returned.
  132901. **
  132902. ** If this function is being called as part of an xConnect(), then the rtree
  132903. ** table already exists. In this case the node-size is determined by inspecting
  132904. ** the root node of the tree.
  132905. **
  132906. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  132907. ** This ensures that each node is stored on a single database page. If the
  132908. ** database page-size is so large that more than RTREE_MAXCELLS entries
  132909. ** would fit in a single node, use a smaller node-size.
  132910. */
  132911. static int getNodeSize(
  132912. sqlite3 *db, /* Database handle */
  132913. Rtree *pRtree, /* Rtree handle */
  132914. int isCreate, /* True for xCreate, false for xConnect */
  132915. char **pzErr /* OUT: Error message, if any */
  132916. ){
  132917. int rc;
  132918. char *zSql;
  132919. if( isCreate ){
  132920. int iPageSize = 0;
  132921. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  132922. rc = getIntFromStmt(db, zSql, &iPageSize);
  132923. if( rc==SQLITE_OK ){
  132924. pRtree->iNodeSize = iPageSize-64;
  132925. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  132926. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  132927. }
  132928. }else{
  132929. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  132930. }
  132931. }else{
  132932. zSql = sqlite3_mprintf(
  132933. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  132934. pRtree->zDb, pRtree->zName
  132935. );
  132936. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  132937. if( rc!=SQLITE_OK ){
  132938. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  132939. }
  132940. }
  132941. sqlite3_free(zSql);
  132942. return rc;
  132943. }
  132944. /*
  132945. ** This function is the implementation of both the xConnect and xCreate
  132946. ** methods of the r-tree virtual table.
  132947. **
  132948. ** argv[0] -> module name
  132949. ** argv[1] -> database name
  132950. ** argv[2] -> table name
  132951. ** argv[...] -> column names...
  132952. */
  132953. static int rtreeInit(
  132954. sqlite3 *db, /* Database connection */
  132955. void *pAux, /* One of the RTREE_COORD_* constants */
  132956. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  132957. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  132958. char **pzErr, /* OUT: Error message, if any */
  132959. int isCreate /* True for xCreate, false for xConnect */
  132960. ){
  132961. int rc = SQLITE_OK;
  132962. Rtree *pRtree;
  132963. int nDb; /* Length of string argv[1] */
  132964. int nName; /* Length of string argv[2] */
  132965. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  132966. const char *aErrMsg[] = {
  132967. 0, /* 0 */
  132968. "Wrong number of columns for an rtree table", /* 1 */
  132969. "Too few columns for an rtree table", /* 2 */
  132970. "Too many columns for an rtree table" /* 3 */
  132971. };
  132972. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  132973. if( aErrMsg[iErr] ){
  132974. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  132975. return SQLITE_ERROR;
  132976. }
  132977. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  132978. /* Allocate the sqlite3_vtab structure */
  132979. nDb = (int)strlen(argv[1]);
  132980. nName = (int)strlen(argv[2]);
  132981. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  132982. if( !pRtree ){
  132983. return SQLITE_NOMEM;
  132984. }
  132985. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  132986. pRtree->nBusy = 1;
  132987. pRtree->base.pModule = &rtreeModule;
  132988. pRtree->zDb = (char *)&pRtree[1];
  132989. pRtree->zName = &pRtree->zDb[nDb+1];
  132990. pRtree->nDim = (argc-4)/2;
  132991. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  132992. pRtree->eCoordType = eCoordType;
  132993. memcpy(pRtree->zDb, argv[1], nDb);
  132994. memcpy(pRtree->zName, argv[2], nName);
  132995. /* Figure out the node size to use. */
  132996. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  132997. /* Create/Connect to the underlying relational database schema. If
  132998. ** that is successful, call sqlite3_declare_vtab() to configure
  132999. ** the r-tree table schema.
  133000. */
  133001. if( rc==SQLITE_OK ){
  133002. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  133003. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  133004. }else{
  133005. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  133006. char *zTmp;
  133007. int ii;
  133008. for(ii=4; zSql && ii<argc; ii++){
  133009. zTmp = zSql;
  133010. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  133011. sqlite3_free(zTmp);
  133012. }
  133013. if( zSql ){
  133014. zTmp = zSql;
  133015. zSql = sqlite3_mprintf("%s);", zTmp);
  133016. sqlite3_free(zTmp);
  133017. }
  133018. if( !zSql ){
  133019. rc = SQLITE_NOMEM;
  133020. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  133021. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  133022. }
  133023. sqlite3_free(zSql);
  133024. }
  133025. }
  133026. if( rc==SQLITE_OK ){
  133027. *ppVtab = (sqlite3_vtab *)pRtree;
  133028. }else{
  133029. rtreeRelease(pRtree);
  133030. }
  133031. return rc;
  133032. }
  133033. /*
  133034. ** Implementation of a scalar function that decodes r-tree nodes to
  133035. ** human readable strings. This can be used for debugging and analysis.
  133036. **
  133037. ** The scalar function takes two arguments, a blob of data containing
  133038. ** an r-tree node, and the number of dimensions the r-tree indexes.
  133039. ** For a two-dimensional r-tree structure called "rt", to deserialize
  133040. ** all nodes, a statement like:
  133041. **
  133042. ** SELECT rtreenode(2, data) FROM rt_node;
  133043. **
  133044. ** The human readable string takes the form of a Tcl list with one
  133045. ** entry for each cell in the r-tree node. Each entry is itself a
  133046. ** list, containing the 8-byte rowid/pageno followed by the
  133047. ** <num-dimension>*2 coordinates.
  133048. */
  133049. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  133050. char *zText = 0;
  133051. RtreeNode node;
  133052. Rtree tree;
  133053. int ii;
  133054. UNUSED_PARAMETER(nArg);
  133055. memset(&node, 0, sizeof(RtreeNode));
  133056. memset(&tree, 0, sizeof(Rtree));
  133057. tree.nDim = sqlite3_value_int(apArg[0]);
  133058. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  133059. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  133060. for(ii=0; ii<NCELL(&node); ii++){
  133061. char zCell[512];
  133062. int nCell = 0;
  133063. RtreeCell cell;
  133064. int jj;
  133065. nodeGetCell(&tree, &node, ii, &cell);
  133066. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  133067. nCell = (int)strlen(zCell);
  133068. for(jj=0; jj<tree.nDim*2; jj++){
  133069. #ifndef SQLITE_RTREE_INT_ONLY
  133070. sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
  133071. (double)cell.aCoord[jj].f);
  133072. #else
  133073. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  133074. cell.aCoord[jj].i);
  133075. #endif
  133076. nCell = (int)strlen(zCell);
  133077. }
  133078. if( zText ){
  133079. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  133080. sqlite3_free(zText);
  133081. zText = zTextNew;
  133082. }else{
  133083. zText = sqlite3_mprintf("{%s}", zCell);
  133084. }
  133085. }
  133086. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  133087. }
  133088. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  133089. UNUSED_PARAMETER(nArg);
  133090. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  133091. || sqlite3_value_bytes(apArg[0])<2
  133092. ){
  133093. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  133094. }else{
  133095. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  133096. sqlite3_result_int(ctx, readInt16(zBlob));
  133097. }
  133098. }
  133099. /*
  133100. ** Register the r-tree module with database handle db. This creates the
  133101. ** virtual table module "rtree" and the debugging/analysis scalar
  133102. ** function "rtreenode".
  133103. */
  133104. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  133105. const int utf8 = SQLITE_UTF8;
  133106. int rc;
  133107. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  133108. if( rc==SQLITE_OK ){
  133109. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  133110. }
  133111. if( rc==SQLITE_OK ){
  133112. #ifdef SQLITE_RTREE_INT_ONLY
  133113. void *c = (void *)RTREE_COORD_INT32;
  133114. #else
  133115. void *c = (void *)RTREE_COORD_REAL32;
  133116. #endif
  133117. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  133118. }
  133119. if( rc==SQLITE_OK ){
  133120. void *c = (void *)RTREE_COORD_INT32;
  133121. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  133122. }
  133123. return rc;
  133124. }
  133125. /*
  133126. ** A version of sqlite3_free() that can be used as a callback. This is used
  133127. ** in two places - as the destructor for the blob value returned by the
  133128. ** invocation of a geometry function, and as the destructor for the geometry
  133129. ** functions themselves.
  133130. */
  133131. static void doSqlite3Free(void *p){
  133132. sqlite3_free(p);
  133133. }
  133134. /*
  133135. ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
  133136. ** scalar user function. This C function is the callback used for all such
  133137. ** registered SQL functions.
  133138. **
  133139. ** The scalar user functions return a blob that is interpreted by r-tree
  133140. ** table MATCH operators.
  133141. */
  133142. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  133143. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  133144. RtreeMatchArg *pBlob;
  133145. int nBlob;
  133146. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
  133147. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  133148. if( !pBlob ){
  133149. sqlite3_result_error_nomem(ctx);
  133150. }else{
  133151. int i;
  133152. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  133153. pBlob->xGeom = pGeomCtx->xGeom;
  133154. pBlob->pContext = pGeomCtx->pContext;
  133155. pBlob->nParam = nArg;
  133156. for(i=0; i<nArg; i++){
  133157. #ifdef SQLITE_RTREE_INT_ONLY
  133158. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  133159. #else
  133160. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  133161. #endif
  133162. }
  133163. sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
  133164. }
  133165. }
  133166. /*
  133167. ** Register a new geometry function for use with the r-tree MATCH operator.
  133168. */
  133169. SQLITE_API int sqlite3_rtree_geometry_callback(
  133170. sqlite3 *db,
  133171. const char *zGeom,
  133172. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
  133173. void *pContext
  133174. ){
  133175. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  133176. /* Allocate and populate the context object. */
  133177. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  133178. if( !pGeomCtx ) return SQLITE_NOMEM;
  133179. pGeomCtx->xGeom = xGeom;
  133180. pGeomCtx->pContext = pContext;
  133181. /* Create the new user-function. Register a destructor function to delete
  133182. ** the context object when it is no longer required. */
  133183. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  133184. (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
  133185. );
  133186. }
  133187. #if !SQLITE_CORE
  133188. #ifdef _WIN32
  133189. __declspec(dllexport)
  133190. #endif
  133191. SQLITE_API int sqlite3_rtree_init(
  133192. sqlite3 *db,
  133193. char **pzErrMsg,
  133194. const sqlite3_api_routines *pApi
  133195. ){
  133196. SQLITE_EXTENSION_INIT2(pApi)
  133197. return sqlite3RtreeInit(db);
  133198. }
  133199. #endif
  133200. #endif
  133201. /************** End of rtree.c ***********************************************/
  133202. /************** Begin file icu.c *********************************************/
  133203. /*
  133204. ** 2007 May 6
  133205. **
  133206. ** The author disclaims copyright to this source code. In place of
  133207. ** a legal notice, here is a blessing:
  133208. **
  133209. ** May you do good and not evil.
  133210. ** May you find forgiveness for yourself and forgive others.
  133211. ** May you share freely, never taking more than you give.
  133212. **
  133213. *************************************************************************
  133214. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  133215. **
  133216. ** This file implements an integration between the ICU library
  133217. ** ("International Components for Unicode", an open-source library
  133218. ** for handling unicode data) and SQLite. The integration uses
  133219. ** ICU to provide the following to SQLite:
  133220. **
  133221. ** * An implementation of the SQL regexp() function (and hence REGEXP
  133222. ** operator) using the ICU uregex_XX() APIs.
  133223. **
  133224. ** * Implementations of the SQL scalar upper() and lower() functions
  133225. ** for case mapping.
  133226. **
  133227. ** * Integration of ICU and SQLite collation sequences.
  133228. **
  133229. ** * An implementation of the LIKE operator that uses ICU to
  133230. ** provide case-independent matching.
  133231. */
  133232. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  133233. /* Include ICU headers */
  133234. #include <unicode/utypes.h>
  133235. #include <unicode/uregex.h>
  133236. #include <unicode/ustring.h>
  133237. #include <unicode/ucol.h>
  133238. /* #include <assert.h> */
  133239. #ifndef SQLITE_CORE
  133240. SQLITE_EXTENSION_INIT1
  133241. #else
  133242. #endif
  133243. /*
  133244. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  133245. ** operator.
  133246. */
  133247. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  133248. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  133249. #endif
  133250. /*
  133251. ** Version of sqlite3_free() that is always a function, never a macro.
  133252. */
  133253. static void xFree(void *p){
  133254. sqlite3_free(p);
  133255. }
  133256. /*
  133257. ** Compare two UTF-8 strings for equality where the first string is
  133258. ** a "LIKE" expression. Return true (1) if they are the same and
  133259. ** false (0) if they are different.
  133260. */
  133261. static int icuLikeCompare(
  133262. const uint8_t *zPattern, /* LIKE pattern */
  133263. const uint8_t *zString, /* The UTF-8 string to compare against */
  133264. const UChar32 uEsc /* The escape character */
  133265. ){
  133266. static const int MATCH_ONE = (UChar32)'_';
  133267. static const int MATCH_ALL = (UChar32)'%';
  133268. int iPattern = 0; /* Current byte index in zPattern */
  133269. int iString = 0; /* Current byte index in zString */
  133270. int prevEscape = 0; /* True if the previous character was uEsc */
  133271. while( zPattern[iPattern]!=0 ){
  133272. /* Read (and consume) the next character from the input pattern. */
  133273. UChar32 uPattern;
  133274. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  133275. assert(uPattern!=0);
  133276. /* There are now 4 possibilities:
  133277. **
  133278. ** 1. uPattern is an unescaped match-all character "%",
  133279. ** 2. uPattern is an unescaped match-one character "_",
  133280. ** 3. uPattern is an unescaped escape character, or
  133281. ** 4. uPattern is to be handled as an ordinary character
  133282. */
  133283. if( !prevEscape && uPattern==MATCH_ALL ){
  133284. /* Case 1. */
  133285. uint8_t c;
  133286. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  133287. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  133288. ** test string.
  133289. */
  133290. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  133291. if( c==MATCH_ONE ){
  133292. if( zString[iString]==0 ) return 0;
  133293. U8_FWD_1_UNSAFE(zString, iString);
  133294. }
  133295. iPattern++;
  133296. }
  133297. if( zPattern[iPattern]==0 ) return 1;
  133298. while( zString[iString] ){
  133299. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  133300. return 1;
  133301. }
  133302. U8_FWD_1_UNSAFE(zString, iString);
  133303. }
  133304. return 0;
  133305. }else if( !prevEscape && uPattern==MATCH_ONE ){
  133306. /* Case 2. */
  133307. if( zString[iString]==0 ) return 0;
  133308. U8_FWD_1_UNSAFE(zString, iString);
  133309. }else if( !prevEscape && uPattern==uEsc){
  133310. /* Case 3. */
  133311. prevEscape = 1;
  133312. }else{
  133313. /* Case 4. */
  133314. UChar32 uString;
  133315. U8_NEXT_UNSAFE(zString, iString, uString);
  133316. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  133317. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  133318. if( uString!=uPattern ){
  133319. return 0;
  133320. }
  133321. prevEscape = 0;
  133322. }
  133323. }
  133324. return zString[iString]==0;
  133325. }
  133326. /*
  133327. ** Implementation of the like() SQL function. This function implements
  133328. ** the build-in LIKE operator. The first argument to the function is the
  133329. ** pattern and the second argument is the string. So, the SQL statements:
  133330. **
  133331. ** A LIKE B
  133332. **
  133333. ** is implemented as like(B, A). If there is an escape character E,
  133334. **
  133335. ** A LIKE B ESCAPE E
  133336. **
  133337. ** is mapped to like(B, A, E).
  133338. */
  133339. static void icuLikeFunc(
  133340. sqlite3_context *context,
  133341. int argc,
  133342. sqlite3_value **argv
  133343. ){
  133344. const unsigned char *zA = sqlite3_value_text(argv[0]);
  133345. const unsigned char *zB = sqlite3_value_text(argv[1]);
  133346. UChar32 uEsc = 0;
  133347. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  133348. ** of deep recursion and N*N behavior in patternCompare().
  133349. */
  133350. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  133351. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  133352. return;
  133353. }
  133354. if( argc==3 ){
  133355. /* The escape character string must consist of a single UTF-8 character.
  133356. ** Otherwise, return an error.
  133357. */
  133358. int nE= sqlite3_value_bytes(argv[2]);
  133359. const unsigned char *zE = sqlite3_value_text(argv[2]);
  133360. int i = 0;
  133361. if( zE==0 ) return;
  133362. U8_NEXT(zE, i, nE, uEsc);
  133363. if( i!=nE){
  133364. sqlite3_result_error(context,
  133365. "ESCAPE expression must be a single character", -1);
  133366. return;
  133367. }
  133368. }
  133369. if( zA && zB ){
  133370. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  133371. }
  133372. }
  133373. /*
  133374. ** This function is called when an ICU function called from within
  133375. ** the implementation of an SQL scalar function returns an error.
  133376. **
  133377. ** The scalar function context passed as the first argument is
  133378. ** loaded with an error message based on the following two args.
  133379. */
  133380. static void icuFunctionError(
  133381. sqlite3_context *pCtx, /* SQLite scalar function context */
  133382. const char *zName, /* Name of ICU function that failed */
  133383. UErrorCode e /* Error code returned by ICU function */
  133384. ){
  133385. char zBuf[128];
  133386. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  133387. zBuf[127] = '\0';
  133388. sqlite3_result_error(pCtx, zBuf, -1);
  133389. }
  133390. /*
  133391. ** Function to delete compiled regexp objects. Registered as
  133392. ** a destructor function with sqlite3_set_auxdata().
  133393. */
  133394. static void icuRegexpDelete(void *p){
  133395. URegularExpression *pExpr = (URegularExpression *)p;
  133396. uregex_close(pExpr);
  133397. }
  133398. /*
  133399. ** Implementation of SQLite REGEXP operator. This scalar function takes
  133400. ** two arguments. The first is a regular expression pattern to compile
  133401. ** the second is a string to match against that pattern. If either
  133402. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  133403. ** is 1 if the string matches the pattern, or 0 otherwise.
  133404. **
  133405. ** SQLite maps the regexp() function to the regexp() operator such
  133406. ** that the following two are equivalent:
  133407. **
  133408. ** zString REGEXP zPattern
  133409. ** regexp(zPattern, zString)
  133410. **
  133411. ** Uses the following ICU regexp APIs:
  133412. **
  133413. ** uregex_open()
  133414. ** uregex_matches()
  133415. ** uregex_close()
  133416. */
  133417. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  133418. UErrorCode status = U_ZERO_ERROR;
  133419. URegularExpression *pExpr;
  133420. UBool res;
  133421. const UChar *zString = sqlite3_value_text16(apArg[1]);
  133422. (void)nArg; /* Unused parameter */
  133423. /* If the left hand side of the regexp operator is NULL,
  133424. ** then the result is also NULL.
  133425. */
  133426. if( !zString ){
  133427. return;
  133428. }
  133429. pExpr = sqlite3_get_auxdata(p, 0);
  133430. if( !pExpr ){
  133431. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  133432. if( !zPattern ){
  133433. return;
  133434. }
  133435. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  133436. if( U_SUCCESS(status) ){
  133437. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  133438. }else{
  133439. assert(!pExpr);
  133440. icuFunctionError(p, "uregex_open", status);
  133441. return;
  133442. }
  133443. }
  133444. /* Configure the text that the regular expression operates on. */
  133445. uregex_setText(pExpr, zString, -1, &status);
  133446. if( !U_SUCCESS(status) ){
  133447. icuFunctionError(p, "uregex_setText", status);
  133448. return;
  133449. }
  133450. /* Attempt the match */
  133451. res = uregex_matches(pExpr, 0, &status);
  133452. if( !U_SUCCESS(status) ){
  133453. icuFunctionError(p, "uregex_matches", status);
  133454. return;
  133455. }
  133456. /* Set the text that the regular expression operates on to a NULL
  133457. ** pointer. This is not really necessary, but it is tidier than
  133458. ** leaving the regular expression object configured with an invalid
  133459. ** pointer after this function returns.
  133460. */
  133461. uregex_setText(pExpr, 0, 0, &status);
  133462. /* Return 1 or 0. */
  133463. sqlite3_result_int(p, res ? 1 : 0);
  133464. }
  133465. /*
  133466. ** Implementations of scalar functions for case mapping - upper() and
  133467. ** lower(). Function upper() converts its input to upper-case (ABC).
  133468. ** Function lower() converts to lower-case (abc).
  133469. **
  133470. ** ICU provides two types of case mapping, "general" case mapping and
  133471. ** "language specific". Refer to ICU documentation for the differences
  133472. ** between the two.
  133473. **
  133474. ** To utilise "general" case mapping, the upper() or lower() scalar
  133475. ** functions are invoked with one argument:
  133476. **
  133477. ** upper('ABC') -> 'abc'
  133478. ** lower('abc') -> 'ABC'
  133479. **
  133480. ** To access ICU "language specific" case mapping, upper() or lower()
  133481. ** should be invoked with two arguments. The second argument is the name
  133482. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  133483. ** as the second argument is the same as invoking the 1 argument version
  133484. ** of upper() or lower().
  133485. **
  133486. ** lower('I', 'en_us') -> 'i'
  133487. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  133488. **
  133489. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  133490. */
  133491. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  133492. const UChar *zInput;
  133493. UChar *zOutput;
  133494. int nInput;
  133495. int nOutput;
  133496. UErrorCode status = U_ZERO_ERROR;
  133497. const char *zLocale = 0;
  133498. assert(nArg==1 || nArg==2);
  133499. if( nArg==2 ){
  133500. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  133501. }
  133502. zInput = sqlite3_value_text16(apArg[0]);
  133503. if( !zInput ){
  133504. return;
  133505. }
  133506. nInput = sqlite3_value_bytes16(apArg[0]);
  133507. nOutput = nInput * 2 + 2;
  133508. zOutput = sqlite3_malloc(nOutput);
  133509. if( !zOutput ){
  133510. return;
  133511. }
  133512. if( sqlite3_user_data(p) ){
  133513. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  133514. }else{
  133515. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  133516. }
  133517. if( !U_SUCCESS(status) ){
  133518. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  133519. return;
  133520. }
  133521. sqlite3_result_text16(p, zOutput, -1, xFree);
  133522. }
  133523. /*
  133524. ** Collation sequence destructor function. The pCtx argument points to
  133525. ** a UCollator structure previously allocated using ucol_open().
  133526. */
  133527. static void icuCollationDel(void *pCtx){
  133528. UCollator *p = (UCollator *)pCtx;
  133529. ucol_close(p);
  133530. }
  133531. /*
  133532. ** Collation sequence comparison function. The pCtx argument points to
  133533. ** a UCollator structure previously allocated using ucol_open().
  133534. */
  133535. static int icuCollationColl(
  133536. void *pCtx,
  133537. int nLeft,
  133538. const void *zLeft,
  133539. int nRight,
  133540. const void *zRight
  133541. ){
  133542. UCollationResult res;
  133543. UCollator *p = (UCollator *)pCtx;
  133544. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  133545. switch( res ){
  133546. case UCOL_LESS: return -1;
  133547. case UCOL_GREATER: return +1;
  133548. case UCOL_EQUAL: return 0;
  133549. }
  133550. assert(!"Unexpected return value from ucol_strcoll()");
  133551. return 0;
  133552. }
  133553. /*
  133554. ** Implementation of the scalar function icu_load_collation().
  133555. **
  133556. ** This scalar function is used to add ICU collation based collation
  133557. ** types to an SQLite database connection. It is intended to be called
  133558. ** as follows:
  133559. **
  133560. ** SELECT icu_load_collation(<locale>, <collation-name>);
  133561. **
  133562. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  133563. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  133564. ** collation sequence to create.
  133565. */
  133566. static void icuLoadCollation(
  133567. sqlite3_context *p,
  133568. int nArg,
  133569. sqlite3_value **apArg
  133570. ){
  133571. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  133572. UErrorCode status = U_ZERO_ERROR;
  133573. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  133574. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  133575. UCollator *pUCollator; /* ICU library collation object */
  133576. int rc; /* Return code from sqlite3_create_collation_x() */
  133577. assert(nArg==2);
  133578. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  133579. zName = (const char *)sqlite3_value_text(apArg[1]);
  133580. if( !zLocale || !zName ){
  133581. return;
  133582. }
  133583. pUCollator = ucol_open(zLocale, &status);
  133584. if( !U_SUCCESS(status) ){
  133585. icuFunctionError(p, "ucol_open", status);
  133586. return;
  133587. }
  133588. assert(p);
  133589. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  133590. icuCollationColl, icuCollationDel
  133591. );
  133592. if( rc!=SQLITE_OK ){
  133593. ucol_close(pUCollator);
  133594. sqlite3_result_error(p, "Error registering collation function", -1);
  133595. }
  133596. }
  133597. /*
  133598. ** Register the ICU extension functions with database db.
  133599. */
  133600. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  133601. struct IcuScalar {
  133602. const char *zName; /* Function name */
  133603. int nArg; /* Number of arguments */
  133604. int enc; /* Optimal text encoding */
  133605. void *pContext; /* sqlite3_user_data() context */
  133606. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  133607. } scalars[] = {
  133608. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  133609. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  133610. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  133611. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  133612. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  133613. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  133614. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  133615. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  133616. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  133617. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  133618. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  133619. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  133620. };
  133621. int rc = SQLITE_OK;
  133622. int i;
  133623. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  133624. struct IcuScalar *p = &scalars[i];
  133625. rc = sqlite3_create_function(
  133626. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  133627. );
  133628. }
  133629. return rc;
  133630. }
  133631. #if !SQLITE_CORE
  133632. #ifdef _WIN32
  133633. __declspec(dllexport)
  133634. #endif
  133635. SQLITE_API int sqlite3_icu_init(
  133636. sqlite3 *db,
  133637. char **pzErrMsg,
  133638. const sqlite3_api_routines *pApi
  133639. ){
  133640. SQLITE_EXTENSION_INIT2(pApi)
  133641. return sqlite3IcuInit(db);
  133642. }
  133643. #endif
  133644. #endif
  133645. /************** End of icu.c *************************************************/
  133646. /************** Begin file fts3_icu.c ****************************************/
  133647. /*
  133648. ** 2007 June 22
  133649. **
  133650. ** The author disclaims copyright to this source code. In place of
  133651. ** a legal notice, here is a blessing:
  133652. **
  133653. ** May you do good and not evil.
  133654. ** May you find forgiveness for yourself and forgive others.
  133655. ** May you share freely, never taking more than you give.
  133656. **
  133657. *************************************************************************
  133658. ** This file implements a tokenizer for fts3 based on the ICU library.
  133659. */
  133660. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  133661. #ifdef SQLITE_ENABLE_ICU
  133662. /* #include <assert.h> */
  133663. /* #include <string.h> */
  133664. #include <unicode/ubrk.h>
  133665. /* #include <unicode/ucol.h> */
  133666. /* #include <unicode/ustring.h> */
  133667. #include <unicode/utf16.h>
  133668. typedef struct IcuTokenizer IcuTokenizer;
  133669. typedef struct IcuCursor IcuCursor;
  133670. struct IcuTokenizer {
  133671. sqlite3_tokenizer base;
  133672. char *zLocale;
  133673. };
  133674. struct IcuCursor {
  133675. sqlite3_tokenizer_cursor base;
  133676. UBreakIterator *pIter; /* ICU break-iterator object */
  133677. int nChar; /* Number of UChar elements in pInput */
  133678. UChar *aChar; /* Copy of input using utf-16 encoding */
  133679. int *aOffset; /* Offsets of each character in utf-8 input */
  133680. int nBuffer;
  133681. char *zBuffer;
  133682. int iToken;
  133683. };
  133684. /*
  133685. ** Create a new tokenizer instance.
  133686. */
  133687. static int icuCreate(
  133688. int argc, /* Number of entries in argv[] */
  133689. const char * const *argv, /* Tokenizer creation arguments */
  133690. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  133691. ){
  133692. IcuTokenizer *p;
  133693. int n = 0;
  133694. if( argc>0 ){
  133695. n = strlen(argv[0])+1;
  133696. }
  133697. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  133698. if( !p ){
  133699. return SQLITE_NOMEM;
  133700. }
  133701. memset(p, 0, sizeof(IcuTokenizer));
  133702. if( n ){
  133703. p->zLocale = (char *)&p[1];
  133704. memcpy(p->zLocale, argv[0], n);
  133705. }
  133706. *ppTokenizer = (sqlite3_tokenizer *)p;
  133707. return SQLITE_OK;
  133708. }
  133709. /*
  133710. ** Destroy a tokenizer
  133711. */
  133712. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  133713. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  133714. sqlite3_free(p);
  133715. return SQLITE_OK;
  133716. }
  133717. /*
  133718. ** Prepare to begin tokenizing a particular string. The input
  133719. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  133720. ** used to incrementally tokenize this string is returned in
  133721. ** *ppCursor.
  133722. */
  133723. static int icuOpen(
  133724. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  133725. const char *zInput, /* Input string */
  133726. int nInput, /* Length of zInput in bytes */
  133727. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  133728. ){
  133729. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  133730. IcuCursor *pCsr;
  133731. const int32_t opt = U_FOLD_CASE_DEFAULT;
  133732. UErrorCode status = U_ZERO_ERROR;
  133733. int nChar;
  133734. UChar32 c;
  133735. int iInput = 0;
  133736. int iOut = 0;
  133737. *ppCursor = 0;
  133738. if( zInput==0 ){
  133739. nInput = 0;
  133740. zInput = "";
  133741. }else if( nInput<0 ){
  133742. nInput = strlen(zInput);
  133743. }
  133744. nChar = nInput+1;
  133745. pCsr = (IcuCursor *)sqlite3_malloc(
  133746. sizeof(IcuCursor) + /* IcuCursor */
  133747. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  133748. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  133749. );
  133750. if( !pCsr ){
  133751. return SQLITE_NOMEM;
  133752. }
  133753. memset(pCsr, 0, sizeof(IcuCursor));
  133754. pCsr->aChar = (UChar *)&pCsr[1];
  133755. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  133756. pCsr->aOffset[iOut] = iInput;
  133757. U8_NEXT(zInput, iInput, nInput, c);
  133758. while( c>0 ){
  133759. int isError = 0;
  133760. c = u_foldCase(c, opt);
  133761. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  133762. if( isError ){
  133763. sqlite3_free(pCsr);
  133764. return SQLITE_ERROR;
  133765. }
  133766. pCsr->aOffset[iOut] = iInput;
  133767. if( iInput<nInput ){
  133768. U8_NEXT(zInput, iInput, nInput, c);
  133769. }else{
  133770. c = 0;
  133771. }
  133772. }
  133773. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  133774. if( !U_SUCCESS(status) ){
  133775. sqlite3_free(pCsr);
  133776. return SQLITE_ERROR;
  133777. }
  133778. pCsr->nChar = iOut;
  133779. ubrk_first(pCsr->pIter);
  133780. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  133781. return SQLITE_OK;
  133782. }
  133783. /*
  133784. ** Close a tokenization cursor previously opened by a call to icuOpen().
  133785. */
  133786. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  133787. IcuCursor *pCsr = (IcuCursor *)pCursor;
  133788. ubrk_close(pCsr->pIter);
  133789. sqlite3_free(pCsr->zBuffer);
  133790. sqlite3_free(pCsr);
  133791. return SQLITE_OK;
  133792. }
  133793. /*
  133794. ** Extract the next token from a tokenization cursor.
  133795. */
  133796. static int icuNext(
  133797. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  133798. const char **ppToken, /* OUT: *ppToken is the token text */
  133799. int *pnBytes, /* OUT: Number of bytes in token */
  133800. int *piStartOffset, /* OUT: Starting offset of token */
  133801. int *piEndOffset, /* OUT: Ending offset of token */
  133802. int *piPosition /* OUT: Position integer of token */
  133803. ){
  133804. IcuCursor *pCsr = (IcuCursor *)pCursor;
  133805. int iStart = 0;
  133806. int iEnd = 0;
  133807. int nByte = 0;
  133808. while( iStart==iEnd ){
  133809. UChar32 c;
  133810. iStart = ubrk_current(pCsr->pIter);
  133811. iEnd = ubrk_next(pCsr->pIter);
  133812. if( iEnd==UBRK_DONE ){
  133813. return SQLITE_DONE;
  133814. }
  133815. while( iStart<iEnd ){
  133816. int iWhite = iStart;
  133817. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  133818. if( u_isspace(c) ){
  133819. iStart = iWhite;
  133820. }else{
  133821. break;
  133822. }
  133823. }
  133824. assert(iStart<=iEnd);
  133825. }
  133826. do {
  133827. UErrorCode status = U_ZERO_ERROR;
  133828. if( nByte ){
  133829. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  133830. if( !zNew ){
  133831. return SQLITE_NOMEM;
  133832. }
  133833. pCsr->zBuffer = zNew;
  133834. pCsr->nBuffer = nByte;
  133835. }
  133836. u_strToUTF8(
  133837. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  133838. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  133839. &status /* Output success/failure */
  133840. );
  133841. } while( nByte>pCsr->nBuffer );
  133842. *ppToken = pCsr->zBuffer;
  133843. *pnBytes = nByte;
  133844. *piStartOffset = pCsr->aOffset[iStart];
  133845. *piEndOffset = pCsr->aOffset[iEnd];
  133846. *piPosition = pCsr->iToken++;
  133847. return SQLITE_OK;
  133848. }
  133849. /*
  133850. ** The set of routines that implement the simple tokenizer
  133851. */
  133852. static const sqlite3_tokenizer_module icuTokenizerModule = {
  133853. 0, /* iVersion */
  133854. icuCreate, /* xCreate */
  133855. icuDestroy, /* xCreate */
  133856. icuOpen, /* xOpen */
  133857. icuClose, /* xClose */
  133858. icuNext, /* xNext */
  133859. };
  133860. /*
  133861. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  133862. */
  133863. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  133864. sqlite3_tokenizer_module const**ppModule
  133865. ){
  133866. *ppModule = &icuTokenizerModule;
  133867. }
  133868. #endif /* defined(SQLITE_ENABLE_ICU) */
  133869. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  133870. /************** End of fts3_icu.c ********************************************/